private MavenProject mavenProject;
private File resourceBaseDir;
- @Override
- public Collection<File> generateSources(final SchemaContext context, final File outputBaseDir,
- final Set<Module> currentModules) throws IOException {
- return generateSources(context, outputBaseDir, currentModules,
- module -> Optional.of("/" + module.getModuleSourcePath().replace(File.separator, "/")));
- }
-
@Override
public Collection<File> generateSources(final SchemaContext context, final File outputDir,
final Set<Module> yangModules, final Function<Module, Optional<String>> moduleResourcePathResolver)
package org.opendaylight.mdsal.binding.yang.unified.doc.generator
import com.google.common.collect.Iterables
+import com.google.common.collect.Lists
import java.io.BufferedWriter
import java.io.File
import java.io.IOException
import java.io.OutputStreamWriter
import java.nio.charset.StandardCharsets
-import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Collection
import java.util.HashMap
import java.util.LinkedHashMap
import java.util.List
import java.util.Map
+import java.util.Optional
import java.util.Set
import org.opendaylight.yangtools.yang.common.QName
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
+import org.opendaylight.yangtools.yang.model.api.ElementCountConstraintAware
import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition
import org.opendaylight.yangtools.yang.model.api.GroupingDefinition
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode
import org.opendaylight.yangtools.yang.model.api.UsesNode
import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition
import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition
-import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition
+import org.opendaylight.yangtools.yang.model.api.type.Int8TypeDefinition
+import org.opendaylight.yangtools.yang.model.api.type.Int16TypeDefinition
+import org.opendaylight.yangtools.yang.model.api.type.Int32TypeDefinition
+import org.opendaylight.yangtools.yang.model.api.type.Int64TypeDefinition
import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint
import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition
-import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition
+import org.opendaylight.yangtools.yang.model.api.type.Uint8TypeDefinition
+import org.opendaylight.yangtools.yang.model.api.type.Uint16TypeDefinition
+import org.opendaylight.yangtools.yang.model.api.type.Uint32TypeDefinition
+import org.opendaylight.yangtools.yang.model.api.type.Uint64TypeDefinition
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.sonatype.plexus.build.incremental.BuildContext
import org.sonatype.plexus.build.incremental.DefaultBuildContext
-import com.google.common.collect.Lists
class GeneratorImpl {
File path
- static val REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd")
static val Logger LOG = LoggerFactory.getLogger(GeneratorImpl)
static val BuildContext CTX = new DefaultBuildContext();
var Module currentModule;
private def parseTargetPath(SchemaPath path) {
val List<DataSchemaNode> nodes = new ArrayList<DataSchemaNode>();
for (QName pathElement : path.pathFromRoot) {
- val module = ctx.findModuleByNamespaceAndRevision(pathElement.namespace, pathElement.revision);
- if (module !== null) {
- var foundNode = module.getDataChildByName(pathElement)
+ val module = ctx.findModule(pathElement.module)
+ if (module.isPresent) {
+ var foundNode = module.get.getDataChildByName(pathElement)
if (foundNode === null) {
val child = nodes.last
if (child instanceof DataNodeContainer) {
private def CharSequence printAugmentedNode(DataSchemaNode child) {
- if(child instanceof ChoiceCaseNode)
+ if(child instanceof CaseSchemaNode)
return ''
return
}
private def printChoiceNode(ChoiceSchemaNode child) {
- val List<ChoiceCaseNode> cases = new ArrayList(child.cases);
+ val List<CaseSchemaNode> cases = new ArrayList(child.cases.values);
if(!cases.empty) {
- val ChoiceCaseNode aCase = cases.get(0)
+ val CaseSchemaNode aCase = cases.get(0)
for(caseChildNode : aCase.childNodes)
printAugmentedNode(caseChildNode)
}
<td>«module.namespace»</td>
</tr>
<tr>
+ «IF module.revision.isPresent»
<td>«strong("revision")»</td>
- <td>«REVISION_FORMAT.format(module.revision)»</td>
+ <td>«module.revision.get.toString»</td>
+ «ENDIF»
</tr>
<tr>
<td>«strong("description")»</td>
</tr>
<tr>
«FOR imp : module.imports BEFORE '''<td>«strong("imports")»</td><td>''' AFTER '''</td>'''»
- «imp.prefix»:«imp.moduleName»«IF imp.revision !== null» «REVISION_FORMAT.format(imp.revision)»«ENDIF»;
+ «imp.prefix»:«imp.moduleName»«IF imp.revision.isPresent» «imp.revision.get.toString»«ENDIF»;
«ENDFOR»
</tr>
</table>
private def dispatch CharSequence tree(ChoiceSchemaNode node,YangInstanceIdentifier path) '''
«node.nodeName» (choice)
- «casesTree(node.cases,path)»
+ «casesTree(node.cases.values, path)»
'''
- def casesTree(Set<ChoiceCaseNode> nodes,YangInstanceIdentifier path) '''
+ def casesTree(Collection<CaseSchemaNode> nodes, YangInstanceIdentifier path) '''
<ul>
«FOR node : nodes»
<li>
return '''
«printInfo(node, "leaf")»
«listItem("type", typeAnchorLink(node.type?.path, node.type.QName.localName))»
- «listItem("units", node.units)»
- «listItem("default", node.^default)»
+ «listItem("units", node.type.units.orElse(null))»
+ «listItem("default", node.type.defaultValue.map([ Object o | o.toString]).orElse(null))»
</ul>
'''
} else if(node instanceof LeafListSchemaNode) {
} else if(node instanceof ChoiceSchemaNode) {
return '''
«printInfo(node, "choice")»
- «listItem("default case", node.defaultCase)»
- «FOR caseNode : node.cases»
+ «listItem("default case", node.defaultCase.map([ CaseSchemaNode n | n.getQName.localName]).orElse(null))»
+ «FOR caseNode : node.cases.values»
«caseNode.printSchemaNodeInfo»
«ENDFOR»
</ul>
'''
- } else if(node instanceof ChoiceCaseNode) {
+ } else if(node instanceof CaseSchemaNode) {
return '''
«printInfo(node, "case")»
</ul>
«strong(listItem(nodeType, node.QName.localName))»
«ENDIF»
<ul>
- «listItem("description", node.description)»
- «listItem("reference", node.reference)»
+ «listItem("description", node.description.orElse(null))»
+ «listItem("reference", node.reference.orElse(null))»
«IF node instanceof DataSchemaNode»
- «listItem("when condition", node.constraints.whenCondition?.toString)»
- «listItem("min elements", node.constraints.minElements?.toString)»
- «listItem("max elements", node.constraints.maxElements?.toString)»
+ «IF node.whenCondition.present»
+ «listItem("when condition", node.whenCondition.get.toString)»
+ «ENDIF»
+ «ENDIF»
+ «IF node instanceof ElementCountConstraintAware»
+ «IF node.elementCountConstraint.present»
+ «val constraint = node.elementCountConstraint.get»
+ «listItem("min elements", constraint.minElements?.toString)»
+ «listItem("max elements", constraint.maxElements?.toString)»
+ «ENDIF»
«ENDIF»
'''
}
val leafNodes = nodes.filter(LeafSchemaNode)
val leafListNodes = nodes.filter(LeafListSchemaNode)
val choices = nodes.filter(ChoiceSchemaNode)
- val cases = nodes.filter(ChoiceCaseNode)
+ val cases = nodes.filter(CaseSchemaNode)
val containers = nodes.filter(ContainerSchemaNode)
val lists = nodes.filter(ListSchemaNode)
return '''
'''
private def dispatch CharSequence printInfo(ChoiceSchemaNode node, int level, YangInstanceIdentifier path) '''
- «val Set<DataSchemaNode> choiceCases = new HashSet(node.cases)»
- «choiceCases.printChildren(level,path)»
+ «val Set<DataSchemaNode> choiceCases = new HashSet(node.cases.values)»
+ «choiceCases.printChildren(level, path)»
'''
- private def dispatch CharSequence printInfo(ChoiceCaseNode node, int level, YangInstanceIdentifier path) '''
- «node.childNodes.printChildren(level,path)»
+ private def dispatch CharSequence printInfo(CaseSchemaNode node, int level, YangInstanceIdentifier path) '''
+ «node.childNodes.printChildren(level, path)»
'''
<li>«strong((node.QName.localName))» (anyxml)
<ul>
<li>configuration data: «strong(String.valueOf(node.configuration))»</li>
- <li>mandatory: «strong(String.valueOf(node.constraints.mandatory))»</li>
+ <li>mandatory: «strong(String.valueOf(node.mandatory))»</li>
</ul>
</li>
'''
<li>«strong((node.QName.localName))» (leaf)
<ul>
<li>configuration data: «strong(String.valueOf(node.configuration))»</li>
- <li>mandatory: «strong(String.valueOf(node.constraints.mandatory))»</li>
+ <li>mandatory: «strong(String.valueOf(node.mandatory))»</li>
</ul>
</li>
'''
}
val QName qname = path.get(0)
- var Object parent = ctx.findModuleByNamespaceAndRevision(qname.namespace, qname.revision)
+ var Object parent = ctx.findModule(qname.module).orElse(null)
for (name : path) {
if (parent instanceof DataNodeContainer) {
}
}
- val pathElementModule = ctx.findModuleByNamespaceAndRevision(name.namespace, name.revision)
+ val pathElementModule = ctx.findModule(name.module).get
val String moduleName = pathElementModule.name
pathString.append(moduleName)
pathString.append(':')
pathString.append(name.localName)
pathString.append('/')
if(node instanceof ChoiceSchemaNode && dataNode !== null) {
- val DataSchemaNode caseNode = dataNode.childNodes.findFirst[DataSchemaNode e | e instanceof ChoiceCaseNode];
+ val DataSchemaNode caseNode = dataNode.childNodes.findFirst[DataSchemaNode e | e instanceof CaseSchemaNode];
if(caseNode !== null) {
pathString.append("(case)");
pathString.append(caseNode.QName.localName);
}
private def dispatch toLength(BinaryTypeDefinition type) '''
- «type.lengthConstraints.toLengthStmt»
+ «type.lengthConstraint.toLengthStmt»
'''
private def dispatch toLength(StringTypeDefinition type) '''
- «type.lengthConstraints.toLengthStmt»
+ «type.lengthConstraint.toLengthStmt»
'''
private def dispatch toRange(TypeDefinition<?> type) {
}
private def dispatch toRange(DecimalTypeDefinition type) '''
- «type.rangeConstraints.toRangeStmt»
+ «type.rangeConstraint.toRangeStmt»
+ '''
+
+ private def dispatch toRange(Int8TypeDefinition type) '''
+ «type.rangeConstraint.toRangeStmt»
+ '''
+
+ private def dispatch toRange(Int16TypeDefinition type) '''
+ «type.rangeConstraint.toRangeStmt»
+ '''
+
+ private def dispatch toRange(Int32TypeDefinition type) '''
+ «type.rangeConstraint.toRangeStmt»
+ '''
+
+ private def dispatch toRange(Int64TypeDefinition type) '''
+ «type.rangeConstraint.toRangeStmt»
+ '''
+
+ private def dispatch toRange(Uint8TypeDefinition type) '''
+ «type.rangeConstraint.toRangeStmt»
+ '''
+
+ private def dispatch toRange(Uint16TypeDefinition type) '''
+ «type.rangeConstraint.toRangeStmt»
'''
- private def dispatch toRange(IntegerTypeDefinition type) '''
- «type.rangeConstraints.toRangeStmt»
+ private def dispatch toRange(Uint32TypeDefinition type) '''
+ «type.rangeConstraint.toRangeStmt»
'''
- private def dispatch toRange(UnsignedIntegerTypeDefinition type) '''
- «type.rangeConstraints.toRangeStmt»
+ private def dispatch toRange(Uint64TypeDefinition type) '''
+ «type.rangeConstraint.toRangeStmt»
'''
- def toLengthStmt(Collection<LengthConstraint> lengths) '''
- «IF lengths !== null && !lengths.empty»
+ def toLengthStmt(Optional<LengthConstraint> lengths) '''
+ «IF lengths.isPresent»
«listItem("Length restrictions:")»
<ul>
- «FOR length : lengths»
+ «FOR length : lengths.get.allowedRanges.asRanges»
<li>
- «IF length.min == length.max»
- «length.min»
+ «IF length.lowerEndpoint == length.upperEndpoint»
+ «length.lowerEndpoint»
«ELSE»
- <«length.min», «length.max»>
+ <«length.lowerEndpoint», «length.upperEndpoint»>
«ENDIF»
</li>
«ENDFOR»
«ENDIF»
'''
- def toRangeStmt(Collection<RangeConstraint> ranges) '''
- «IF ranges !== null && !ranges.empty»
+ def toRangeStmt(Optional<? extends RangeConstraint<?>> constraint) '''
+ «IF constraint.present»
«listItem("Range restrictions:")»
<ul>
- «FOR range : ranges»
+ «FOR range : constraint.get.allowedRanges.asRanges»
<li>
- «IF range.min == range.max»
- «range.min»
+ «IF range.lowerEndpoint == range.upperEndpoint»
+ «range.lowerEndpoint»
«ELSE»
- <«range.min», «range.max»>
+ <«range.lowerEndpoint», «range.upperEndpoint»>
«ENDIF»
</li>
«ENDFOR»
private def italic(CharSequence str) '''<i>«str»</i>'''
def CharSequence descAndRefLi(SchemaNode node) '''
- «listItem("Description", node.description)»
- «listItem("Reference", node.reference)»
+ «listItem("Description", node.description.orElse(null))»
+ «listItem("Reference", node.reference.orElse(null))»
'''
def CharSequence descAndRef(SchemaNode node) '''
'''
private def String nodeSchemaPathToPath(DataSchemaNode node, Map<SchemaPath, DataSchemaNode> childNodes) {
- if (node instanceof ChoiceSchemaNode || node instanceof ChoiceCaseNode) {
+ if (node instanceof ChoiceSchemaNode || node instanceof CaseSchemaNode) {
return null
}
for (pathElement : path) {
actual.add(pathElement)
val DataSchemaNode nodeByPath = childNodes.get(SchemaPath.create(actual, absolute))
- if (!(nodeByPath instanceof ChoiceSchemaNode) && !(nodeByPath instanceof ChoiceCaseNode)) {
+ if (!(nodeByPath instanceof ChoiceSchemaNode) && !(nodeByPath instanceof CaseSchemaNode)) {
result.append(pathElement.localName)
if (i != path.size - 1) {
result.append('/')
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
+import java.util.function.Function;
import org.opendaylight.mdsal.binding.yang.unified.doc.generator.GeneratorImpl;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
public class DocumentationGeneratorImpl extends GeneratorImpl implements BasicCodeGenerator {
-
- @Override
- public Collection<File> generateSources(final SchemaContext arg0, final File arg1, final Set<Module> arg2)
- throws IOException {
- return generate(arg0, arg1, arg2);
- }
-
@Override
public void setAdditionalConfig(final Map<String, String> additionalConfiguration) {
// no additional config utilized
public void setResourceBaseDir(final File resourceBaseDir) {
// no resource processing necessary
}
+
+ @Override
+ public Collection<File> generateSources(final SchemaContext context, final File outputBaseDir,
+ final Set<Module> currentModules, final Function<Module, Optional<String>> moduleResourcePathResolver)
+ throws IOException {
+ return generate(context, outputBaseDir, currentModules);
+ }
}
private def importsAsNamespaces(Module module) '''
«FOR imprt : module.imports»
- xmlns:«imprt.prefix»="«context.findModuleByName(imprt.moduleName, imprt.revision).namespace»"
+ xmlns:«imprt.prefix»="«context.findModule(imprt.moduleName, imprt.revision).get.namespace»"
«ENDFOR»
'''
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
+import java.util.function.Function;
import org.opendaylight.mdsal.binding.yang.wadl.generator.WadlRestconfGenerator;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
public class WadlGenerator implements BasicCodeGenerator {
-
@Override
- public Collection<File> generateSources(final SchemaContext context, final File outputDir,
- final Set<Module> currentModules) throws IOException {
+ public void setAdditionalConfig(final Map<String, String> additionalConfiguration) {
+ }
+
+ public void setResourceBaseDir(final File resourceBaseDir) {
+ }
- final File outputBaseDir;
- if (outputDir == null) {
+ @Override
+ public Collection<File> generateSources(final SchemaContext context, final File outputBaseDir,
+ final Set<Module> currentModules, final Function<Module, Optional<String>> moduleResourcePathResolver)
+ throws IOException {
+ final File outputDir;
+ if (outputBaseDir == null) {
// FIXME: this hard-codes the destination
- outputBaseDir = new File("target" + File.separator + "generated-sources" + File.separator
+ outputDir = new File("target" + File.separator + "generated-sources" + File.separator
+ "maven-sal-api-gen" + File.separator + "wadl");
} else {
- outputBaseDir = outputDir;
+ outputDir = outputBaseDir;
}
- final WadlRestconfGenerator generator = new WadlRestconfGenerator(outputBaseDir);
+ final WadlRestconfGenerator generator = new WadlRestconfGenerator(outputDir);
return generator.generate(context, currentModules);
}
-
- @Override
- public void setAdditionalConfig(final Map<String, String> additionalConfiguration) {
- }
-
- @Override
- public void setResourceBaseDir(final File resourceBaseDir) {
- }
}
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
@Test
public void testListGeneration() throws Exception {
final List<File> sourceFiles = getSourceFiles("/doc-gen");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final Set<Module> modules = context.getModules();
final BasicCodeGenerator generator = new DocumentationGeneratorImpl();
- Collection<File> generatedFiles = generator.generateSources(context, GENERATOR_OUTPUT_DIR, modules);
+ Collection<File> generatedFiles = generator.generateSources(context, GENERATOR_OUTPUT_DIR, modules,
+ module -> Optional.empty());
assertEquals(4, generatedFiles.size());
}
- private static List<File> getSourceFiles(String path) throws Exception {
+ private static List<File> getSourceFiles(final String path) throws Exception {
final URI resPath = DocGenTest.class.getResource(path).toURI();
final File sourcesDir = new File(resPath);
if (sourcesDir.exists()) {
}
}
- private static void deleteTestDir(File file) {
+ private static void deleteTestDir(final File file) {
if (file.isDirectory()) {
File[] filesToDelete = file.listFiles();
if (filesToDelete != null) {
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import org.junit.Test;
import org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl;
import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
+import org.opendaylight.yangtools.yang.common.YangConstants;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
import org.sonatype.plexus.build.incremental.DefaultBuildContext;
private static void generateTestSources(final String resourceDirPath, final File sourcesOutputDir)
throws Exception {
final List<File> sourceFiles = getSourceFiles(resourceDirPath);
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
CodeGeneratorImpl codegen = new CodeGeneratorImpl();
codegen.setBuildContext(new DefaultBuildContext());
- codegen.generateSources(context, sourcesOutputDir, context.getModules());
+ codegen.generateSources(context, sourcesOutputDir, context.getModules(),
+ module -> Optional.of(resourceDirPath + File.separator + module.getName()
+ + YangConstants.RFC6020_YANG_FILE_EXTENSION));
}
@Test
public void generateTestSourcesWithAdditionalConfig() throws Exception {
final List<File> sourceFiles = getSourceFiles("/yang-module-info");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
CodeGeneratorImpl codegen = new CodeGeneratorImpl();
codegen.setBuildContext(new DefaultBuildContext());
codegen.setResourceBaseDir(null);
codegen.setMavenProject(new MavenProject());
codegen.setAdditionalConfig(ImmutableMap.of("test", "test"));
- Collection<File> files = codegen.generateSources(context, null, context.getModules());
+ Collection<File> files = codegen.generateSources(context, null, context.getModules(),
+ module -> Optional.of(module.getName()));
assertFalse(files.isEmpty());
files.forEach(file -> {
deleteTestDir(file);
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
@Test
public void testListGeneration() throws Exception {
final List<File> sourceFiles = getSourceFiles("/wadl-gen");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final Set<Module> modules = context.getModules();
final BasicCodeGenerator generator = new WadlGenerator();
- Collection<File> generatedWadlFiles = generator.generateSources(context, GENERATOR_OUTPUT_DIR, modules);
+ Collection<File> generatedWadlFiles = generator.generateSources(context, GENERATOR_OUTPUT_DIR, modules,
+ module -> Optional.empty());
assertEquals(3, generatedWadlFiles.size());
- generatedWadlFiles.forEach((file -> assertTrue(file.exists())));
+ generatedWadlFiles.forEach(file -> assertTrue(file.exists()));
}
@Test
public void testListGenerationWithoutPath() throws Exception {
final List<File> sourceFiles = getSourceFiles("/wadl-gen");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final Set<Module> modules = context.getModules();
final BasicCodeGenerator generator = new WadlGenerator();
- Collection<File> generatedWadlFiles = generator.generateSources(context, null, modules);
+ Collection<File> generatedWadlFiles = generator.generateSources(context, null, modules,
+ module -> Optional.empty());
assertEquals(3, generatedWadlFiles.size());
- generatedWadlFiles.forEach((file -> {
+ generatedWadlFiles.forEach(file -> {
deleteTestDir(file);
assertFalse(file.exists());
- }));
+ });
}
- private static List<File> getSourceFiles(String path) throws Exception {
+ private static List<File> getSourceFiles(final String path) throws Exception {
final URI resPath = WadlGenTest.class.getResource(path).toURI();
final File sourcesDir = new File(resPath);
if (sourcesDir.exists()) {
}
}
- private static void deleteTestDir(File file) {
+ private static void deleteTestDir(final File file) {
if (file.isDirectory()) {
File[] filesToDelete = file.listFiles();
if (filesToDelete != null) {
}
@Override
- public void close() throws Exception {
+ public void close() {
domReg.close();
}
};
*/
package org.opendaylight.mdsal.binding.dom.adapter;
-import com.google.common.base.Optional;
+import java.util.Optional;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
UNKNOWN;
static BindingStructuralType from(final DataTreeCandidateNode domChildNode) {
- final Optional<NormalizedNode<?, ?>> dataBased = domChildNode.getDataAfter().or(domChildNode.getDataBefore());
+ Optional<NormalizedNode<?, ?>> dataBased = domChildNode.getDataAfter();
+ if (!dataBased.isPresent()) {
+ dataBased = domChildNode.getDataBefore();
+ }
if (dataBased.isPresent()) {
return from(dataBased.get());
}
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import java.lang.reflect.Method;
-import java.net.URI;
import java.util.AbstractMap.SimpleEntry;
import java.util.Collection;
-import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
private Module getModuleBlocking(final Class<?> modeledClass) {
final QNameModule moduleName = BindingReflections.getQNameModule(modeledClass);
- final URI namespace = moduleName.getNamespace();
- final Date revision = moduleName.getRevision();
BindingRuntimeContext localRuntimeContext = runtimeContext();
Module module = localRuntimeContext == null ? null :
- localRuntimeContext.getSchemaContext().findModuleByNamespaceAndRevision(namespace, revision);
- if (module == null && futureSchema.waitForSchema(namespace,revision)) {
+ localRuntimeContext.getSchemaContext().findModule(moduleName).orElse(null);
+ if (module == null && futureSchema.waitForSchema(moduleName)) {
localRuntimeContext = runtimeContext();
Preconditions.checkState(localRuntimeContext != null, "BindingRuntimeContext is not available.");
- module = localRuntimeContext.getSchemaContext().findModuleByNamespaceAndRevision(namespace, revision);
+ module = localRuntimeContext.getSchemaContext().findModule(moduleName).orElse(null);
}
Preconditions.checkState(module != null, "Schema for %s is not available.", modeledClass);
return module;
import static java.util.Objects.requireNonNull;
import com.google.common.util.concurrent.SettableFuture;
-import java.net.URI;
import java.util.Collection;
import java.util.Collections;
-import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
import org.opendaylight.yangtools.yang.binding.Augmentation;
+import org.opendaylight.yangtools.yang.common.QNameModule;
abstract class FutureSchema implements AutoCloseable {
private static final class Waiting extends FutureSchema {
}
}
- boolean waitForSchema(final URI namespace, final Date revision) {
+ boolean waitForSchema(final QNameModule module) {
return addPostponedOpAndWait(new FutureSchemaPredicate() {
@Override
public boolean test(final BindingRuntimeContext input) {
- return input.getSchemaContext().findModuleByNamespaceAndRevision(namespace, revision) != null;
+ return input.getSchemaContext().findModule(module).isPresent();
}
});
}
*/
package org.opendaylight.mdsal.binding.dom.adapter;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
+import java.util.Optional;
import org.opendaylight.mdsal.binding.api.DataObjectModification;
import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeNode;
import org.opendaylight.yangtools.yang.binding.Augmentation;
@SuppressWarnings("unchecked")
@Override
public <C extends ChildOf<? super T>> Collection<DataObjectModification<C>>
- getModifiedChildren(Class<C> childType) {
+ getModifiedChildren(final Class<C> childType) {
List<DataObjectModification<C>> children = new ArrayList<>();
for (DataObjectModification<? extends DataObject> potential : getModifiedChildren()) {
if (childType.isAssignableFrom(potential.getDataType())) {
package org.opendaylight.mdsal.binding.dom.adapter;
-import com.google.common.base.Optional;
import java.util.Collection;
import java.util.Map;
+import java.util.Optional;
import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.common.QName;
}
@Override
- public Set<? extends Class> getRequiredDelegates() {
+ public Set<? extends Class<?>> getRequiredDelegates() {
return DELEGATES.keySet();
}
@Override
- protected Object createInstance(ClassToInstanceMap delegates) {
+ protected Object createInstance(final ClassToInstanceMap delegates) {
return delegates;
}
}
\ No newline at end of file
import com.google.common.collect.ImmutableMap;
import java.lang.reflect.Method;
import java.net.URI;
-import java.util.Date;
import org.junit.Test;
import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.bi.ba.rpcservice.rev140701.OpendaylightTestRpcServiceService;
final BindingNormalizedNodeCodecRegistry registry = mock(BindingNormalizedNodeCodecRegistry.class);
final Method testMethod = this.getClass().getDeclaredMethod("testMethod");
final SchemaPath schemaPath = SchemaPath.create(true,
- QName.create(QNameModule.create(new URI("tst"), new Date()), "test"));
+ QName.create(QNameModule.create(new URI("tst")), "test"));
final BindingDOMRpcImplementationAdapter adapter =
new BindingDOMRpcImplementationAdapter(registry, OpendaylightTestRpcServiceService.class,
ImmutableMap.of(schemaPath, testMethod), mock(OpendaylightTestRpcServiceService.class));
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableBiMap;
-import com.google.common.collect.Multimaps;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.google.common.util.concurrent.Uninterruptibles;
import java.lang.reflect.Method;
import java.net.URI;
-import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.two.level.list.TopLevelListKey;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.util.AbstractSchemaContext;
static class EmptySchemaContext extends AbstractSchemaContext {
@Override
public Set<Module> getModules() {
- return Collections.emptySet();
+ return ImmutableSet.of();
}
@Override
- protected Map<ModuleIdentifier, String> getIdentifiersToSources() {
- return Collections.emptyMap();
+ protected Map<QNameModule, Module> getModuleMap() {
+ return ImmutableMap.of();
}
@Override
protected SetMultimap<URI, Module> getNamespaceToModules() {
- return Multimaps.forMap(Collections.emptyMap());
+ return ImmutableSetMultimap.of();
}
@Override
protected SetMultimap<String, Module> getNameToModules() {
- return Multimaps.forMap(Collections.emptyMap());
+ return ImmutableSetMultimap.of();
}
}
}
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import com.google.common.base.Optional;
+import java.util.Optional;
import org.junit.Test;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
*/
@Test
public void fromNormalizedNodeTest() throws Exception {
- final SchemaContext schemaCtx = YangParserTestUtils.parseYangSource("/test.yang");
+ final SchemaContext schemaCtx = YangParserTestUtils.parseYangResource("/test.yang");
final NormalizedNode<?, ?> data = prepareData(schemaCtx, 42);
final Entry<InstanceIdentifier<?>, DataObject> fromNormalizedNode = fromNormalizedNode(data, schemaCtx);
*/
@Test
public void fromNormalizedNodeWithAnotherInputDataTest() throws Exception {
- final SchemaContext schemaCtx = YangParserTestUtils.parseYangSource("/test.yang");
+ final SchemaContext schemaCtx = YangParserTestUtils.parseYangResource("/test.yang");
final NormalizedNode<?, ?> data = prepareData(schemaCtx, "42");
final Entry<InstanceIdentifier<?>, DataObject> fromNormalizedNode = fromNormalizedNode(data, schemaCtx);
}
private static Entry<InstanceIdentifier<?>, DataObject> fromNormalizedNode(final NormalizedNode<?, ?> data,
- final SchemaContext schemaCtx) throws Exception {
+ final SchemaContext schemaCtx) {
final DataObjectSerializerGenerator serializerGenerator =
StreamWriterGenerator.create(JavassistUtils.forClassPool(ClassPool.getDefault()));
final BindingNormalizedNodeCodecRegistry codecRegistry =
import com.google.common.collect.ImmutableSet;
import java.net.URI;
-import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
+import org.opendaylight.yangtools.yang.common.QNameModule;
public class FutureSchemaTest {
public void basicTest() throws Exception {
final FutureSchema futureSchema = FutureSchema.create(0, TimeUnit.MICROSECONDS, true);
assertNotNull(futureSchema);
- assertFalse(futureSchema.waitForSchema(new URI("test"), new Date(0)));
+ assertFalse(futureSchema.waitForSchema(QNameModule.create(new URI("test"))));
assertFalse(futureSchema.waitForSchema(ImmutableSet.of()));
assertEquals(0, futureSchema.getDuration());
assertEquals(TimeUnit.MICROSECONDS, futureSchema.getUnit());
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import com.google.common.base.Optional;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.util.concurrent.MoreExecutors;
+import java.util.Optional;
import org.junit.Test;
import org.opendaylight.mdsal.binding.dom.adapter.test.util.BindingBrokerTestFactory;
import org.opendaylight.mdsal.binding.dom.adapter.test.util.BindingTestContext;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.RpcEffectiveStatementImpl;
public class LazySerializedContainerNodeTest {
final BindingNormalizedNodeCodecRegistry codec = mock(BindingNormalizedNodeCodecRegistry.class);
final ContainerNode containerNode = mock(ContainerNode.class);
doReturn(containerNode).when(codec).toNormalizedNodeRpcData(any());
- doReturn(Optional.absent()).when(containerNode).getChild(any());
+ doReturn(Optional.empty()).when(containerNode).getChild(any());
final BindingBrokerTestFactory bindingBrokerTestFactory = new BindingBrokerTestFactory();
bindingBrokerTestFactory.setExecutor(MoreExecutors.newDirectExecutorService());
final ImmutableBiMap<?, ?> biMap =
bindingTestContext.getCodec().getRpcMethodToSchema(OpendaylightTestRpcServiceService.class);
- rpcName = ((RpcEffectiveStatementImpl) biMap.values().iterator().next()).getPath();
+ rpcName = ((RpcDefinition) biMap.values().iterator().next()).getPath();
final LeafNode<?> leafNode = ImmutableLeafNodeBuilder.create().withNodeIdentifier(NodeIdentifier
- .create(QName.create("test"))).build();
+ .create(QName.create("", "test"))).withValue("").build();
final NormalizedNode<?, ?> normalizedNode = LazySerializedContainerNode.create(rpcName, dataObject, codec);
assertNotNull(normalizedNode);
final LazySerializedContainerNode lazySerializedContainerNode =
import org.opendaylight.mdsal.binding.api.ReadTransaction;
import org.opendaylight.mdsal.binding.api.WriteTransaction;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.BigIntContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.BigIntContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.BigUintContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.BigUintContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.BinaryContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.BinaryContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.BitsContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.BitsContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.BooleanContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.BooleanContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.DecimalContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.DecimalContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.EnumContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.EnumContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.IdentityrefContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.IdentityrefContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.NormalIntContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.NormalIntContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.NormalUintContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.NormalUintContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.SmallIntContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.SmallIntContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.SmallUintContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.SmallUintContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.StringContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.StringContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.TinyIntContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.TinyIntContainerBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.TinyUintContainer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.rev700101.TinyUintContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.BigIntContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.BigIntContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.BigUintContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.BigUintContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.BinaryContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.BinaryContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.BitsContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.BitsContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.BooleanContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.BooleanContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.DecimalContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.DecimalContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.EnumContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.EnumContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.IdentityrefContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.IdentityrefContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.NormalIntContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.NormalIntContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.NormalUintContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.NormalUintContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.SmallIntContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.SmallIntContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.SmallUintContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.SmallUintContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.StringContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.StringContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.TinyIntContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.TinyIntContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.TinyUintContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns._default.value.test.norev.TinyUintContainerBuilder;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
public class LeafDefaultValueTest extends AbstractDataBrokerTest {
@Override
@SuppressWarnings("checkstyle:illegalCatch")
- public void close() throws Exception {
+ public void close() {
try {
inner.close();
} finally {
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verifyNotNull;
-import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.ListenableFuture;
import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.mdsal.binding.dom.codec.osgi.BindingRuntimeContextListener;
import org.opendaylight.mdsal.binding.dom.codec.osgi.BindingRuntimeContextService;
import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
}
@Override
- public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(
- final SourceIdentifier sourceIdentifier) {
+ public ListenableFuture<? extends YangTextSchemaSource> getSource(final SourceIdentifier sourceIdentifier) {
return sourceProvider.getSource(sourceIdentifier);
}
import org.opendaylight.yangtools.yang.binding.DataObjectSerializerImplementation;
import org.opendaylight.yangtools.yang.binding.DataObjectSerializerRegistry;
import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
} else {
source = generateMapEntrySerializer(generatedType, casted);
}
- } else if (schema instanceof AugmentationSchema) {
- source = generateSerializer(generatedType,(AugmentationSchema) schema);
- } else if (schema instanceof ChoiceCaseNode) {
- source = generateCaseSerializer(generatedType,(ChoiceCaseNode) schema);
+ } else if (schema instanceof AugmentationSchemaNode) {
+ source = generateSerializer(generatedType,(AugmentationSchemaNode) schema);
+ } else if (schema instanceof CaseSchemaNode) {
+ source = generateCaseSerializer(generatedType,(CaseSchemaNode) schema);
} else if (schema instanceof NotificationDefinition) {
source = generateNotificationSerializer(generatedType,(NotificationDefinition) schema);
} else {
* @param node Schema of case
* @return Source for case node writer
*/
- protected abstract DataObjectSerializerSource generateCaseSerializer(GeneratedType type, ChoiceCaseNode node);
+ protected abstract DataObjectSerializerSource generateCaseSerializer(GeneratedType type, CaseSchemaNode node);
/**
* Generates serializer source for supplied list node, which will read supplied binding type and invoke proper
* @param schema Schema of augmentation
* @return Source for augmentation node writer
*/
- protected abstract DataObjectSerializerSource generateSerializer(GeneratedType type, AugmentationSchema schema);
+ protected abstract DataObjectSerializerSource generateSerializer(GeneratedType type, AugmentationSchemaNode schema);
/**
* Generates serializer source for notification node, which will read supplied binding type and invoke proper
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
import org.slf4j.Logger;
private static String getGetterName(final DataSchemaNode node) {
final TypeDefinition<?> type;
- if (node instanceof TypedSchemaNode) {
- type = ((TypedSchemaNode) node).getType();
+ if (node instanceof TypedDataSchemaNode) {
+ type = ((TypedDataSchemaNode) node).getType();
} else {
type = null;
}
import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.DataObjectSerializerImplementation;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
}
@Override
- protected DataObjectSerializerSource generateCaseSerializer(final GeneratedType type, final ChoiceCaseNode node) {
+ protected DataObjectSerializerSource generateCaseSerializer(final GeneratedType type, final CaseSchemaNode node) {
return new AugmentableDataNodeContainerEmitterSource(this, type, node) {
@Override
public CharSequence emitStartEvent() {
@Override
protected DataObjectSerializerSource generateSerializer(final GeneratedType type,
- final AugmentationSchema schema) {
+ final AugmentationSchemaNode schema) {
return new DataNodeContainerSerializerSource(this, type, schema) {
@Override
public CharSequence emitStartEvent() {
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
final class AugmentationNodeContext<D extends DataObject & Augmentation<?>>
- extends DataObjectCodecContext<D, AugmentationSchema> {
+ extends DataObjectCodecContext<D, AugmentationSchemaNode> {
- AugmentationNodeContext(final DataContainerCodecPrototype<AugmentationSchema> prototype) {
+ AugmentationNodeContext(final DataContainerCodecPrototype<AugmentationSchemaNode> prototype) {
super(prototype);
}
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
final DataNodeContainer childSchema) {
final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
- if (leaf instanceof TypedSchemaNode) {
- getterToLeafSchema.put(getGetterName(leaf.getQName(), ((TypedSchemaNode) leaf).getType()), leaf);
+ if (leaf instanceof TypedDataSchemaNode) {
+ getterToLeafSchema.put(getGetterName(leaf.getQName(), ((TypedDataSchemaNode) leaf).getType()), leaf);
}
}
return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
}
private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
- Preconditions.checkArgument(schema instanceof TypedSchemaNode, "Unsupported leaf node type %s", schema);
+ Preconditions.checkArgument(schema instanceof TypedDataSchemaNode, "Unsupported leaf node type %s", schema);
- return getCodec(valueType, ((TypedSchemaNode)schema).getType());
+ return getCodec(valueType, ((TypedDataSchemaNode)schema).getType());
}
Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
-final class CaseNodeCodecContext<D extends DataObject> extends DataObjectCodecContext<D,ChoiceCaseNode> {
- CaseNodeCodecContext(final DataContainerCodecPrototype<ChoiceCaseNode> prototype) {
+final class CaseNodeCodecContext<D extends DataObject> extends DataObjectCodecContext<D, CaseSchemaNode> {
+ CaseNodeCodecContext(final DataContainerCodecPrototype<CaseSchemaNode> prototype) {
super(prototype);
}
Preconditions.checkArgument(arg == null);
return null;
}
-}
\ No newline at end of file
+}
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D,ChoiceSchemaNode> {
+final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D, ChoiceSchemaNode> {
private static final Logger LOG = LoggerFactory.getLogger(ChoiceNodeCodecContext.class);
private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChild;
private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byClass;
for (final Class<?> caze : factory().getRuntimeContext().getCases(getBindingClass())) {
// We try to load case using exact match thus name
// and original schema must equals
- final DataContainerCodecPrototype<ChoiceCaseNode> cazeDef = loadCase(caze);
+ final DataContainerCodecPrototype<CaseSchemaNode> cazeDef = loadCase(caze);
// If we have case definition, this case is instantiated
// at current location and thus is valid in context of parent choice
if (cazeDef != null) {
// Updates collection of YANG instance identifier to case
for (final DataSchemaNode cazeChild : cazeDef.getSchema().getChildNodes()) {
if (cazeChild.isAugmenting()) {
- final AugmentationSchema augment = SchemaUtils.findCorrespondingAugment(cazeDef.getSchema(),
+ final AugmentationSchemaNode augment = SchemaUtils.findCorrespondingAugment(cazeDef.getSchema(),
cazeChild);
if (augment != null) {
byYangCaseChildBuilder.put(SchemaUtils.getNodeIdentifierForAugmentation(augment), cazeDef);
return byCaseChildClass.keySet();
}
- protected DataContainerCodecPrototype<ChoiceCaseNode> loadCase(final Class<?> childClass) {
- final Optional<ChoiceCaseNode> childSchema = factory().getRuntimeContext().getCaseSchemaDefinition(getSchema(),
+ protected DataContainerCodecPrototype<CaseSchemaNode> loadCase(final Class<?> childClass) {
+ final Optional<CaseSchemaNode> childSchema = factory().getRuntimeContext().getCaseSchemaDefinition(getSchema(),
childClass);
if (childSchema.isPresent()) {
return DataContainerCodecPrototype.from(childClass, childSchema.get(), factory());
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@SuppressWarnings({ "rawtypes", "unchecked" })
static DataContainerCodecPrototype<?> from(final Class<?> augClass, final AugmentationIdentifier arg,
- final AugmentationSchema schema, final CodecContextFactory factory) {
+ final AugmentationSchemaNode schema, final CodecContextFactory factory) {
return new DataContainerCodecPrototype(augClass, arg, schema, factory);
}
}
} else if (schema instanceof ChoiceSchemaNode) {
return new ChoiceNodeCodecContext(this);
- } else if (schema instanceof AugmentationSchema) {
+ } else if (schema instanceof AugmentationSchemaNode) {
return new AugmentationNodeContext(this);
- } else if (schema instanceof ChoiceCaseNode) {
+ } else if (schema instanceof CaseSchemaNode) {
return new CaseNodeCodecContext(this);
}
throw new IllegalArgumentException("Unsupported type " + bindingClass + " " + schema);
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
}
@SuppressWarnings("unchecked")
- final Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
+ final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
.getResolvedAugmentationSchema(getSchema(), augClass);
return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
}
Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
final NodeCodecContext<?> childContext = byMethod.get(method).get();
@SuppressWarnings("unchecked")
- final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
+ final java.util.Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
if (domChild.isPresent()) {
return childContext.deserializeObject(domChild.get());
} else if (childContext instanceof LeafNodeCodecContext) {
}
}
for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
- final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
+ final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
if (augData.isPresent()) {
map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
}
@SuppressWarnings({"unchecked","rawtypes"})
final Optional<DataContainerCodecContext<?, ?>> augCtx = context.possibleStreamChild((Class) cls);
if (augCtx.isPresent()) {
- final Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.get().getDomPathArgument());
+ final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.get().getDomPathArgument());
if (augData.isPresent()) {
return augCtx.get().deserialize(augData.get());
}
private static Object createDefaultObject(final DataSchemaNode schema, final Codec<Object, Object> codec,
final SchemaContext schemaContext) {
if (schema instanceof LeafSchemaNode) {
- Object defaultValue = ((LeafSchemaNode) schema).getDefault();
+ java.util.Optional<? extends Object> defaultValue = ((LeafSchemaNode) schema).getType().getDefaultValue();
TypeDefinition<?> type = ((LeafSchemaNode) schema).getType();
- if (defaultValue != null) {
+ if (defaultValue.isPresent()) {
if (type instanceof IdentityrefTypeDefinition) {
- return qnameDomValueFromString(codec, schema, (String) defaultValue, schemaContext);
+ return qnameDomValueFromString(codec, schema, (String) defaultValue.get(), schemaContext);
}
- return domValueFromString(codec, type, defaultValue);
+ return domValueFromString(codec, type, defaultValue.get());
}
- while (type.getBaseType() != null && type.getDefaultValue() == null) {
+ while (type.getBaseType() != null && !type.getDefaultValue().isPresent()) {
type = type.getBaseType();
}
defaultValue = type.getDefaultValue();
- if (defaultValue != null) {
+ if (defaultValue.isPresent()) {
if (type instanceof IdentityrefTypeDefinition) {
- return qnameDomValueFromString(codec, schema, (String) defaultValue, schemaContext);
+ return qnameDomValueFromString(codec, schema, (String) defaultValue.get(), schemaContext);
}
return domValueFromString(codec, type, defaultValue);
}
if (prefixEndIndex != -1) {
String defaultValuePrefix = defaultValue.substring(0, prefixEndIndex);
- Module module = schemaContext.findModuleByNamespaceAndRevision(schema.getQName().getNamespace(),
- schema.getQName().getRevision());
-
+ Module module = schemaContext.findModule(schema.getQName().getModule()).get();
if (module.getPrefix().equals(defaultValuePrefix)) {
qname = QName.create(module.getQNameModule(), defaultValue.substring(prefixEndIndex + 1));
return codec.deserialize(qname);
Set<ModuleImport> imports = module.getImports();
for (ModuleImport moduleImport : imports) {
if (moduleImport.getPrefix().equals(defaultValuePrefix)) {
- Module importedModule = schemaContext.findModuleByName(moduleImport.getModuleName(),
- moduleImport.getRevision());
+ Module importedModule = schemaContext.findModule(moduleImport.getModuleName(),
+ moduleImport.getRevision()).get();
qname = QName.create(importedModule.getQNameModule(), defaultValue.substring(prefixEndIndex + 1));
return codec.deserialize(qname);
}
}
static void checkModulePresent(final SchemaContext schemaContext, final QName name) {
- if (schemaContext.findModuleByNamespaceAndRevision(name.getNamespace(), name.getRevision()) == null) {
+ if (!schemaContext.findModule(name.getModule()).isPresent()) {
throw MissingSchemaException.create("Module %s is not present in current schema context.",
name.getModule());
}
final BindingCodecContext bindingCodecContext, final Set<UnionValueOptionContext> values,
final TypeDefinition<?> subtype) throws NoSuchMethodException {
final SchemaContext schemaContext = bindingCodecContext.getRuntimeContext().getSchemaContext();
- final Module module = schemaContext.findModuleByNamespaceAndRevision(subtype.getQName().getNamespace(),
- subtype.getQName().getRevision());
+ final Module module = schemaContext.findModule(subtype.getQName().getModule()).get();
final RevisionAwareXPath xpath = ((LeafrefTypeDefinition) subtype).getPathStatement();
// find schema node in schema context by xpath of leafref
final SchemaNode dataNode;
import java.util.concurrent.ExecutionException;
import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
@Override
public Object serialize(final Object input) {
- // Empty type has null value in NormalizedNode and Composite Node representation
- return null;
+ // Empty type has Empty value in NormalizedNode and Composite Node representation
+ return Empty.getInstance();
}
@Override
*/
package org.opendaylight.mdsal.binding.generator.spi;
-import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
+import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
//FIXME not implemented anywhere
public interface TypeProviderFactory {
- TypeProvider providerFor(ModuleIdentifier module);
+ TypeProvider providerFor(SourceIdentifier module);
}
package org.opendaylight.mdsal.binding.model.api;
import java.util.List;
+import java.util.Optional;
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;
public interface Restrictions {
- List<LengthConstraint> getLengthConstraints();
+ Optional<LengthConstraint> getLengthConstraint();
List<PatternConstraint> getPatternConstraints();
- List<RangeConstraint> getRangeConstraints();
+ Optional<? extends RangeConstraint<?>> getRangeConstraint();
boolean isEmpty();
}
import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
/**
* Comparator based on augment target path.
*/
- private static final Comparator<AugmentationSchema> AUGMENT_COMP = (o1, o2) -> {
+ private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
}
final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
- genType.addComment(node.getDescription());
+ genType.addComment(node.getDescription().orElse(null));
annotateDeprecatedIfNecessary(node.getStatus(), genType);
genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
genType.setModuleName(module.getName());
- genType.setReference(node.getReference());
+ genType.setReference(node.getReference().orElse(null));
genType.setSchemaPath(node.getPath().getPathFromRoot());
if (node instanceof DataNodeContainer) {
genCtx.get(module).addChildNodeType(node, genType);
final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final ContainerSchemaNode node) {
final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
if (genType != null) {
- constructGetter(parent, node.getQName().getLocalName(), node.getDescription(), genType, node.getStatus());
+ constructGetter(parent, node.getQName().getLocalName(), node.getDescription().orElse(null), genType,
+ node.getStatus());
resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes());
}
}
final GeneratedTypeBuilder childOf, final ListSchemaNode node) {
final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node);
if (genType != null) {
- constructGetter(parent, node.getQName().getLocalName(), node.getDescription(),
+ constructGetter(parent, node.getQName().getLocalName(), node.getDescription().orElse(null),
Types.listTypeFor(genType), node.getStatus());
final List<String> listKeys = listKeys(node);
private void processUsesAugments(final DataNodeContainer node, final Module module) {
final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
for (final UsesNode usesNode : node.getUses()) {
- for (final AugmentationSchema augment : usesNode.getAugmentations()) {
+ for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
processUsesAugments(augment, module);
}
checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
- final List<AugmentationSchema> augmentations = resolveAugmentations(module);
- for (final AugmentationSchema augment : augmentations) {
+ for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
augmentationToGenTypes(basePackageName, augment, module);
}
}
* @throws IllegalStateException
* if set of module augmentations is null
*/
- private static List<AugmentationSchema> resolveAugmentations(final Module module) {
+ private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
checkArgument(module != null, "Module reference cannot be NULL.");
checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
- final Set<AugmentationSchema> augmentations = module.getAugmentations();
- final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
+ final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
+ final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
sortedAugmentations.sort(AUGMENT_COMP);
return sortedAugmentations;
final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data");
addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
- moduleDataTypeBuilder.addComment(module.getDescription());
+ moduleDataTypeBuilder.addComment(module.getDescription().orElse(null));
moduleDataTypeBuilder.setDescription(createDescription(module));
- moduleDataTypeBuilder.setReference(module.getReference());
+ moduleDataTypeBuilder.setReference(module.getReference().orElse(null));
return moduleDataTypeBuilder;
}
if (rpc != null) {
final String rpcName = BindingMapping.getClassName(rpc.getQName());
final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
- final String rpcComment = encodeAngleBrackets(rpc.getDescription());
+ final String rpcComment = encodeAngleBrackets(rpc.getDescription().orElse(null));
final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
final ContainerSchemaNode input = rpc.getInput();
final ContainerSchemaNode output = rpc.getOutput();
listenerInterface.addMethod("on" + notificationInterface.getName())
.setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
- .setComment(encodeAngleBrackets(notification.getDescription())).setReturnType(Types.VOID);
+ .setComment(encodeAngleBrackets(notification.getDescription().orElse(null))).setReturnType(Types.VOID);
}
}
listenerInterface.setDescription(createDescription(notifications, module.getName()));
final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
final String genTypeName = BindingMapping.getClassName(identity.getQName());
final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTypeName);
- final IdentitySchemaNode baseIdentity = identity.getBaseIdentity();
- if (baseIdentity == null) {
+ final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
+ if (baseIdentities.isEmpty()) {
final GeneratedTOBuilderImpl gto = new GeneratedTOBuilderImpl(BaseIdentity.class.getPackage().getName(),
BaseIdentity.class.getSimpleName());
newType.setExtendsType(gto.toInstance());
} else {
+ final IdentitySchemaNode baseIdentity = baseIdentities.iterator().next();
final Module baseIdentityParentModule = SchemaContextUtil.findParentModule(context, baseIdentity);
final String returnTypePkgName = BindingMapping.getRootPackageName(baseIdentityParentModule
.getQNameModule());
newType.setExtendsType(gto);
}
newType.setAbstract(true);
- newType.addComment(identity.getDescription());
+ newType.addComment(identity.getDescription().orElse(null));
newType.setDescription(createDescription(identity, newType.getFullyQualifiedName()));
- newType.setReference(identity.getReference());
+ newType.setReference(identity.getReference().orElse(null));
newType.setModuleName(module.getName());
newType.setSchemaPath(identity.getPath().getPathFromRoot());
* @param module
* current module
*/
- private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
+ private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping,
+ final Module module) {
final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
final String enumerationName = BindingMapping.getClassName(enumName);
final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
- final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
+ final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null));
enumBuilder.setDescription(enumTypedefDescription);
enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
ModuleContext ctx = genCtx.get(module);
final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
moduleBuilder.setDescription(createDescription(module));
- moduleBuilder.setReference(module.getReference());
+ moduleBuilder.setReference(module.getReference().orElse(null));
moduleBuilder.setModuleName(moduleName);
return moduleBuilder;
* @throws IllegalStateException
* if augment target path is null
*/
- private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
+ private void augmentationToGenTypes(final String augmentPackageName, final AugmentationSchemaNode augSchema,
final Module module) {
checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
if (targetSchemaNode instanceof DerivableSchemaNode) {
- targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
+ targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
}
if (targetSchemaNode == null) {
throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
}
}
- private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
+ private void usesAugmentationToGenTypes(final String augmentPackageName, final AugmentationSchemaNode augSchema,
final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
String packageName = augmentPackageName;
if (usesNodeParent instanceof SchemaNode) {
- packageName = packageNameForAugmentedGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath());
+ packageName = packageNameForAugmentedGeneratedType(augmentPackageName,
+ ((SchemaNode) usesNodeParent).getPath());
}
addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetTypeBuilder.toInstance(),
augSchema);
final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
result = ((DataNodeContainer) result).getDataChildByName(resultNode);
} else if (result instanceof ChoiceSchemaNode) {
- result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
+ result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
}
}
if (result == null) {
if (result instanceof DerivableSchemaNode) {
DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
- Optional<? extends SchemaNode> originalNode = castedResult
- .getOriginal();
+ Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
if (castedResult.isAddedByUses() && originalNode.isPresent()) {
result = originalNode.get();
}
* @return generated type builder for augment
*/
private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
- final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
+ final String basePackageName, final Type targetTypeRef, final AugmentationSchemaNode augSchema) {
Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
if (augmentBuilders == null) {
augmentBuilders = new HashMap<>();
final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
constructGetter(parent, choiceNode.getQName().getLocalName(),
- choiceNode.getDescription(), choiceTypeBuilder, choiceNode.getStatus());
+ choiceNode.getDescription().orElse(null), choiceTypeBuilder, choiceNode.getStatus());
choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
- final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
- if (caseNodes == null) {
- return;
- }
-
- for (final ChoiceCaseNode caseNode : caseNodes) {
+ for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
- final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
+ final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode,
+ module);
caseTypeBuilder.addImplementsType(refChoiceType);
annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
- if (parent instanceof AugmentationSchema) {
- final AugmentationSchema augSchema = (AugmentationSchema) parent;
+ if (parent instanceof AugmentationSchemaNode) {
+ final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
final SchemaPath targetPath = augSchema.getTargetPath();
SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
if (targetSchemaNode instanceof DataSchemaNode
&& ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
if (targetSchemaNode instanceof DerivableSchemaNode) {
- targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
+ targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
+ .orElse(null);
}
if (targetSchemaNode == null) {
throw new IllegalStateException(
GeneratedTypeBuilder childOfType = null;
if (parent instanceof Module) {
childOfType = genCtx.get(parent).getModuleNode();
- } else if (parent instanceof ChoiceCaseNode) {
+ } else if (parent instanceof CaseSchemaNode) {
childOfType = findCaseByPath(parent.getPath());
} else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
childOfType = findChildNodeByPath(parent.getPath());
throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
}
- ChoiceCaseNode node = null;
+ CaseSchemaNode node = null;
final String caseLocalName = caseNode.getQName().getLocalName();
- if (caseNode instanceof ChoiceCaseNode) {
- node = (ChoiceCaseNode) caseNode;
- } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
+ if (caseNode instanceof CaseSchemaNode) {
+ node = (CaseSchemaNode) caseNode;
+ } else if (findNamedCase(targetNode, caseLocalName) == null) {
final String targetNodeLocalName = targetNode.getQName().getLocalName();
for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
().getLocalName())) {
- node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
+ node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
break;
}
}
} else {
- node = targetNode.getCaseNodeByName(caseLocalName);
+ node = findNamedCase(targetNode, caseLocalName);
}
final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
if (childNodes != null) {
}
}
+ private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
+ final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
+ return cases.isEmpty() ? null : cases.get(0);
+ }
+
private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
// New parser with encapsulated type
if (leaf.getPath().equals(type.getPath())) {
((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
}
- String leafDesc = leaf.getDescription();
- if (leafDesc == null) {
- leafDesc = "";
- }
-
- final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType, leaf.getStatus());
+ final String leafDesc = leaf.getDescription().orElse("");
+ final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType,
+ leaf.getStatus());
processContextRefExtension(leaf, getter, parentModule);
return returnType;
}
private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
for (final ModuleImport imp : imports) {
if (imp.getPrefix().equals(prefix)) {
- return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
+ return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
}
}
return null;
// GeneratedType for this type definition should be already
// created
final QName qname = typeDef.getQName();
- final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
- qname.getRevision());
+ final Module unionModule = schemaContext.findModule(qname.getModule()).orElse(null);
final ModuleContext mc = genCtx.get(unionModule);
returnType = mc.getTypedefs().get(typeDef.getPath());
} else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
// Annonymous enumeration (already generated, since it is inherited via uses).
LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
QName qname = originalLeaf.getQName();
- final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
- qname.getRevision());
+ final Module enumModule = schemaContext.findModule(qname.getModule()).orElse(null);
returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
} else {
returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
return false;
}
final String leafName = leaf.getQName().getLocalName();
- final String leafDesc = encodeAngleBrackets(leaf.getDescription());
+ final String leafDesc = encodeAngleBrackets(leaf.getDescription().orElse(null));
final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
propBuilder.setReadOnly(isReadOnly);
propBuilder.setReturnType(returnType);
* <li>false - other cases</li>
* </ul>
*/
- private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
+ private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
+ final Module module) {
if (node == null || typeBuilder == null || node.isAddedByUses()) {
return false;
}
}
final ParameterizedType listType = Types.listTypeFor(returnType);
- constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType, node.getStatus());
+ constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription().orElse(null), listType,
+ node.getStatus());
return true;
}
final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
genTOBuilder.getName());
- final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
+ final String typedefDescription = encodeAngleBrackets(typeDef.getDescription().orElse(null));
returnType.setDescription(typedefDescription);
- returnType.setReference(typeDef.getReference());
+ returnType.setReference(typeDef.getReference().orElse(null));
returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
returnType.setModuleName(parentModule.getName());
genTOBuilder.setTypedef(true);
genTOBuilder.setIsUnion(true);
- TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
+ TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
final Module module = findParentModule(schemaContext, schemaNode);
qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
- newType.addComment(schemaNode.getDescription());
+ newType.addComment(schemaNode.getDescription().orElse(null));
newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
- newType.setReference(schemaNode.getReference());
+ newType.setReference(schemaNode.getReference().orElse(null));
newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
newType.setModuleName(module.getName());
private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
final StringBuilder sb = new StringBuilder();
- final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
+ final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription().orElse(null));
final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
if (!Strings.isNullOrEmpty(formattedDescription)) {
private String createDescription(final Module module) {
final StringBuilder sb = new StringBuilder();
- final String moduleDescription = encodeAngleBrackets(module.getDescription());
+ final String moduleDescription = encodeAngleBrackets(module.getDescription().orElse(null));
final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
if (!Strings.isNullOrEmpty(formattedDescription)) {
import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.common.Revision;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
for (DataSchemaNode child : ctx.getChildNodes()) {
if (child instanceof ChoiceSchemaNode) {
- DataNodeContainer potential = findInCases(((ChoiceSchemaNode) child), targetQName);
+ DataNodeContainer potential = findInCases((ChoiceSchemaNode) child, targetQName);
if (potential != null) {
return Optional.of(potential);
}
}
private static DataNodeContainer findInCases(final ChoiceSchemaNode choiceNode, final QName targetQName) {
- for (ChoiceCaseNode caze : choiceNode.getCases()) {
+ for (CaseSchemaNode caze : choiceNode.getCases().values()) {
Optional<DataNodeContainer> potential = findDataNodeContainer(caze, targetQName);
if (potential.isPresent()) {
return potential.get();
for(RpcDefinition rpc : ctx.getOperations()) {
String rpcNamespace = rpc.getQName().getNamespace().toString();
- String rpcRevision = rpc.getQName().getFormattedRevision();
+ String rpcRevision = rpc.getQName().getRevision().map(Revision::toString).orElse(null);
if(moduleInfo.getNamespace().equals(rpcNamespace) && moduleInfo.getRevision().equals(rpcRevision)) {
Optional<DataNodeContainer> potential = findInputOutput(rpc,targetType.getSimpleName());
if(potential.isPresent()) {
return Optional.absent();
}
- public static Set<AugmentationSchema> collectAllAugmentationDefinitions(final SchemaContext currentSchema, final AugmentationTarget ctxNode) {
- HashSet<AugmentationSchema> augmentations = new HashSet<>();
+ public static Set<AugmentationSchemaNode> collectAllAugmentationDefinitions(final SchemaContext currentSchema,
+ final AugmentationTarget ctxNode) {
+ HashSet<AugmentationSchemaNode> augmentations = new HashSet<>();
augmentations.addAll(ctxNode.getAvailableAugmentations());
if(ctxNode instanceof DataSchemaNode && ((DataSchemaNode) ctxNode).isAddedByUses()) {
return augmentations;
}
- public static Optional<ChoiceSchemaNode> findInstantiatedChoice(final DataNodeContainer parent, final Class<?> choiceClass) {
+ public static Optional<ChoiceSchemaNode> findInstantiatedChoice(final DataNodeContainer parent,
+ final Class<?> choiceClass) {
return findInstantiatedChoice(parent, BindingReflections.findQName(choiceClass));
}
- public static Optional<ChoiceSchemaNode> findInstantiatedChoice(final DataNodeContainer ctxNode, final QName choiceName) {
+ public static Optional<ChoiceSchemaNode> findInstantiatedChoice(final DataNodeContainer ctxNode,
+ final QName choiceName) {
DataSchemaNode potential = ctxNode.getDataChildByName(choiceName);
if (potential instanceof ChoiceSchemaNode) {
return Optional.of((ChoiceSchemaNode) potential);
return Optional.absent();
}
- public static Optional<ChoiceCaseNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice, final ChoiceCaseNode originalDefinition) {
- ChoiceCaseNode potential = instantiatedChoice.getCaseNodeByName(originalDefinition.getQName());
+ public static Optional<CaseSchemaNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice,
+ final CaseSchemaNode originalDefinition) {
+ CaseSchemaNode potential = instantiatedChoice.getCaseNodeByName(originalDefinition.getQName());
if(originalDefinition.equals(potential)) {
return Optional.of(potential);
}
return Optional.of(potential);
}
}
+
// We try to find case by name, then lookup its root definition
// and compare it with original definition
// This solves case, if choice was inside grouping
// Still we need to check equality of definition, because local name is not
// sufficient to uniquelly determine equality of cases
//
- potential = instantiatedChoice.getCaseNodeByName(originalDefinition.getQName().getLocalName());
- if(potential != null && (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential)))) {
- return Optional.of(potential);
+ for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
+ if (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(caze))) {
+ return Optional.of(caze);
+ }
}
return Optional.absent();
}
import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
private final Map<QName,GeneratedTOBuilder> identities = new HashMap<>();
private final Set<GeneratedTypeBuilder> topLevelNodes = new HashSet<>();
private final List<GeneratedTypeBuilder> augmentations = new ArrayList<>();
- private final BiMap<Type, AugmentationSchema> typeToAugmentation = HashBiMap.create();
+ private final BiMap<Type, AugmentationSchemaNode> typeToAugmentation = HashBiMap.create();
private final Map<Type,Object> typeToSchema = new HashMap<>();
private final Multimap<Type, Type> choiceToCases = HashMultimap.create();
- private final BiMap<Type, ChoiceCaseNode> caseTypeToSchema = HashBiMap.create();
+ private final BiMap<Type, CaseSchemaNode> caseTypeToSchema = HashBiMap.create();
private final Map<SchemaPath, Type> innerTypes = new HashMap<>();
return Collections.unmodifiableList(augmentations);
}
- public BiMap<Type, AugmentationSchema> getTypeToAugmentation() {
+ public BiMap<Type, AugmentationSchemaNode> getTypeToAugmentation() {
return Maps.unmodifiableBiMap(typeToAugmentation);
}
- public void addTypeToAugmentation(final GeneratedTypeBuilder builder, final AugmentationSchema schema) {
+ public void addTypeToAugmentation(final GeneratedTypeBuilder builder, final AugmentationSchemaNode schema) {
typeToAugmentation.put(builder, schema);
typeToSchema.put(builder, schema);
}
- public void addChoiceToCaseMapping(final Type choiceType, final Type caseType, final ChoiceCaseNode schema) {
+ public void addChoiceToCaseMapping(final Type choiceType, final Type caseType, final CaseSchemaNode schema) {
choiceToCases.put(choiceType, caseType);
caseTypeToSchema.put(caseType, schema);
typeToSchema.put(caseType, schema);
}
- public BiMap<Type, ChoiceCaseNode> getCaseTypeToSchemas() {
+ public BiMap<Type, CaseSchemaNode> getCaseTypeToSchemas() {
return Maps.unmodifiableBiMap(caseTypeToSchema);
}
*
* Returns mapping of type to its schema.
*
- * Valid values are only instances of {@link DataSchemaNode} or {@link AugmentationSchema}
+ * Valid values are only instances of {@link DataSchemaNode} or {@link AugmentationSchemaNode}
*
* @return Mapping from type to corresponding schema
*/
return Collections.unmodifiableMap(typeToSchema);
}
- protected void addTypeToSchema(Type type, TypeDefinition<?> typedef) {
+ protected void addTypeToSchema(final Type type, final TypeDefinition<?> typedef) {
typeToSchema.put(type, typedef);
}
* @param path
* @param enumBuilder
*/
- void addInnerTypedefType(SchemaPath path, EnumBuilder enumBuilder) {
+ void addInnerTypedefType(final SchemaPath path, final EnumBuilder enumBuilder) {
innerTypes.put(path, enumBuilder);
}
- public Type getInnerType(SchemaPath path) {
+ public Type getInnerType(final SchemaPath path) {
return innerTypes.get(path);
}
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.base.Optional;
+import com.google.common.base.Strings;
import com.google.common.io.ByteSource;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import org.opendaylight.yangtools.util.ClassLoaderUtils;
import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBackedContext.class);
- private final ConcurrentMap<String, WeakReference<ClassLoader>> packageNameToClassLoader = new ConcurrentHashMap<>();
- private final ConcurrentMap<SourceIdentifier, YangModuleInfo> sourceIdentifierToModuleInfo = new ConcurrentHashMap<>();
+ private final ConcurrentMap<String, WeakReference<ClassLoader>> packageNameToClassLoader =
+ new ConcurrentHashMap<>();
+ private final ConcurrentMap<SourceIdentifier, YangModuleInfo> sourceIdentifierToModuleInfo =
+ new ConcurrentHashMap<>();
private final ClassLoadingStrategy backingLoadingStrategy;
// Implement remove ModuleInfo to update SchemaContext
public Optional<SchemaContext> tryToCreateSchemaContext() {
- return ctxResolver.getSchemaContext();
+ return Optional.fromJavaUtil(ctxResolver.getSchemaContext());
}
private boolean resolveModuleInfo(final Class<?> cls) {
return true;
}
- private static YangTextSchemaSource toYangTextSource(final SourceIdentifier identifier, final YangModuleInfo moduleInfo) {
+ private static YangTextSchemaSource toYangTextSource(final SourceIdentifier identifier,
+ final YangModuleInfo moduleInfo) {
return new YangTextSchemaSource(identifier) {
@Override
}
private static SourceIdentifier sourceIdentifierFrom(final YangModuleInfo moduleInfo) {
- return RevisionSourceIdentifier.create(moduleInfo.getName(), Optional.of(moduleInfo.getRevision()));
+ return RevisionSourceIdentifier.create(moduleInfo.getName(), Revision.ofNullable(moduleInfo.getRevision()));
}
public void addModuleInfos(final Iterable<? extends YangModuleInfo> moduleInfos) {
return registration;
}
- @Override public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(
+ @Override
+ public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(
final SourceIdentifier sourceIdentifier) {
final YangModuleInfo yangModuleInfo = sourceIdentifierToModuleInfo.get(sourceIdentifier);
package org.opendaylight.mdsal.binding.generator.impl
import java.util.Collection
-import java.util.Date
import java.util.List
import java.util.Map
import java.util.Set
-import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil
+import org.opendaylight.yangtools.yang.common.Revision
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
«IF node instanceof NotificationDefinition»
«writeNotification(node)»
«ELSEIF node instanceof RpcDefinition»
- «writeRPC(node as RpcDefinition)»
+ «writeRPC(node)»
«ENDIF»
«ENDFOR»
'''
'''
}
- def private static writeRevision(Date moduleRevision, String moduleDescription) {
+ def private static writeRevision(Revision moduleRevision, String moduleDescription) {
val revisionIndent = 12
'''
- revision «SimpleDateFormatUtil.getRevisionFormat.format(moduleRevision)» {
+ revision «moduleRevision.toString» {
description "«YangTextTemplate.formatToParagraph(moduleDescription, revisionIndent)»";
}
'''
«IF !module.imports.nullOrEmpty»
«writeModuleImports(module.imports)»
«ENDIF»
- «IF module.revision !== null»
- «writeRevision(module.revision, module.description)»
+ «IF module.revision.present»
+ «writeRevision(module.revision.get, module.description.orElse(null))»
«ENDIF»
«IF !module.childNodes.nullOrEmpty»
var boolean isStatusDeprecated = rpc.status == Status::DEPRECATED
'''
rpc «rpc.QName.localName» {
- «IF !rpc.description.nullOrEmpty»
- "«rpc.description»";
+ «IF rpc.description.present»
+ "«rpc.description.get»";
«ENDIF»
«IF !rpc.groupings.nullOrEmpty»
«writeGroupingDefs(rpc.groupings)»
«IF rpc.output !== null»
«writeRpcOutput(rpc.output)»
«ENDIF»
- «IF !rpc.reference.nullOrEmpty»
+ «IF rpc.reference.present»
reference
- "«rpc.reference»";
+ "«rpc.reference.get»";
«ENDIF»
«IF isStatusDeprecated»
status «rpc.status»;
var boolean isStatusDeprecated = notification.status == Status::DEPRECATED
'''
notification «notification.QName.localName» {
- «IF !notification.description.nullOrEmpty»
+ «IF notification.description.present»
description
- "«notification.description»";
+ "«notification.description.get»";
«ENDIF»
«IF !notification.childNodes.nullOrEmpty»
«writeDataSchemaNodes(notification.childNodes)»
«IF !notification.uses.nullOrEmpty»
«writeUsesNodes(notification.uses)»
«ENDIF»
- «IF !notification.reference.nullOrEmpty»
+ «IF notification.reference.present»
reference
- "«notification.reference»";
+ "«notification.reference.get»";
«ENDIF»
«IF isStatusDeprecated»
status «notification.status»;
return ''
'''
identity «identity.QName.localName» {
- «IF identity.baseIdentity !== null»
- base "()«identity.baseIdentity»";
- «ENDIF»
- «IF !identity.description.nullOrEmpty»
+ «FOR baseIdentity : identity.baseIdentities»
+ base "()«baseIdentity»";
+ «ENDFOR»
+ «IF identity.description.present»
description
- "«identity.description»";
+ "«identity.description.get»";
«ENDIF»
- «IF !identity.reference.nullOrEmpty»
+ «IF identity.reference.present»
reference
- "«identity.reference»";
+ "«identity.reference.get»";
«ENDIF»
«IF identity.status !== null»
status «identity.status»;
def private static writeFeature(FeatureDefinition featureDef) {
'''
feature «featureDef.QName.localName» {
- «IF !featureDef.description.nullOrEmpty»
+ «IF featureDef.description.present»
description
- "«featureDef.description»";
+ "«featureDef.description.get»";
«ENDIF»
- «IF !featureDef.reference.nullOrEmpty»
+ «IF featureDef.reference.present»
reference
- "«featureDef.reference»";
+ "«featureDef.reference.get»";
«ENDIF»
«IF featureDef.status !== null»
status «featureDef.status»;
def private static writeExtension(ExtensionDefinition extensionDef) {
'''
extension «extensionDef.QName.localName» {
- «IF !extensionDef.description.nullOrEmpty»
+ «IF extensionDef.description.present»
description
- "«extensionDef.description»";
+ "«extensionDef.description.get»";
«ENDIF»
«IF !extensionDef.argument.nullOrEmpty»
argument "«extensionDef.argument»";
«ENDIF»
- «IF !extensionDef.reference.nullOrEmpty»
+ «IF extensionDef.reference.present»
reference
- "«extensionDef.reference»";
+ "«extensionDef.reference.get»";
«ENDIF»
«IF extensionDef.status !== null»
status «extensionDef.status»;
def private static writeDeviation(Deviation deviation) {
'''
deviation «deviation.targetPath» {
- «IF !deviation.reference.nullOrEmpty»
+ «IF deviation.reference.present»
reference
- "«deviation.reference»";
+ "«deviation.reference.get»";
«ENDIF»
«FOR dev : deviation.deviates»
«IF dev !== null && dev.deviateType !== null»
'''
}
- def private static writeAugments(Set<AugmentationSchema> augments) {
+ def private static writeAugments(Set<AugmentationSchemaNode> augments) {
'''
«FOR augment : augments»
«IF augment !== null»
'''
}
- def private static writeAugment(AugmentationSchema augment) {
+ def private static writeAugment(AugmentationSchemaNode augment) {
'''
augment «YangTextTemplate.formatToAugmentPath(augment.targetPath.pathFromRoot)» {
«IF augment.whenCondition !== null && !augment.whenCondition.toString.nullOrEmpty»
when "«augment.whenCondition.toString»";
«ENDIF»
- «IF !augment.description.nullOrEmpty»
+ «IF augment.description.present»
description
- "«augment.description»";
+ "«augment.description.get»";
«ENDIF»
- «IF !augment.reference.nullOrEmpty»
+ «IF augment.reference.present»
reference
- "«augment.reference»";
+ "«augment.reference.get»";
«ENDIF»
«IF augment.status !== null»
status «augment.status»;
'''
}
- def private static writeChoiceCaseNode(ChoiceCaseNode choiceCaseNode) {
+ def private static writeCaseSchemaNode(CaseSchemaNode choiceCaseNode) {
var boolean isStatusDeprecated = choiceCaseNode.status == Status::DEPRECATED
'''
case «choiceCaseNode.getQName.localName» {
var boolean isStatusDeprecated = choiceNode.status == Status::DEPRECATED
'''
choice «choiceNode.getQName.localName» {
- «FOR child : choiceNode.cases»
+ «FOR child : choiceNode.cases.values»
«writeDataSchemaNode(child)»
«ENDFOR»
«IF isStatusDeprecated»
«IF child instanceof LeafListSchemaNode»
«writeLeafListSchemaNode(child)»
«ENDIF»
- «IF child instanceof ChoiceCaseNode»
- «writeChoiceCaseNode(child)»
+ «IF child instanceof CaseSchemaNode»
+ «writeCaseSchemaNode(child)»
«ENDIF»
«IF child instanceof ChoiceSchemaNode»
«writeChoiceNode(child)»
import org.opendaylight.yangtools.yang.binding.BindingMapping;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
private final ClassLoadingStrategy strategy;
private final SchemaContext schemaContext;
- private final Map<Type, AugmentationSchema> augmentationToSchema = new HashMap<>();
+ private final Map<Type, AugmentationSchemaNode> augmentationToSchema = new HashMap<>();
private final BiMap<Type, Object> typeToDefiningSchema = HashBiMap.create();
private final Multimap<Type, Type> choiceToCases = HashMultimap.create();
private final Map<QName, Type> identities = new HashMap<>();
* which may be present in runtime for them, thus returned schema is unsuitable
* for use for validation of data.
* <p>
- * For retrieving {@link AugmentationSchema}, which will contains
+ * For retrieving {@link AugmentationSchemaNode}, which will contains
* full model for child nodes, you should use method {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
* which will return augmentation schema derived from supplied augmentation target
* schema.
* @return Schema of augmentation or null if augmentaiton is not known in this context
* @throws IllegalArgumentException If supplied class is not an augmentation
*/
- public @Nullable AugmentationSchema getAugmentationDefinition(final Class<?> augClass) throws IllegalArgumentException {
- Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass), "Class %s does not represent augmentation", augClass);
+ public @Nullable AugmentationSchemaNode getAugmentationDefinition(final Class<?> augClass) {
+ Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass),
+ "Class %s does not represent augmentation", augClass);
return augmentationToSchema.get(referencedType(augClass));
}
return (DataSchemaNode) typeToDefiningSchema.get(referencedType(cls));
}
- public Entry<AugmentationIdentifier, AugmentationSchema> getResolvedAugmentationSchema(final DataNodeContainer target,
- final Class<? extends Augmentation<?>> aug) {
- final AugmentationSchema origSchema = getAugmentationDefinition(aug);
+ public Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
+ final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
+ final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
Preconditions.checkArgument(origSchema != null, "Augmentation %s is not known in current schema context",aug);
/*
* FIXME: Validate augmentation schema lookup
}
final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
- final AugmentationSchema proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
+ final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
return new SimpleEntry<>(identifier, proxy);
}
* the given context.
* @throws IllegalArgumentException If supplied class does not represent case.
*/
- public Optional<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) throws IllegalArgumentException {
+ public Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) throws IllegalArgumentException {
final DataSchemaNode origSchema = getSchemaDefinition(childClass);
- Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "Supplied schema %s is not case.", origSchema);
+ Preconditions.checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
/* FIXME: Make sure that if there are multiple augmentations of same
* named case, with same structure we treat it as equals
* that user may be unaware that he is using incorrect case
* which was generated for choice inside grouping.
*/
- final Optional<ChoiceCaseNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
- (ChoiceCaseNode) origSchema);
+ final Optional<CaseSchemaNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
+ (CaseSchemaNode) origSchema);
return found;
}
}
/**
- * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition})
+ * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
* from which supplied class was generated. Returned schema may be augmented with
* additional information, which was not available at compile type
* (e.g. third party augmentations).
*
* @param type Binding Class for which schema should be retrieved.
* @return Instance of generated type (definition of Java API), along with
- * {@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition}
+ * {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
* which was used to generate supplied class.
*/
public Entry<GeneratedType, Object> getTypeWithSchema(final Class<?> type) {
public ImmutableMap<AugmentationIdentifier,Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
final Map<AugmentationIdentifier,Type> identifierToType = new HashMap<>();
if (container instanceof AugmentationTarget) {
- final Set<AugmentationSchema> augments = ((AugmentationTarget) container).getAvailableAugmentations();
- for (final AugmentationSchema augment : augments) {
+ final Set<AugmentationSchemaNode> augments = ((AugmentationTarget) container).getAvailableAugmentations();
+ for (final AugmentationSchemaNode augment : augments) {
// Augmentation must have child nodes if is to be used with Binding classes
- AugmentationSchema augOrig = augment;
+ AugmentationSchemaNode augOrig = augment;
while (augOrig.getOriginalDefinition().isPresent()) {
augOrig = augOrig.getOriginalDefinition().get();
}
return ImmutableMap.copyOf(identifierToType);
}
- private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchema augment) {
+ private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
final Set<QName> childNames = new HashSet<>();
for (final DataSchemaNode child : augment.getChildNodes()) {
childNames.add(child.getQName());
import com.google.common.base.Preconditions;
import java.net.URI;
-import java.util.Date;
import java.util.Iterator;
+import java.util.Optional;
import javax.annotation.Nullable;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.common.Revision;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
throw new UnsupportedOperationException("Helper class. Instantiation is prohibited");
}
- public static QName getAugmentationQName(final AugmentationSchema augmentation) {
+ public static QName getAugmentationQName(final AugmentationSchemaNode augmentation) {
checkNotNull(augmentation, "Augmentation must not be null.");
final QName identifier = getAugmentationIdentifier(augmentation);
if(identifier != null) {
return identifier;
}
URI namespace = null;
- Date revision = null;
+ Optional<Revision> revision = null;
if(augmentation instanceof NamespaceRevisionAware) {
namespace = ((NamespaceRevisionAware) augmentation).getNamespace();
revision = ((NamespaceRevisionAware) augmentation).getRevision();
}
checkState(namespace != null, "Augmentation namespace must not be null");
checkState(revision != null, "Augmentation revision must not be null");
- // FIXME: Allways return a qname with module namespace.
- return QName.create(namespace,revision, "foo_augment");
+ // FIXME: Always return a qname with module namespace.
+ return QName.create(namespace, revision, "foo_augment");
}
- public static QName getAugmentationIdentifier(final AugmentationSchema augmentation) {
+ public static QName getAugmentationIdentifier(final AugmentationSchemaNode augmentation) {
for(final UnknownSchemaNode extension : augmentation.getUnknownSchemaNodes()) {
if(AUGMENT_IDENTIFIER.equals(extension.getNodeType().getLocalName())) {
return extension.getQName();
Preconditions.checkArgument(arguments.hasNext(), "Type Definition path must contain at least one element.");
QName currentArg = arguments.next();
- DataNodeContainer currentNode = context.findModuleByNamespaceAndRevision(currentArg.getNamespace(), currentArg.getRevision());
+ DataNodeContainer currentNode = context.findModule(currentArg.getModule()).orElse(null);
if(currentNode == null) {
return null;
}
}
};
- private static <T extends Number> Restrictions singleRangeRestrictions(final T min, final T max) {
+ private static <T extends Number & Comparable<T>> Restrictions singleRangeRestrictions(final T min, final T max) {
return Types.getDefaultRestrictions(min, max);
}
import java.util.Set;
import org.opendaylight.yangtools.util.TopologicalSort;
import org.opendaylight.yangtools.util.TopologicalSort.Node;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
ret.addAll(usesNodes);
for (UsesNode usesNode : usesNodes) {
- for (AugmentationSchema augment : usesNode.getAugmentations()) {
+ for (AugmentationSchemaNode augment : usesNode.getAugmentations()) {
ret.addAll(getAllUsesNodes(augment));
}
}
if (childNode instanceof DataNodeContainer) {
ret.addAll(getAllUsesNodes((DataNodeContainer) childNode));
} else if (childNode instanceof ChoiceSchemaNode) {
- Set<ChoiceCaseNode> cases = ((ChoiceSchemaNode) childNode).getCases();
- for (ChoiceCaseNode choiceCaseNode : cases) {
+ for (CaseSchemaNode choiceCaseNode : ((ChoiceSchemaNode) childNode).getCases().values()) {
ret.addAll(getAllUsesNodes(choiceCaseNode));
}
}
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
-import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
-import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedTOBuilderImpl;
import org.opendaylight.yangtools.yang.binding.BindingMapping;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
/**
* Map<moduleName, Map<moduleDate, Map<typeName, type>>>
*/
- private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
+ private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap;
/**
* The map which maps schema paths to JAVA <code>Type</code>.
final Module module = findParentModule(schemaContext, typeDefinition);
final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
if (module != null) {
- final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
+ final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
if (genTOs != null) {
returnType = genTOs.get(typedefName);
* @param idref
* identityref type definition for which JAVA <code>Type</code>
* is sought
- * @return JAVA <code>Type</code> of the identity which is refrenced through
+ * @return JAVA <code>Type</code> of the identity which is referenced through
* <code>idref</code>
*/
private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
- final QName baseIdQName = idref.getIdentity().getQName();
- final Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
- baseIdQName.getRevision());
+ final Collection<IdentitySchemaNode> identities = idref.getIdentities();
+ if (identities.size() > 1) {
+ LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
+ }
+
+ final QName baseIdQName = identities.iterator().next().getQName();
+ final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
IdentitySchemaNode identity = null;
for (final IdentitySchemaNode id : module.getIdentities()) {
if (id.getQName().equals(baseIdQName)) {
final Module module = findParentModule(schemaContext, parentNode);
if (module != null) {
- final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
+ final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
if (genTOs != null) {
return genTOs.get(typeDefinition.getQName().getLocalName());
final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
- final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
+ final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null));
enumBuilder.setDescription(enumTypedefDescription);
- enumBuilder.setReference(enumTypeDef.getReference());
+ enumBuilder.setReference(enumTypeDef.getReference().orElse(null));
enumBuilder.setModuleName(module.getName());
enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
final String enumerationName = BindingMapping.getClassName(enumName);
final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
- final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
+ final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null));
enumBuilder.setDescription(enumTypedefDescription);
enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
return enumBuilder.toInstance(enumBuilder);
final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
for (final Module module : modulesSortedByDependency) {
- Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
+ Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
if (dateTypeMap == null) {
dateTypeMap = new HashMap<>();
}
*/
private Type typedefToGeneratedType(final String basePackageName, final Module module, final TypeDefinition<?> typedef) {
final String moduleName = module.getName();
- final Date moduleRevision = module.getRevision();
+ final Optional<Revision> moduleRevision = module.getRevision();
if (basePackageName != null && moduleName != null && typedef != null && typedef.getQName() != null) {
final String typedefName = typedef.getQName().getLocalName();
final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
(UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
genTOBuilder.setTypedef(true);
genTOBuilder.setIsUnion(true);
- addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+ addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
returnType = genTOBuilder.toInstance();
// union builder
final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
basePackageName, bitsTypeDefinition, typedefName, module.getName());
genTOBuilder.setTypedef(true);
- addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+ addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
returnType = genTOBuilder.toInstance();
} else {
returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
}
if (returnType != null) {
- final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
+ final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
+ genTypeDefsContextMap.get(moduleName);
Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
if (typeMap != null) {
if (typeMap.isEmpty()) {
* JAVA <code>Type</code> to which is <code>typedef</code> mapped
* @return generated transfer object which represent<code>javaType</code>
*/
- private static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef, final Type javaType, final String moduleName) {
+ private static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName,
+ final TypeDefinition<?> typedef, final Type javaType, final String moduleName) {
Preconditions.checkNotNull(javaType, "javaType cannot be null");
final String propertyName = "value";
final List<String> regExps = resolveRegExpressionsFromTypedef(typedef);
addStringRegExAsConstant(genTOBuilder, regExps);
}
- addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+ addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
genTOBuilder.setTypedef(true);
makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
return genTOBuilder.toInstance();
* <li>if Qname of <code>typedef</code> is null</li>
* </ul>
*/
- public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName, final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
+ public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
+ final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
if (typeDefName != null && !typeDefName.isEmpty()) {
final String typeName = BindingMapping.getClassName(typeDefName);
unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
- final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
+ final String typedefDescription = encodeAngleBrackets(typedef.getDescription().orElse(null));
unionGenTOBuilder.setDescription(typedefDescription);
- unionGenTOBuilder.setReference(typedef.getReference());
+ unionGenTOBuilder.setReference(typedef.getReference().orElse(null));
unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
unionGenTOBuilder.setModuleName(module.getName());
} else {
* bigger one due to recursive call of
* <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
*/
- private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
+ private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
+ final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
basePackageName, unionSubtype, newTOBuilderName, parentNode);
private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
final Module typeModule = findParentModule(schemaContext, parentNode);
if (typeModule != null && typeModule.getName() != null) {
- final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
+ final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
if (genTOs != null) {
return genTOs.get(searchedTypeName);
if (!(newTypeDef instanceof UnionTypeDefinition)) {
final Module parentModule = findParentModule(schemaContext, parentNode);
if (parentModule != null && parentModule.getName() != null) {
- final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
+ final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
}
if (packageName != null && typeDefTOName != null) {
final String genTOName = BindingMapping.getClassName(typeDefTOName);
final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
- final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
+ final String typedefDescription = encodeAngleBrackets(typedef.getDescription().orElse(null));
newType.setDescription(typedefDescription);
- newType.setReference(typedef.getReference());
+ newType.setReference(typedef.getReference().orElse(null));
newType.setSchemaPath(typedef.getPath().getPathFromRoot());
newType.setModuleName(moduleName);
* <li>if <code>basePackageName</code> equals null</li>
* </ul>
*/
- public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName, final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
+ public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
+ final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
final String typeName = BindingMapping.getClassName(typeDefName);
final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
- final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
+ final String typedefDescription = encodeAngleBrackets(typeDef.getDescription().orElse(null));
genTOBuilder.setDescription(typedefDescription);
- genTOBuilder.setReference(typeDef.getReference());
+ genTOBuilder.setReference(typeDef.getReference().orElse(null));
genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
genTOBuilder.setModuleName(moduleName);
genTOBuilder.setBaseType(typeDef);
final List<String> regExps = new ArrayList<>(patternConstraints.size());
for (final PatternConstraint patternConstraint : patternConstraints) {
- final String regEx = patternConstraint.getRegularExpression();
+ final String regEx = patternConstraint.getJavaPatternString();
final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
regExps.add(modifiedRegEx);
}
final String classTypedefName = BindingMapping.getClassName(typedefName);
final String innerTypeDef = innerExtendedType.getQName().getLocalName();
final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
- final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
+ final String typedefDescription = encodeAngleBrackets(typedef.getDescription().orElse(null));
genTOBuilder.setDescription(typedefDescription);
- genTOBuilder.setReference(typedef.getReference());
+ genTOBuilder.setReference(typedef.getReference().orElse(null));
genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
genTOBuilder.setModuleName(moduleName);
genTOBuilder.setTypedef(true);
genTOBuilder.setIsUnion(true);
}
- Map<Date, Map<String, Type>> modulesByDate = null;
+ Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
Map<String, Type> typeMap = null;
final Module parentModule = findParentModule(schemaContext, innerExtendedType);
if (parentModule != null) {
genTOBuilder.setExtendsType((GeneratedTransferObject) type);
}
}
- addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+ addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
makeSerializable(genTOBuilder);
return genTOBuilder.toInstance();
@Override
public String getTypeDefaultConstruction(final LeafSchemaNode node) {
- return getTypeDefaultConstruction(node, node.getDefault());
+ return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
}
public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
private Module getParentModule(final SchemaNode node) {
final QName qname = node.getPath().getPathFromRoot().iterator().next();
- final URI namespace = qname.getNamespace();
- final Date revision = qname.getRevision();
- return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
+ return schemaContext.findModule(qname.getModule()).orElse(null);
}
private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
if (type.getBaseType() != null) {
final QName typeQName = type.getQName();
Module module = null;
- final Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
+ final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
if (modules.size() > 1) {
for (final Module m : modules) {
if (m.getRevision().equals(typeQName.getRevision())) {
}
if (module == null) {
final List<Module> modulesList = new ArrayList<>(modules);
- Collections.sort(modulesList, (o1, o2) -> o1.getRevision().compareTo(o2.getRevision()));
+ Collections.sort(modulesList, (o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
module = modulesList.get(0);
}
} else {
} else {
final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
final QName first = path.next();
+ final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
+ final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
if (!path.hasNext()) {
- final URI namespace = first.getNamespace();
- final Date revision = first.getRevision();
- final Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
parentName = BindingMapping.getClassName(parent.getName()) + "Data";
- final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
} else {
- final URI namespace = first.getNamespace();
- final Date revision = first.getRevision();
- final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
- final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
className = packageName + "." + BindingMapping.getClassName(node.getQName());
}
}
- return union(className, node.getDefault(), node);
+ return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
}
private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
import java.util.Collection;
import java.util.List;
import java.util.Set;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
} else if (childNode instanceof ListSchemaNode) {
fillRecursively(list, (ListSchemaNode) childNode);
} else if (childNode instanceof ChoiceSchemaNode) {
- final Set<ChoiceCaseNode> cases = ((ChoiceSchemaNode) childNode).getCases();
- if (cases != null) {
- for (final ChoiceCaseNode caseNode : cases) {
- fillRecursively(list, caseNode);
- }
+ for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) childNode).getCases().values()) {
+ fillRecursively(list, caseNode);
}
}
}
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import java.io.IOException;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
import org.opendaylight.mdsal.binding.model.api.MethodSignature;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class AugmentRelativeXPathTest extends AbstractTypesTest {
}
@Test
- public void AugmentationWithRelativeXPathTest() throws IOException, SourceException, ReactorException {
+ public void AugmentationWithRelativeXPathTest() {
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(testModels);
assertNotNull("context is null", context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import java.io.File;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
public class AugmentedTypeTest {
@Test
- public void augmentedAbstractTopologyTest() throws Exception {
- File abstractTopology = new File(getClass().getResource(
- "/augment-test-models/abstract-topology@2013-02-08.yang").toURI());
- File augmentTopology = new File(getClass().getResource(
- "/augment-test-models/augment-abstract-topology@2013-05-03.yang").toURI());
- File augmentNetworkLink = new File(getClass().getResource(
- "/augment-test-models/augment-network-link-attributes@2013-05-03.yang").toURI());
- File augmentTopologyTunnels = new File(getClass().getResource(
- "/augment-test-models/augment-topology-tunnels@2013-05-03.yang").toURI());
- File ietfInterfaces = new File(getClass().getResource("/augment-test-models/ietf-interfaces@2012-11-15.yang")
- .toURI());
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(abstractTopology, augmentTopology,
- augmentNetworkLink, augmentTopologyTunnels, ietfInterfaces);
+ public void augmentedAbstractTopologyTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResources(AugmentedTypeTest.class,
+ "/augment-test-models/abstract-topology@2013-02-08.yang",
+ "/augment-test-models/augment-abstract-topology@2013-05-03.yang",
+ "/augment-test-models/augment-network-link-attributes@2013-05-03.yang",
+ "/augment-test-models/augment-topology-tunnels@2013-05-03.yang",
+ "/augment-test-models/ietf-interfaces@2012-11-15.yang");
assertNotNull("Schema Context is null", context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
import static org.junit.Assert.assertNotNull;
import java.io.File;
-import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class BinaryTypeTest {
}
@Test
- public void binaryTypeTest() throws IOException, SourceException, ReactorException {
- final SchemaContext context = YangParserTestUtils.parseYangSources(yangModels);
+ public void binaryTypeTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(yangModels);
assertNotNull("context is null", context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import com.google.common.collect.ImmutableList;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URISyntaxException;
import java.util.List;
import org.junit.Test;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class BindingGeneratorImplTest {
@Test
- public void isisTotpologyStatementParserTest() throws IOException,
- URISyntaxException, ReactorException {
- final InputStream topo = getClass().getResourceAsStream("/isis-topology/network-topology@2013-10-21.yang");
- final InputStream isis = getClass().getResourceAsStream("/isis-topology/isis-topology@2013-10-21.yang");
- final InputStream l3 = getClass().getResourceAsStream("/isis-topology/l3-unicast-igp-topology@2013-10-21.yang");
-
- SchemaContext context = YangParserTestUtils.parseYangStreams(ImmutableList.of(isis, l3, topo));
+ public void isisTotpologyStatementParserTest() {
+ SchemaContext context = YangParserTestUtils.parseYangResources(BindingGeneratorImplTest.class,
+ "/isis-topology/network-topology@2013-10-21.yang", "/isis-topology/isis-topology@2013-10-21.yang",
+ "/isis-topology/l3-unicast-igp-topology@2013-10-21.yang");
assertNotNull(context);
List<Type> generateTypes = new BindingGeneratorImpl(false)
}
@Test
- public void choiceNodeGenerationTest() throws IOException,
- URISyntaxException, ReactorException {
- File resourceFile = new File(getClass().getResource(
- "/binding-generator-impl-test/choice-test.yang").toURI());
-
- SchemaContext context = YangParserTestUtils.parseYangSources(resourceFile);
+ public void choiceNodeGenerationTest() {
+ SchemaContext context = YangParserTestUtils.parseYangResource("/binding-generator-impl-test/choice-test.yang");
- List<Type> generateTypes = new BindingGeneratorImpl(false)
- .generateTypes(context);
+ List<Type> generateTypes = new BindingGeneratorImpl(false).generateTypes(context);
GeneratedType choiceTestData = null;
GeneratedType myRootContainer = null;
}
@Test
- public void notificationGenerationTest() throws IOException, URISyntaxException, ReactorException {
- File resourceFile = new File(getClass().getResource(
- "/binding-generator-impl-test/notification-test.yang").toURI());
+ public void notificationGenerationTest() {
+ SchemaContext context = YangParserTestUtils.parseYangResource(
+ "/binding-generator-impl-test/notification-test.yang");
- SchemaContext context = YangParserTestUtils.parseYangSources(resourceFile);
-
- List<Type> generateTypes = new BindingGeneratorImpl(false)
- .generateTypes(context);
+ List<Type> generateTypes = new BindingGeneratorImpl(false).generateTypes(context);
GeneratedType foo = null;
for (Type type : generateTypes) {
import static org.opendaylight.mdsal.binding.generator.impl.SupportTestUtil.containsAttributes;
import static org.opendaylight.mdsal.binding.generator.impl.SupportTestUtil.containsMethods;
-import java.io.File;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class BitAndUnionTOEnclosingTest {
- private final static List<File> testModels = new ArrayList<>();
private static List<Type> genTypes = null;
private static GeneratedType parentContainer = null;
- public static void parseResources() throws IOException, SourceException, ReactorException {
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ @BeforeClass
+ public static void loadTestResources() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/bit_and_union.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
}
- @BeforeClass
- public static void loadTestResources() throws IOException, URISyntaxException, SourceException, ReactorException {
- final File listModelFile = new File(ExtendedTypedefTest.class.getResource("/bit_and_union.yang").toURI());
- testModels.add(listModelFile);
- parseResources();
- }
-
@Test
public void testNestedTypesInLeaf() {
GeneratedTransferObject lfLeaf = null;
for (Type type : genTypes) {
if (type instanceof GeneratedType) {
GeneratedType genType = (GeneratedType) type;
- if (genType.getName().equals("TypeUnion") && (genType instanceof GeneratedTransferObject)) {
+ if (genType.getName().equals("TypeUnion") && genType instanceof GeneratedTransferObject) {
typeUnionTypedef = (GeneratedTransferObject) genType;
typeUnionTypedefCounter++;
}
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import java.io.File;
-import java.io.IOException;
-import java.net.URISyntaxException;
import java.util.List;
import org.junit.Test;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class Bug4145Test {
@Test
- public void bug4145Test() throws URISyntaxException, IOException, YangSyntaxErrorException, ReactorException {
- File resourceFile = new File(getClass().getResource(
- "/bug-4145/foo.yang").toURI());
+ public void bug4145Test() {
+ SchemaContext context = YangParserTestUtils.parseYangResource("/bug-4145/foo.yang");
- SchemaContext context = YangParserTestUtils.parseYangSources(resourceFile);
-
- List<Type> generateTypes = new BindingGeneratorImpl(false)
- .generateTypes(context);
+ List<Type> generateTypes = new BindingGeneratorImpl(false).generateTypes(context);
assertNotNull(generateTypes);
assertTrue(generateTypes.size() > 0);
}
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.Enumeration;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
import org.opendaylight.mdsal.binding.model.api.Type;
@Ignore
@Test
public void bug6135Test() throws FileNotFoundException, ReactorException, URISyntaxException {
- final SchemaContext context = YangParserTestUtils.parseYangSource("/bug-6135/foo.yang");
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/bug-6135/foo.yang");
assertNotNull(context);
final List<Type> generateTypes = new BindingGeneratorImpl(false).generateTypes(context);
import static org.opendaylight.mdsal.binding.generator.impl.SupportTestUtil.containsInterface;
import static org.opendaylight.mdsal.binding.generator.impl.SupportTestUtil.containsMethods;
-import java.io.IOException;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class ChoiceCaseGenTypesTest extends AbstractTypesTest {
}
@Test
- public void choiceCaseResolvingTypeTest() throws IOException, SourceException, ReactorException {
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ public void choiceCaseResolvingTypeTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(testModels);
assertNotNull("context is null", context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import java.io.File;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class ControllerTest {
@Test
- public void controllerAugmentationTest() throws Exception {
- File cn = new File(getClass().getResource("/controller-models/controller-network.yang").toURI());
- File co = new File(getClass().getResource("/controller-models/controller-openflow.yang").toURI());
- File ietfInetTypes = new File(getClass().getResource("/ietf/ietf-inet-types.yang").toURI());
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(cn, co, ietfInetTypes);
+ public void controllerAugmentationTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResources(ControllerTest.class,
+ "/controller-models/controller-network.yang", "/controller-models/controller-openflow.yang",
+ "/ietf/ietf-inet-types.yang");
assertNotNull("Schema Context is null", context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import java.io.File;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.mdsal.binding.model.api.Type;
public class ExtendedTypedefTest {
@Test
- public void constantGenerationTest() throws Exception {
- File abstractTopology = new File(getClass().getResource("/typedef-of-typedef/typedef_of_typedef.yang").toURI());
- File ietfInetTypes = new File(getClass().getResource("/ietf/ietf-inet-types.yang").toURI());
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(abstractTopology, ietfInetTypes);
+ public void constantGenerationTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResources(ExtendedTypedefTest.class,
+ "/typedef-of-typedef/typedef_of_typedef.yang", "/ietf/ietf-inet-types.yang");
assertNotNull("Schema Context is null", context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import java.io.File;
-import java.io.IOException;
-import java.net.URISyntaxException;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.Enumeration;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
import org.opendaylight.mdsal.binding.model.api.MethodSignature;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class GenEnumResolvingTest {
@Test
- public void testLeafEnumResolving() throws URISyntaxException, IOException, SourceException, ReactorException {
- File ietfInterfaces = new File(getClass().getResource("/enum-test-models/ietf-interfaces@2012-11-15.yang")
- .toURI());
- File ianaIfTypeModel = new File(getClass().getResource("/ietf/iana-if-type.yang").toURI());
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(ietfInterfaces, ianaIfTypeModel);
+ public void testLeafEnumResolving() {
+ final SchemaContext context = YangParserTestUtils.parseYangResources(GenEnumResolvingTest.class,
+ "/enum-test-models/ietf-interfaces@2012-11-15.yang", "/ietf/iana-if-type.yang");
assertTrue(context != null);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void testTypedefEnumResolving() throws URISyntaxException, IOException, SourceException, ReactorException {
- File ianaIfType = new File(getClass().getResource("/ietf/iana-if-type.yang").toURI());
- final SchemaContext context = YangParserTestUtils.parseYangSources(ianaIfType);
+ public void testTypedefEnumResolving() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/ietf/iana-if-type.yang");
assertTrue(context != null);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
final List<Type> genTypes = bindingGen.generateTypes(context);
}
@Test
- public void testLeafrefEnumResolving() throws URISyntaxException, IOException, SourceException, ReactorException {
- File abstractTopology = new File(getClass().getResource("/enum-test-models/abstract-topology@2013-02-08.yang")
- .toURI());
- File ietfInterfaces = new File(getClass().getResource("/enum-test-models/ietf-interfaces@2012-11-15.yang")
- .toURI());
- File ianaIfType = new File(getClass().getResource("/ietf/iana-if-type.yang").toURI());
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(abstractTopology, ietfInterfaces,
- ianaIfType);
+ public void testLeafrefEnumResolving() {
+ final SchemaContext context = YangParserTestUtils.parseYangResources(GenEnumResolvingTest.class,
+ "/enum-test-models/abstract-topology@2013-02-08.yang", "/enum-test-models/ietf-interfaces@2012-11-15.yang",
+ "/ietf/iana-if-type.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
final List<Type> genTypes = bindingGen.generateTypes(context);
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
-import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public class GenTypesSubSetTest {
@Test
- public void genTypesFromSubsetOfTwoModulesTest() throws Exception {
- File abstractTopology = new File(getClass().getResource(
- "/leafref-test-models/abstract-topology@2013-02-08.yang").toURI());
- File ietfInterfaces = new File(getClass().getResource("/ietf/ietf-interfaces.yang").toURI());
- File ietfInetTypes = new File(getClass().getResource("/ietf/ietf-inet-types.yang").toURI());
- File ietfYangTypes = new File(getClass().getResource("/ietf/ietf-yang-types.yang").toURI());
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(abstractTopology, ietfInterfaces,
- ietfInetTypes, ietfYangTypes);
+ public void genTypesFromSubsetOfTwoModulesTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResources(GenTypesSubSetTest.class,
+ "/leafref-test-models/abstract-topology@2013-02-08.yang", "/ietf/ietf-interfaces.yang",
+ "/ietf/ietf-inet-types.yang", "/ietf/ietf-yang-types.yang");
Set<Module> modules = context.getModules();
final Set<Module> toGenModules = new HashSet<>();
}
@Test
- public void genTypesFromSubsetOfThreeModulesTest() throws Exception {
- File abstractTopology = new File(getClass().getResource(
- "/leafref-test-models/abstract-topology@2013-02-08.yang").toURI());
- File ietfInterfaces = new File(getClass().getResource("/ietf/ietf-interfaces.yang").toURI());
- File ietfInetTypes = new File(getClass().getResource("/ietf/ietf-inet-types.yang").toURI());
- File ietfYangTypes = new File(getClass().getResource("/ietf/ietf-yang-types.yang").toURI());
- File ianaIfType = new File(getClass().getResource("/ietf/iana-if-type.yang").toURI());
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(abstractTopology, ietfInterfaces,
- ietfInetTypes, ietfYangTypes, ianaIfType);
+ public void genTypesFromSubsetOfThreeModulesTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResources(GenTypesSubSetTest.class,
+ "/leafref-test-models/abstract-topology@2013-02-08.yang", "/ietf/ietf-interfaces.yang",
+ "/ietf/ietf-inet-types.yang", "/ietf/ietf-yang-types.yang", "/ietf/iana-if-type.yang");
assertNotNull("Schema Context is null", context);
final Set<Module> modules = context.getModules();
import static org.junit.Assert.assertTrue;
-import java.io.File;
-import java.net.URI;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
public class GenerateInnerClassForBitsAndUnionInLeavesTest {
@Test
- public void testInnerClassCreationForBitsAndUnionsInLeafes() throws Exception {
- final URI yangTypesPath = getClass().getResource("/bit_and_union_in_leaf.yang").toURI();
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(new File(yangTypesPath));
+ public void testInnerClassCreationForBitsAndUnionsInLeafes() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/bit_and_union_in_leaf.yang");
assertTrue(context != null);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import java.io.File;
-import java.net.URI;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
import org.opendaylight.mdsal.binding.model.api.MethodSignature;
-import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.mdsal.binding.model.api.MethodSignature.Parameter;
+import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class GeneratedTypesBitsTest {
@Test
- public void testGeneretedTypesBitsTest() throws Exception {
- final URI yangTypesPath = getClass().getResource("/simple-bits-demo.yang").toURI();
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(new File(yangTypesPath));
+ public void testGeneretedTypesBitsTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/simple-bits-demo.yang");
assertTrue(context != null);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
hashPropertiesNum = genProperties.size();
}
- } else if (type instanceof GeneratedType) { // searching for
- // interface
- // LeafParameterContainer
+ } else if (type instanceof GeneratedType) {
+ // searching for interface LeafParameterContainer
final GeneratedType genType = (GeneratedType) type;
if (genType.getName().equals("LeafParentContainer")) {
leafParentFound = true;
// check of methods
methodSignaturesList = genType.getMethodDefinitions();
if (methodSignaturesList != null) {
- for (MethodSignature methodSignature : methodSignaturesList) { // loop
- // through
- // all
- // methods
+ // loop through all methods
+ for (MethodSignature methodSignature : methodSignaturesList) {
if (methodSignature.getName().equals("getByteLeaf")) {
getByteLeafMethodFound = true;
}
}
}
-
}
assertTrue(byteTypeFound);
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import java.io.File;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
import org.opendaylight.mdsal.binding.model.api.MethodSignature;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class GeneratedTypesLeafrefTest {
@Test
- public void testLeafrefResolving() throws URISyntaxException, IOException, SourceException, ReactorException {
- File abstractTopology = new File(getClass().getResource(
- "/leafref-test-models/abstract-topology@2013-02-08.yang").toURI());
- File ietfInterfaces = new File(getClass().getResource("/ietf/ietf-interfaces.yang").toURI());
- File ietfInetTypes = new File(getClass().getResource("/ietf/ietf-inet-types.yang").toURI());
- File ietfYangTypes = new File(getClass().getResource("/ietf/ietf-yang-types.yang").toURI());
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(abstractTopology, ietfInterfaces,
- ietfInetTypes, ietfYangTypes);
+ public void testLeafrefResolving() {
+ final SchemaContext context = YangParserTestUtils.parseYangResources(GeneratedTypesLeafrefTest.class,
+ "/leafref-test-models/abstract-topology@2013-02-08.yang", "/ietf/ietf-interfaces.yang",
+ "/ietf/ietf-inet-types.yang", "/ietf/ietf-yang-types.yang");
assertNotNull(context);
assertEquals(4, context.getModules().size());
}
@Test
- public void testLeafrefInvalidPathResolving() throws URISyntaxException, IOException, SourceException, ReactorException {
- final URI resource = getClass().getResource("/leafref-test-invalid-model/foo.yang").toURI();
- assertNotNull(resource);
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(new File(resource));
+ public void testLeafrefInvalidPathResolving() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/leafref-test-invalid-model/foo.yang");
assertNotNull(context);
assertEquals(1, context.getModules().size());
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import java.io.File;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
import java.util.List;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.Constant;
import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class GeneratedTypesStringTest {
- private final static List<File> testModels = new ArrayList<>();
-
- @BeforeClass
- public static void loadTestResources() throws URISyntaxException {
- final File listModelFile = new File(GeneratedTypesStringTest.class.getResource("/simple-string-demo.yang")
- .toURI());
- testModels.add(listModelFile);
- }
-
@Test
- public void constantGenerationTest() throws IOException, SourceException, ReactorException {
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ public void constantGenerationTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/simple-string-demo.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import java.io.File;
-import java.io.IOException;
-import java.net.URISyntaxException;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
import org.opendaylight.mdsal.binding.model.api.MethodSignature;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class GeneratedTypesTest {
@Test
- public void testMultipleModulesResolving() throws URISyntaxException, IOException, SourceException, ReactorException {
- File abstractTopology = new File(getClass().getResource("/abstract-topology.yang").toURI());
- File ietfInetTypes = new File(getClass().getResource("/ietf/ietf-inet-types.yang").toURI());
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(abstractTopology, ietfInetTypes);
+ public void testMultipleModulesResolving() {
+ final SchemaContext context = YangParserTestUtils.parseYangResources(GeneratedTypesTest.class,
+ "/abstract-topology.yang", "/ietf/ietf-inet-types.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void testContainerResolving() throws URISyntaxException, IOException, SourceException, ReactorException {
- final File testFile = new File(getClass().getResource("/simple-container-demo.yang").toURI());
- final SchemaContext context = YangParserTestUtils.parseYangSources(testFile);
+ public void testContainerResolving() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/simple-container-demo.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void testLeafListResolving() throws URISyntaxException, IOException, SourceException, ReactorException {
- final File testFile = new File(getClass().getResource("/simple-leaf-list-demo.yang").toURI());
- final SchemaContext context = YangParserTestUtils.parseYangSources(testFile);
+ public void testLeafListResolving() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/simple-leaf-list-demo.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void testListResolving() throws URISyntaxException, IOException, SourceException, ReactorException {
- final File testFile = new File(getClass().getResource("/simple-list-demo.yang").toURI());
- final SchemaContext context = YangParserTestUtils.parseYangSources(testFile);
+ public void testListResolving() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/simple-list-demo.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void testListCompositeKeyResolving() throws URISyntaxException, IOException, SourceException, ReactorException {
- final File testFile = new File(getClass().getResource("/list-composite-key.yang").toURI());
- final SchemaContext context = YangParserTestUtils.parseYangSources(testFile);
+ public void testListCompositeKeyResolving() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/list-composite-key.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void testGeneratedTypes() throws URISyntaxException, IOException, SourceException, ReactorException {
- final File testFile = new File(getClass().getResource("/demo-topology.yang").toURI());
- final SchemaContext context = YangParserTestUtils.parseYangSources(testFile);
+ public void testGeneratedTypes() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/demo-topology.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
import static org.junit.Assert.assertNotNull;
import java.io.File;
-import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
import org.opendaylight.mdsal.binding.model.api.MethodSignature;
import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class IdentityrefTypeTest {
* Test mainly for the method
* TypeProviderImpl#provideTypeForIdentityref(IdentityrefTypeDefinition)
* provideTypeForIdentityref}
- * @throws ReactorException Reactor exception
- * @throws SourceException Source exception
- * @throws IOException IOException
*/
@Test
- public void testIdentityrefYangBuiltInType() throws IOException, SourceException, ReactorException {
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ public void testIdentityrefYangBuiltInType() {
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(testModels);
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import java.io.File;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
import java.util.Set;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.mdsal.binding.yang.types.TypeProviderImpl;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
private Module m;
@BeforeClass
- public static void setup() throws Exception {
- File abstractTopology = new File(TypeProviderIntegrationTest.class.getResource("/type-provider/test.yang")
- .toURI());
- File ietfInetTypes = new File(TypeProviderIntegrationTest.class.getResource("/ietf/ietf-inet-types.yang")
- .toURI());
- context = YangParserTestUtils.parseYangSources(abstractTopology, ietfInetTypes);
+ public static void setup() {
+ context = YangParserTestUtils.parseYangResources(TypeProviderIntegrationTest.class, "/type-provider/test.yang",
+ "/ietf/ietf-inet-types.yang");
assertNotNull(context);
}
@Before
- public void init() throws ParseException {
+ public void init() {
provider = new TypeProviderImpl(context);
- m = context.findModuleByName("test", new SimpleDateFormat("yyyy-MM-dd").parse("2013-10-08"));
+ m = context.findModule("test", Revision.of("2013-10-08")).get();
}
@Test
- public void testGetTypeDefaultConstructionBinary() throws ParseException {
+ public void testGetTypeDefaultConstructionBinary() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-binary");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionBits() throws ParseException {
+ public void testGetTypeDefaultConstructionBits() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-bits");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionBoolean() throws ParseException {
+ public void testGetTypeDefaultConstructionBoolean() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-boolean");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionDecimal() throws ParseException {
+ public void testGetTypeDefaultConstructionDecimal() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-decimal64");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionEmpty() throws ParseException {
+ public void testGetTypeDefaultConstructionEmpty() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-empty");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionEnumeration() throws ParseException {
+ public void testGetTypeDefaultConstructionEnumeration() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-enumeration");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionInt8() throws ParseException {
+ public void testGetTypeDefaultConstructionInt8() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-int8");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionInt16() throws ParseException {
+ public void testGetTypeDefaultConstructionInt16() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-int16");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionInt32() throws ParseException {
+ public void testGetTypeDefaultConstructionInt32() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-int32");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionInt64() throws ParseException {
+ public void testGetTypeDefaultConstructionInt64() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-int64");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionLeafref1() throws ParseException {
+ public void testGetTypeDefaultConstructionLeafref1() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-leafref");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionLeafref2() throws ParseException {
+ public void testGetTypeDefaultConstructionLeafref2() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-leafref1");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionString() throws ParseException {
+ public void testGetTypeDefaultConstructionString() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-string");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionUint8() throws ParseException {
+ public void testGetTypeDefaultConstructionUint8() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-uint8");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionUint16() throws ParseException {
+ public void testGetTypeDefaultConstructionUint16() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-uint16");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionUint32() throws ParseException {
+ public void testGetTypeDefaultConstructionUint32() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-uint32");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionUint64() throws ParseException {
+ public void testGetTypeDefaultConstructionUint64() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-uint64");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstruction() throws ParseException {
+ public void testGetTypeDefaultConstruction() {
final QName leafNode = QName.create(m.getQNameModule(), "ip-leaf");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionUnion() throws ParseException {
+ public void testGetTypeDefaultConstructionUnion() {
final QName leafNode1 = QName.create(m.getQNameModule(), "leaf-union");
LeafSchemaNode leaf = (LeafSchemaNode) m.getDataChildByName(leafNode1);
String actual = provider.getTypeDefaultConstruction(leaf);
}
@Test
- public void testGetTypeDefaultConstructionUnionNested() throws ParseException {
+ public void testGetTypeDefaultConstructionUnionNested() {
final QName containerNode1 = QName.create(m.getQNameModule(), "c1");
ContainerSchemaNode c1 = (ContainerSchemaNode) m.getDataChildByName(containerNode1);
final QName containerNode2 = QName.create(m.getQNameModule(), "c2");
}
@Test
- public void testGetParamNameFromType() throws ParseException {
- m = context.findModuleByName("ietf-inet-types", new SimpleDateFormat("yyyy-MM-dd").parse("2010-09-24"));
+ public void testGetParamNameFromType() {
+ m = context.findModule("ietf-inet-types", Revision.of("2010-09-24")).get();
Set<TypeDefinition<?>> types = m.getTypeDefinitions();
TypeDefinition<?> ipv4 = null;
TypeDefinition<?> ipv6 = null;
assertEquals("ipv4Prefix", provider.getParamNameFromType(ipv4Pref));
assertEquals("ipv6Prefix", provider.getParamNameFromType(ipv6Pref));
}
-}
\ No newline at end of file
+}
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
-import java.io.File;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
public class UnionTypeDefTest {
@Test
- public void unionTypeResolvingTest() throws Exception {
- final File abstractTopology = new File(getClass().getResource("/union-test-models/abstract-topology.yang").toURI());
- final File ietfInetTypes = new File(getClass().getResource("/ietf/ietf-inet-types.yang").toURI());
- final SchemaContext context = YangParserTestUtils.parseYangSources(abstractTopology, ietfInetTypes);
+ public void unionTypeResolvingTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResources(UnionTypeDefTest.class,
+ "/union-test-models/abstract-topology.yang", "/ietf/ietf-inet-types.yang");
assertNotNull("context is null", context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void unionTypedefLeafrefTest() throws Exception {
- final File yang = new File(getClass().getResource("/leafref_typedef_union/bug8449.yang").toURI());
- final SchemaContext schemaContext = YangParserTestUtils.parseYangSources(yang);
+ public void unionTypedefLeafrefTest() {
+ final SchemaContext schemaContext = YangParserTestUtils.parseYangResource(
+ "/leafref_typedef_union/bug8449.yang");
assertNotNull(schemaContext);
final List<Type> generateTypes = new BindingGeneratorImpl(false).generateTypes(schemaContext);
assertNotNull(generateTypes);
for (final Type type : generateTypes) {
if (type.getName().equals("Cont")) {
- final GeneratedType gt = ((GeneratedType) type);
+ final GeneratedType gt = (GeneratedType) type;
assertNotNull(gt);
final GeneratedType refType = gt.getEnclosedTypes().iterator().next();
for (final GeneratedProperty generatedProperty : refType.getProperties()) {
import static org.opendaylight.mdsal.binding.generator.impl.SupportTestUtil.containsInterface;
import static org.opendaylight.mdsal.binding.generator.impl.SupportTestUtil.containsMethods;
-import java.io.File;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class UsesTest {
- private static List<File> loadTestResources(final String testFile) {
- try {
- final List<File> testModels = new ArrayList<>();
- final File listModelFile = new File(UsesTest.class.getResource(testFile).toURI());
- testModels.add(listModelFile);
- return testModels;
- } catch (URISyntaxException e) {
- throw new IllegalStateException(e);
- }
- }
-
@Test
- public void usesInGroupingDependenciesTest() throws IOException, SourceException, ReactorException {
- List<File> testModels = loadTestResources("/uses-of-grouping/uses-of-grouping-dependencies.yang");
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ public void usesInGroupingDependenciesTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource(
+ "/uses-of-grouping/uses-of-grouping-dependencies.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void usesInCaseTest() throws IOException, SourceException, ReactorException {
- List<File> testModels = loadTestResources("/uses-of-grouping/uses-of-grouping-case.yang");
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ public void usesInCaseTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource(
+ "/uses-of-grouping/uses-of-grouping-case.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void usesInContainerTest() throws IOException, SourceException, ReactorException {
- List<File> testModels = loadTestResources("/uses-of-grouping/uses-of-grouping-container.yang");
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ public void usesInContainerTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource(
+ "/uses-of-grouping/uses-of-grouping-container.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void usesInGroupingTest() throws IOException, SourceException, ReactorException {
- List<File> testModels = loadTestResources("/uses-of-grouping/uses-of-grouping-grouping.yang");
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ public void usesInGroupingTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource(
+ "/uses-of-grouping/uses-of-grouping-grouping.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void usesInListTest() throws IOException, SourceException, ReactorException {
- List<File> testModels = loadTestResources("/uses-of-grouping/uses-of-grouping-list.yang");
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ public void usesInListTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource(
+ "/uses-of-grouping/uses-of-grouping-list.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void usesInModulTest() throws IOException, SourceException, ReactorException {
- List<File> testModels = loadTestResources("/uses-of-grouping/uses-of-grouping-modul.yang");
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ public void usesInModulTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource(
+ "/uses-of-grouping/uses-of-grouping-modul.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void usesInRpcTest() throws IOException, SourceException, ReactorException {
- List<File> testModels = loadTestResources("/uses-of-grouping/uses-of-grouping-rpc.yang");
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ public void usesInRpcTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource(
+ "/uses-of-grouping/uses-of-grouping-rpc.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void usesInAugmentTest() throws IOException, SourceException, ReactorException {
- List<File> testModels = loadTestResources("/uses-of-grouping/uses-of-grouping-augment.yang");
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ public void usesInAugmentTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource(
+ "/uses-of-grouping/uses-of-grouping-augment.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
}
@Test
- public void usesInNotification() throws IOException, SourceException, ReactorException {
- List<File> testModels = loadTestResources("/uses-of-grouping/uses-of-grouping-notification.yang");
-
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ public void usesInNotification() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource(
+ "/uses-of-grouping/uses-of-grouping-notification.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.ArrayList;
-import java.util.Date;
import java.util.List;
+import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
public class YangSchemaUtilsTest {
- private static final AugmentationSchema AUGMENTATION_SCHEMA = mock(AugmentationSchema.class);
+ private static final AugmentationSchemaNode AUGMENTATION_SCHEMA = mock(AugmentationSchemaNode.class);
private static final UnknownSchemaNode UNKNOWN_SCHEMA_NODE = mock(UnknownSchemaNode.class);
- private static final QName Q_NAME =
- QName.create(URI.create("testUri"), new Date(System.currentTimeMillis()), "foo_augment");
+ private static final QName Q_NAME = QName.create(URI.create("testUri"), "foo_augment");
@Before
public void setUp() throws Exception {
doReturn(ImmutableList.of(UNKNOWN_SCHEMA_NODE)).when(AUGMENTATION_SCHEMA).getUnknownSchemaNodes();
- doReturn(QName.create(YangSchemaUtils.AUGMENT_IDENTIFIER)).when(UNKNOWN_SCHEMA_NODE).getNodeType();
+ doReturn(QName.create("", YangSchemaUtils.AUGMENT_IDENTIFIER)).when(UNKNOWN_SCHEMA_NODE).getNodeType();
doReturn(Q_NAME).when(UNKNOWN_SCHEMA_NODE).getQName();
}
context = mock(SchemaContext.class);
final Module container = mock(Module.class);
- doReturn(null).when(context).findModuleByNamespaceAndRevision(any(), any());
+ doReturn(Optional.empty()).when(context).findModule(any(QNameModule.class));
assertNull(YangSchemaUtils.findTypeDefinition(context, SchemaPath.create(qNames, false)));
- doReturn(container).when(context).findModuleByNamespaceAndRevision(any(), any());
+ doReturn(Optional.of(container)).when(context).findModule(any(QNameModule.class));
final DataSchemaNode node = mock(DataSchemaNode.class);
doReturn(node).when(container).getDataChildByName((QName) any());
final ChoiceSchemaNode choiceNode =
mock(ChoiceSchemaNode.class, withSettings().extraInterfaces(DataSchemaNode.class));
doReturn(choiceNode).when(container).getDataChildByName((QName) any());
- final ChoiceCaseNode caseNode = mock(ChoiceCaseNode.class);
+ final CaseSchemaNode caseNode = mock(CaseSchemaNode.class);
doReturn(caseNode).when(choiceNode).getCaseNodeByName((QName) any());
doReturn(ImmutableSet.of(typeDefinition)).when(caseNode).getTypeDefinitions();
assertEquals(typeDefinition,
throw e.getCause();
}
}
-}
\ No newline at end of file
+}
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
-import java.util.Collections;
-import java.util.List;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Int16TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Int32TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Int64TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Int8TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Uint16TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Uint32TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Uint64TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Uint8TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
/**
private static BinaryTypeDefinition binary = null;
private static DecimalTypeDefinition decimal64 = null;
private static EnumTypeDefinition enumeration = null;
- private static IntegerTypeDefinition int8 = null;
- private static IntegerTypeDefinition int16 = null;
- private static IntegerTypeDefinition int32 = null;
- private static IntegerTypeDefinition int64 = null;
+ private static Int8TypeDefinition int8 = null;
+ private static Int16TypeDefinition int16 = null;
+ private static Int32TypeDefinition int32 = null;
+ private static Int64TypeDefinition int64 = null;
private static StringTypeDefinition string = null;
- private static UnsignedIntegerTypeDefinition uint8 = null;
- private static UnsignedIntegerTypeDefinition uint16 = null;
- private static UnsignedIntegerTypeDefinition uint32 = null;
- private static UnsignedIntegerTypeDefinition uint64 = null;
+ private static Uint8TypeDefinition uint8 = null;
+ private static Uint16TypeDefinition uint16 = null;
+ private static Uint32TypeDefinition uint32 = null;
+ private static Uint64TypeDefinition uint64 = null;
private static UnionTypeDefinition union = null;
private static EmptyTypeDefinition empty = null;
private static BooleanTypeDefinition bool = null;
@BeforeClass
- public static void setup() throws SourceException, ReactorException {
- final List<InputStream> modelsToParse = Collections
- .singletonList(BaseYangTypesTest.class.getResourceAsStream("/base-yang-types.yang"));
- schemaContext = YangParserTestUtils.parseYangStreams(modelsToParse);
+ public static void setup() {
+ schemaContext = YangParserTestUtils.parseYangResource("/base-yang-types.yang");
assertNotNull(schemaContext);
initTypeDefinitionsFromSchemaContext();
}
decimal64 = (DecimalTypeDefinition) baseType;
} else if (baseType instanceof EnumTypeDefinition) {
enumeration = (EnumTypeDefinition) baseType;
- } else if (baseType instanceof IntegerTypeDefinition) {
- String typeName = baseType.getQName().getLocalName();
- switch (typeName) {
- case "int8":
- int8 = (IntegerTypeDefinition) baseType;
- break;
- case "int16":
- int16 = (IntegerTypeDefinition) baseType;
- break;
- case "int32":
- int32 = (IntegerTypeDefinition) baseType;
- break;
- case "int64":
- int64 = (IntegerTypeDefinition) baseType;
- break;
- }
+ } else if (baseType instanceof Int8TypeDefinition) {
+ int8 = (Int8TypeDefinition) baseType;
+ } else if (baseType instanceof Int16TypeDefinition) {
+ int16 = (Int16TypeDefinition) baseType;
+ } else if (baseType instanceof Int32TypeDefinition) {
+ int32 = (Int32TypeDefinition) baseType;
+ } else if (baseType instanceof Int64TypeDefinition) {
+ int64 = (Int64TypeDefinition) baseType;
} else if (baseType instanceof StringTypeDefinition) {
string = (StringTypeDefinition) baseType;
- } else if (baseType instanceof UnsignedIntegerTypeDefinition) {
- String typeName = baseType.getQName().getLocalName();
- switch (typeName) {
- case "uint8":
- uint8 = (UnsignedIntegerTypeDefinition) baseType;
- break;
- case "uint16":
- uint16 = (UnsignedIntegerTypeDefinition) baseType;
- break;
- case "uint32":
- uint32 = (UnsignedIntegerTypeDefinition) baseType;
- break;
- case "uint64":
- uint64 = (UnsignedIntegerTypeDefinition) baseType;
- break;
- }
+ } else if (baseType instanceof Uint8TypeDefinition) {
+ uint8 = (Uint8TypeDefinition) baseType;
+ } else if (baseType instanceof Uint16TypeDefinition) {
+ uint16 = (Uint16TypeDefinition) baseType;
+ } else if (baseType instanceof Uint32TypeDefinition) {
+ uint32 = (Uint32TypeDefinition) baseType;
+ } else if (baseType instanceof Uint64TypeDefinition) {
+ uint64 = (Uint64TypeDefinition) baseType;
} else if (baseType instanceof UnionTypeDefinition) {
union = (UnionTypeDefinition) baseType;
} else if (baseType instanceof EmptyTypeDefinition) {
public void javaTypeForRestrictedSchemaDefinitionTypeTest() {
final TypeProvider typeProvider = BaseYangTypes.BASE_YANG_TYPES_PROVIDER;
- Type javaType = typeProvider.javaTypeForSchemaDefinitionType(binary, binary, BindingGeneratorUtil.getRestrictions(binary));
+ Type javaType = typeProvider.javaTypeForSchemaDefinitionType(binary, binary,
+ BindingGeneratorUtil.getRestrictions(binary));
assertNotNull(javaType);
assertEquals("byte[]", javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(decimal64, decimal64, BindingGeneratorUtil.getRestrictions(decimal64));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(decimal64, decimal64,
+ BindingGeneratorUtil.getRestrictions(decimal64));
assertNotNull(javaType);
assertEquals(BigDecimal.class.getCanonicalName(), javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(enumeration, enumeration, BindingGeneratorUtil.getRestrictions(enumeration));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(enumeration, enumeration,
+ BindingGeneratorUtil.getRestrictions(enumeration));
assertNotNull(javaType);
assertEquals(Enum.class.getCanonicalName(), javaType.getFullyQualifiedName());
assertNotNull(javaType);
assertEquals(Byte.class.getCanonicalName(), javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(int16, int16, BindingGeneratorUtil.getRestrictions(int16));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(int16, int16,
+ BindingGeneratorUtil.getRestrictions(int16));
assertNotNull(javaType);
assertEquals(Short.class.getCanonicalName(), javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(int32, int32, BindingGeneratorUtil.getRestrictions(int32));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(int32, int32,
+ BindingGeneratorUtil.getRestrictions(int32));
assertNotNull(javaType);
assertEquals(Integer.class.getCanonicalName(), javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(int64, int64, BindingGeneratorUtil.getRestrictions(int64));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(int64, int64,
+ BindingGeneratorUtil.getRestrictions(int64));
assertNotNull(javaType);
assertEquals(Long.class.getCanonicalName(), javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(string, string, BindingGeneratorUtil.getRestrictions(string));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(string, string,
+ BindingGeneratorUtil.getRestrictions(string));
assertNotNull(javaType);
assertEquals(String.class.getCanonicalName(), javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(uint8, uint8, BindingGeneratorUtil.getRestrictions(uint8));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(uint8, uint8,
+ BindingGeneratorUtil.getRestrictions(uint8));
assertNotNull(javaType);
assertEquals(Short.class.getCanonicalName(), javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(uint16, uint16, BindingGeneratorUtil.getRestrictions(uint16));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(uint16, uint16,
+ BindingGeneratorUtil.getRestrictions(uint16));
assertNotNull(javaType);
assertEquals(Integer.class.getCanonicalName(), javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(uint32, uint32, BindingGeneratorUtil.getRestrictions(uint32));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(uint32, uint32,
+ BindingGeneratorUtil.getRestrictions(uint32));
assertNotNull(javaType);
assertEquals(Long.class.getCanonicalName(), javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(uint64, uint64, BindingGeneratorUtil.getRestrictions(uint64));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(uint64, uint64,
+ BindingGeneratorUtil.getRestrictions(uint64));
assertNotNull(javaType);
assertEquals(BigInteger.class.getCanonicalName(), javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(union, union, BindingGeneratorUtil.getRestrictions(union));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(union, union,
+ BindingGeneratorUtil.getRestrictions(union));
assertNotNull(javaType);
assertEquals("Union", javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(empty, empty, BindingGeneratorUtil.getRestrictions(empty));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(empty, empty,
+ BindingGeneratorUtil.getRestrictions(empty));
assertNotNull(javaType);
assertEquals(Boolean.class.getCanonicalName(), javaType.getFullyQualifiedName());
- javaType = typeProvider.javaTypeForSchemaDefinitionType(bool, bool, BindingGeneratorUtil.getRestrictions(bool));
+ javaType = typeProvider.javaTypeForSchemaDefinitionType(bool, bool,
+ BindingGeneratorUtil.getRestrictions(bool));
assertNotNull(javaType);
assertEquals(Boolean.class.getCanonicalName(), javaType.getFullyQualifiedName());
}
import static org.junit.Assert.assertNotNull;
-import java.io.File;
-import java.io.FileNotFoundException;
import java.net.URI;
-import java.net.URISyntaxException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.opendaylight.mdsal.binding.yang.types.TypeProviderImpl;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class Bug4621 {
public ExpectedException expectedEx = ExpectedException.none();
@Test
- public void bug4621test() throws FileNotFoundException, ReactorException, URISyntaxException {
- File file = new File(getClass().getResource("/bug-4621/foo.yang").toURI());
-
- final SchemaContext schemaContext = YangParserTestUtils.parseYangSources(file);
- final Module moduleValid = schemaContext.findModuleByNamespace(new URI("foo")).iterator().next();
+ public void bug4621test() {
+ final SchemaContext schemaContext = YangParserTestUtils.parseYangResource("/bug-4621/foo.yang");
+ final Module moduleValid = schemaContext.findModules(URI.create("foo")).iterator().next();
final TypeProviderImpl typeProvider = new TypeProviderImpl(schemaContext);
expectedEx.expect(IllegalArgumentException.class);
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
List<GroupingDefinition> unsortedGroupingDefs = new ArrayList<>();
GroupingDefinition grp1 = mock(GroupingDefinition.class);
- doReturn(SchemaPath.create(false, QName.create("Cont1"), QName.create("Cont2"))).when(grp1).getPath();
- doReturn(QName.create("leaf1")).when(grp1).getQName();
+ doReturn(SchemaPath.create(false, QName.create("", "Cont1"), QName.create("", "Cont2"))).when(grp1).getPath();
+ doReturn(QName.create("", "leaf1")).when(grp1).getQName();
doReturn(Collections.EMPTY_SET).when(grp1).getUses();
doReturn(Collections.EMPTY_SET).when(grp1).getGroupings();
doReturn(Collections.EMPTY_SET).when(grp1).getChildNodes();
GroupingDefinition grp2 = mock(GroupingDefinition.class);
- doReturn(SchemaPath.create(false, QName.create("Cont1"))).when(grp2).getPath();
- doReturn(QName.create("leaf2")).when(grp2).getQName();
+ doReturn(SchemaPath.create(false, QName.create("", "Cont1"))).when(grp2).getPath();
+ doReturn(QName.create("", "leaf2")).when(grp2).getQName();
doReturn(Collections.EMPTY_SET).when(grp2).getUses();
doReturn(Collections.EMPTY_SET).when(grp2).getGroupings();
doReturn(Collections.EMPTY_SET).when(grp2).getChildNodes();
GroupingDefinition grp3 = mock(GroupingDefinition.class);
- doReturn(SchemaPath.create(false, QName.create("Cont1"), QName.create("Cont2"))).when(grp3).getPath();
- doReturn(QName.create("leaf3")).when(grp3).getQName();
+ doReturn(SchemaPath.create(false, QName.create("", "Cont1"), QName.create("", "Cont2"))).when(grp3).getPath();
+ doReturn(QName.create("", "leaf3")).when(grp3).getQName();
doReturn(Collections.EMPTY_SET).when(grp3).getUses();
doReturn(Collections.EMPTY_SET).when(grp3).getGroupings();
doReturn(Collections.EMPTY_SET).when(grp3).getChildNodes();
GroupingDefinition grp4 = mock(GroupingDefinition.class);
- doReturn(SchemaPath.create(false, QName.create("Cont1"), QName.create("Cont2"), QName.create("List1"))).when(grp4).getPath();
- doReturn(QName.create("leaf4")).when(grp4).getQName();
+ doReturn(SchemaPath.create(false, QName.create("", "Cont1"), QName.create("", "Cont2"),
+ QName.create("", "List1"))).when(grp4).getPath();
+ doReturn(QName.create("", "leaf4")).when(grp4).getQName();
doReturn(Collections.EMPTY_SET).when(grp4).getUses();
doReturn(Collections.EMPTY_SET).when(grp4).getGroupings();
doReturn(Collections.EMPTY_SET).when(grp4).getChildNodes();
GroupingDefinition grp5 = mock(GroupingDefinition.class);
- doReturn(SchemaPath.create(false, QName.create("Cont1"))).when(grp5).getPath();
- doReturn(QName.create("leaf5")).when(grp5).getQName();
+ doReturn(SchemaPath.create(false, QName.create("", "Cont1"))).when(grp5).getPath();
+ doReturn(QName.create("", "leaf5")).when(grp5).getQName();
doReturn(Collections.EMPTY_SET).when(grp5).getUses();
doReturn(Collections.EMPTY_SET).when(grp5).getGroupings();
doReturn(Collections.EMPTY_SET).when(grp5).getChildNodes();
package org.opendaylight.mdsal.binding.yang.types;
import java.util.List;
+import java.util.Optional;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
* Created by lukas on 9/17/14.
*/
public class LeafrefTypeWithNullToStringInXpath implements LeafrefTypeDefinition {
- @Override public RevisionAwareXPath getPathStatement() {
+ @Override
+ public RevisionAwareXPath getPathStatement() {
return new RevisionAwareXPath() {
@Override
public boolean isAbsolute() {
};
}
- @Override public LeafrefTypeDefinition getBaseType() {
+ @Override
+ public LeafrefTypeDefinition getBaseType() {
return null;
}
- @Override public String getUnits() {
- return null;
+ @Override
+ public Optional<String> getUnits() {
+ return Optional.empty();
}
- @Override public Object getDefaultValue() {
- return null;
+ @Override
+ public Optional<? extends Object> getDefaultValue() {
+ return Optional.empty();
}
- @Override public QName getQName() {
+ @Override
+ public QName getQName() {
return null;
}
- @Override public SchemaPath getPath() {
+ @Override
+ public SchemaPath getPath() {
return null;
}
- @Override public List<UnknownSchemaNode> getUnknownSchemaNodes() {
+ @Override
+ public List<UnknownSchemaNode> getUnknownSchemaNodes() {
return null;
}
- @Override public String getDescription() {
- return null;
+ @Override
+ public Optional<String> getDescription() {
+ return Optional.empty();
}
- @Override public String getReference() {
- return null;
+ @Override
+ public Optional<String> getReference() {
+ return Optional.empty();
}
- @Override public Status getStatus() {
+ @Override
+ public Status getStatus() {
return null;
}
+
+ @Override
+ public boolean requireInstance() {
+ return false;
+ }
}
package org.opendaylight.mdsal.binding.yang.types;
import java.util.List;
+import java.util.Optional;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
* @author Lukas Sedlak <lsedlak@cisco.com>
*/
public class LeafrefTypeWithNullXpath implements LeafrefTypeDefinition {
- @Override public RevisionAwareXPath getPathStatement() {
+ @Override
+ public RevisionAwareXPath getPathStatement() {
return null;
}
- @Override public LeafrefTypeDefinition getBaseType() {
+ @Override
+ public LeafrefTypeDefinition getBaseType() {
return null;
}
- @Override public String getUnits() {
- return null;
+ @Override
+ public Optional<String> getUnits() {
+ return Optional.empty();
}
- @Override public Object getDefaultValue() {
- return null;
+ @Override
+ public Optional<? extends Object> getDefaultValue() {
+ return Optional.empty();
}
- @Override public QName getQName() {
+ @Override
+ public QName getQName() {
return null;
}
- @Override public SchemaPath getPath() {
+ @Override
+ public SchemaPath getPath() {
return null;
}
- @Override public List<UnknownSchemaNode> getUnknownSchemaNodes() {
+ @Override
+ public List<UnknownSchemaNode> getUnknownSchemaNodes() {
return null;
}
- @Override public String getDescription() {
- return null;
+ @Override
+ public Optional<String> getDescription() {
+ return Optional.empty();
}
- @Override public String getReference() {
- return null;
+ @Override
+ public Optional<String> getReference() {
+ return Optional.empty();
}
- @Override public Status getStatus() {
+ @Override
+ public Status getStatus() {
return null;
}
+
+ @Override
+ public boolean requireInstance() {
+ return false;
+ }
}
package org.opendaylight.mdsal.binding.yang.types;
import java.util.List;
+import java.util.Optional;
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.IntegerTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Int8TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
/**
*
* @author Lukas Sedlak <lsedlak@cisco.com>
*/
-final class TestIntegerTypeDefinition implements IntegerTypeDefinition {
+final class TestIntegerTypeDefinition implements Int8TypeDefinition {
- @Override public List<RangeConstraint> getRangeConstraints() {
+ @Override
+ public Int8TypeDefinition getBaseType() {
return null;
}
- @Override public IntegerTypeDefinition getBaseType() {
- return null;
+ @Override
+ public Optional<String> getUnits() {
+ return Optional.empty();
}
- @Override public String getUnits() {
- return null;
+ @Override
+ public Optional<Object> getDefaultValue() {
+ return Optional.empty();
}
- @Override public Object getDefaultValue() {
+ @Override
+ public QName getQName() {
return null;
}
- @Override public QName getQName() {
+ @Override
+ public SchemaPath getPath() {
return null;
}
- @Override public SchemaPath getPath() {
+ @Override
+ public List<UnknownSchemaNode> getUnknownSchemaNodes() {
return null;
}
- @Override public List<UnknownSchemaNode> getUnknownSchemaNodes() {
- return null;
+ @Override
+ public Optional<String> getDescription() {
+ return Optional.empty();
}
- @Override public String getDescription() {
- return null;
+ @Override
+ public Optional<String> getReference() {
+ return Optional.empty();
}
- @Override public String getReference() {
+ @Override
+ public Status getStatus() {
return null;
}
- @Override public Status getStatus() {
- return null;
+ @Override
+ public Optional<RangeConstraint<Byte>> getRangeConstraint() {
+ return Optional.empty();
}
}
package org.opendaylight.mdsal.binding.yang.types;
+import com.google.common.collect.ImmutableSet;
+import java.util.Collection;
import java.util.List;
+import java.util.Optional;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.*;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.MustDefinition;
+import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
+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.UnknownSchemaNode;
/**
* Mock Leaf Schema Node designated to increase branch coverage in test cases.
* @author Lukas Sedlak <lsedlak@cisco.com>
*/
public class TestLeafSchemaNode implements LeafSchemaNode {
- @Override public TypeDefinition<?> getType() {
+ @Override
+ public TypeDefinition<?> getType() {
return null;
}
- @Override public String getDefault() {
- return null;
- }
-
- @Override public String getUnits() {
- return null;
- }
-
- @Override public boolean isAugmenting() {
+ @Override
+ public boolean isAugmenting() {
return false;
}
- @Override public boolean isAddedByUses() {
+ @Override
+ public boolean isAddedByUses() {
return false;
}
- @Override public boolean isConfiguration() {
+ @Override
+ public boolean isConfiguration() {
return false;
}
- @Override public ConstraintDefinition getConstraints() {
+ @Override
+ public QName getQName() {
return null;
}
- @Override public QName getQName() {
+ @Override
+ public SchemaPath getPath() {
return null;
}
- @Override public SchemaPath getPath() {
+ @Override
+ public List<UnknownSchemaNode> getUnknownSchemaNodes() {
return null;
}
- @Override public List<UnknownSchemaNode> getUnknownSchemaNodes() {
- return null;
+ @Override
+ public Optional<String> getDescription() {
+ return Optional.empty();
}
- @Override public String getDescription() {
- return null;
+ @Override
+ public Optional<String> getReference() {
+ return Optional.empty();
}
- @Override public String getReference() {
+ @Override public Status getStatus() {
return null;
}
- @Override public Status getStatus() {
- return null;
+ @Override
+ public boolean isMandatory() {
+ return false;
+ }
+
+ @Override
+ public Optional<RevisionAwareXPath> getWhenCondition() {
+ return Optional.empty();
+ }
+
+ @Override
+ public Collection<MustDefinition> getMustConstraints() {
+ return ImmutableSet.of();
}
}
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
-import java.io.File;
import java.net.URI;
import java.util.NoSuchElementException;
import org.junit.Test;
public class TypeProviderImplTest {
- @Test (expected = IllegalArgumentException.class)
- public void testLeafRefRelativeSelfReference() throws Exception {
- File relative = new File(getClass().getResource("/leafref/leafref-relative-invalid.yang").toURI());
-
- final SchemaContext schemaContext = YangParserTestUtils.parseYangSources(relative);
- final Module moduleRelative = schemaContext.findModuleByNamespace(new URI("urn:xml:ns:yang:lrr")).iterator()
- .next();
+ @Test(expected = IllegalArgumentException.class)
+ public void testLeafRefRelativeSelfReference() {
+ final SchemaContext schemaContext = YangParserTestUtils.parseYangResource(
+ "/leafref/leafref-relative-invalid.yang");
+ final Module moduleRelative = schemaContext.findModules(URI.create("urn:xml:ns:yang:lrr")).iterator().next();
final TypeProviderImpl typeProvider = new TypeProviderImpl(schemaContext);
final QName listNode = QName.create(moduleRelative.getQNameModule(), "neighbor");
assertNotNull(leafrefResolvedType);
}
- @Test (expected = IllegalArgumentException.class)
- public void testLeafRefAbsoluteSelfReference() throws Exception {
- File relative = new File(getClass().getResource("/leafref/leafref-absolute-invalid.yang").toURI());
-
- final SchemaContext schemaContext = YangParserTestUtils.parseYangSources(relative);
- final Module moduleRelative = schemaContext.findModuleByNamespace(new URI("urn:xml:ns:yang:lra")).iterator()
- .next();
+ @Test(expected = IllegalArgumentException.class)
+ public void testLeafRefAbsoluteSelfReference() {
+ final SchemaContext schemaContext = YangParserTestUtils.parseYangResource(
+ "/leafref/leafref-absolute-invalid.yang");
+ final Module moduleRelative = schemaContext.findModules(URI.create("urn:xml:ns:yang:lra")).iterator().next();
final TypeProviderImpl typeProvider = new TypeProviderImpl(schemaContext);
final QName listNode = QName.create(moduleRelative.getQNameModule(), "neighbor");
}
@Test
- public void testLeafRefRelativeAndAbsoluteValidReference() throws Exception {
- File valid = new File(getClass().getResource("/leafref/leafref-valid.yang").toURI());
-
- final SchemaContext schemaContext = YangParserTestUtils.parseYangSources(valid);
- final Module moduleValid = schemaContext.findModuleByNamespace(new URI("urn:xml:ns:yang:lrv")).iterator()
- .next();
+ public void testLeafRefRelativeAndAbsoluteValidReference() {
+ final SchemaContext schemaContext = YangParserTestUtils.parseYangResource("/leafref/leafref-valid.yang");
+ final Module moduleValid = schemaContext.findModules(URI.create("urn:xml:ns:yang:lrv")).iterator().next();
final TypeProviderImpl typeProvider = new TypeProviderImpl(schemaContext);
final QName listNode = QName.create(moduleValid.getQNameModule(), "neighbor");
}
@Test
- public void testMethodsOfTypeProviderImpl() throws Exception {
- final File abstractTopology = new File(getClass().getResource("/base-yang-types.yang").toURI());
-
- final SchemaContext schemaContext = YangParserTestUtils.parseYangSources(abstractTopology);
+ public void testMethodsOfTypeProviderImpl() {
+ final SchemaContext schemaContext = YangParserTestUtils.parseYangResource("/base-yang-types.yang");
final TypeProviderImpl typeProvider = new TypeProviderImpl(schemaContext);
- final SchemaPath refTypePath = SchemaPath.create(true, QName.create("cont1"), QName.create("list1"));
+ final SchemaPath refTypePath = SchemaPath.create(true, QName.create("", "cont1"), QName.create("", "list1"));
final GeneratedTypeBuilderImpl refType = new GeneratedTypeBuilderImpl("org.opendaylight.yangtools.test",
"TestType");
typeProvider.putReferencedType(refTypePath, refType);
final LeafSchemaNode leafSchemaNode = mock(LeafSchemaNode.class);
doReturn(stringType).when(leafSchemaNode).getType();
doReturn(SchemaPath.ROOT).when(leafSchemaNode).getPath();
- doReturn(QName.create("Cont1")).when(leafSchemaNode).getQName();
+ doReturn(QName.create("", "Cont1")).when(leafSchemaNode).getQName();
// test constructor
assertNotNull(typeProvider);
reset(leafSchemaNode);
doReturn(binaryType).when(leafSchemaNode).getType();
doReturn(SchemaPath.ROOT).when(leafSchemaNode).getPath();
- doReturn(QName.create("Cont1")).when(leafSchemaNode).getQName();
+ doReturn(QName.create("", "Cont1")).when(leafSchemaNode).getQName();
assertEquals("new byte[] {-45}", typeProvider.getTypeDefaultConstruction(leafSchemaNode, "01"));
reset(leafSchemaNode);
doReturn(booleanType).when(leafSchemaNode).getType();
doReturn(SchemaPath.ROOT).when(leafSchemaNode).getPath();
- doReturn(QName.create("Cont1")).when(leafSchemaNode).getQName();
+ doReturn(QName.create("", "Cont1")).when(leafSchemaNode).getQName();
assertEquals("java.lang.Boolean.FALSE", typeProvider.getTypeDefaultConstruction(leafSchemaNode, "false"));
reset(leafSchemaNode);
doReturn(decimalType).when(leafSchemaNode).getType();
doReturn(SchemaPath.ROOT).when(leafSchemaNode).getPath();
- doReturn(QName.create("Cont1")).when(leafSchemaNode).getQName();
+ doReturn(QName.create("", "Cont1")).when(leafSchemaNode).getQName();
assertEquals("new java.math.BigDecimal(\"111\")", typeProvider.getTypeDefaultConstruction(leafSchemaNode,
"111"));
reset(leafSchemaNode);
doReturn(emptyType).when(leafSchemaNode).getType();
doReturn(SchemaPath.ROOT).when(leafSchemaNode).getPath();
- doReturn(QName.create("Cont1")).when(leafSchemaNode).getQName();
+ doReturn(QName.create("", "Cont1")).when(leafSchemaNode).getQName();
assertEquals("java.lang.Boolean.valueOf(\"default value\")", typeProvider.getTypeDefaultConstruction(
leafSchemaNode, "default value"));
reset(leafSchemaNode);
doReturn(enumType).when(leafSchemaNode).getType();
doReturn(SchemaPath.ROOT).when(leafSchemaNode).getPath();
- doReturn(QName.create("Cont1")).when(leafSchemaNode).getQName();
+ doReturn(QName.create("", "Cont1")).when(leafSchemaNode).getQName();
try {
assertEquals("\"default value\"", typeProvider.getTypeDefaultConstruction(leafSchemaNode, "default value"));
reset(leafSchemaNode);
doReturn(identityRef).when(leafSchemaNode).getType();
doReturn(SchemaPath.ROOT).when(leafSchemaNode).getPath();
- doReturn(QName.create("Cont1")).when(leafSchemaNode).getQName();
+ doReturn(QName.create("", "Cont1")).when(leafSchemaNode).getQName();
try {
assertEquals("\"default value\"", typeProvider.getTypeDefaultConstruction(leafSchemaNode, "default value"));
*/
package org.opendaylight.mdsal.binding.yang.types;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
/**
public static final String TEST_TYPE_PROVIDER_MODULE_NAME = "test-type-provider";
- private static final String BASE_YANG_TYPES_PATH = "/base-yang-types.yang";
- private static final String TEST_TYPE_PROVIDER_PATH = "/"+TEST_TYPE_PROVIDER_MODULE_NAME+".yang";
- private static final String TEST_TYPE_PROVIDER_B_PATH = "/test-type-provider-b.yang";
-
- private static InputStream getInputStream(final String resourceName) {
- return TypeProviderModel.class.getResourceAsStream(resourceName);
- }
-
- private static List<InputStream> provideTestModelStreams() {
- final List<InputStream> arrayList = new ArrayList<>();
-
- arrayList.add(getInputStream(BASE_YANG_TYPES_PATH));
- arrayList.add(getInputStream(TEST_TYPE_PROVIDER_PATH));
- arrayList.add(getInputStream(TEST_TYPE_PROVIDER_B_PATH));
- return arrayList;
- }
-
- public static SchemaContext createTestContext() throws SourceException, ReactorException {
- return YangParserTestUtils.parseYangStreams(provideTestModelStreams());
+ public static SchemaContext createTestContext() {
+ return YangParserTestUtils.parseYangResources(TypeProviderModel.class, "/base-yang-types.yang",
+ "/" + TEST_TYPE_PROVIDER_MODULE_NAME + ".yang", "/test-type-provider-b.yang");
}
}
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
+import com.google.common.collect.Range;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import org.junit.Before;
import org.junit.Ignore;
assertEquals("base-yang-types", genTO.getModuleName());
assertEquals("org.opendaylight.yang.gen.v1.urn.opendaylight.org.test.base.yang.types.rev140914", genTO.getPackageName());
assertEquals("YangInt8", genTO.getName());
- assertTrue(genTO.getProperties().size() == 1);
+ assertEquals(1, genTO.getProperties().size());
}
@Test
final GeneratedTransferObject genTO = (GeneratedTransferObject) result;
assertEquals("org.opendaylight.yang.gen.v1.urn.opendaylight.org.test.base.yang.types.rev140914", genTO.getPackageName());
assertEquals("YangInt8Restricted", genTO.getName());
- assertTrue(genTO.getProperties().size() == 1);
- final List<RangeConstraint> rangeConstraints = genTO.getRestrictions().getRangeConstraints();
+ assertEquals(1, genTO.getProperties().size());
+ final Optional<? extends RangeConstraint<?>> rangeConstraints = genTO.getRestrictions().getRangeConstraint();
- assertTrue(!rangeConstraints.isEmpty());
- final RangeConstraint constraint = rangeConstraints.get(0);
- assertEquals(1, constraint.getMin().intValue());
- assertEquals(100, constraint.getMax().intValue());
+ assertTrue(rangeConstraints.isPresent());
+ final Range<?> constraint = rangeConstraints.get().getAllowedRanges().asRanges().iterator().next();
+ assertEquals((byte) 1, constraint.lowerEndpoint());
+ assertEquals((byte) 100, constraint.upperEndpoint());
}
@Test
final QName leafListNode = QName.create(module.getQNameModule(), "enums");
final DataSchemaNode enumListNode = module.getDataChildByName(leafListNode);
- assertNotNull("leaf-list enums is not present in root of module "+ module.getName(), enumNode);
+ assertNotNull("leaf-list enums is not present in root of module " + module.getName(), enumNode);
assertTrue(enumListNode instanceof LeafListSchemaNode);
final LeafListSchemaNode leafList = (LeafListSchemaNode) enumListNode;
final TypeDefinition<?> leafListType = leafList.getType();
Type refType = new ReferencedTypeImpl(enumType.getPackageName(), enumType.getName());
((TypeProviderImpl) provider).putReferencedType(enumLeafNode.getPath(), refType);
- final LeafListSchemaNode enumListNode = provideLeafListNodeFromTopLevelContainer(this.testTypeProviderModule, "foo",
- "list-of-enums");
+ final LeafListSchemaNode enumListNode = provideLeafListNodeFromTopLevelContainer(this.testTypeProviderModule,
+ "foo", "list-of-enums");
final TypeDefinition<?> enumLeafListTypedef = enumListNode.getType();
enumType = provider.javaTypeForSchemaDefinitionType(enumLeafListTypedef, enumListNode);
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
+import java.util.Optional;
import org.opendaylight.mdsal.binding.model.api.AccessModifier;
import org.opendaylight.mdsal.binding.model.api.Restrictions;
import org.opendaylight.mdsal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
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.api.type.RangeRestrictedTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
import org.opendaylight.yangtools.yang.model.util.type.DecimalTypeBuilder;
private static final Restrictions EMPTY_RESTRICTIONS = new Restrictions() {
@Override
- public List<LengthConstraint> getLengthConstraints() {
- return Collections.emptyList();
+ public Optional<LengthConstraint> getLengthConstraint() {
+ return Optional.empty();
}
@Override
}
@Override
- public List<RangeConstraint> getRangeConstraints() {
- return Collections.emptyList();
+ public Optional<RangeConstraint<?>> getRangeConstraint() {
+ return Optional.empty();
}
@Override
* @return string with the admissible parameter name
*/
public static String resolveJavaReservedWordEquivalency(final String parameterName) {
- if ((parameterName != null) && BindingMapping.JAVA_RESERVED_WORDS.contains(parameterName)) {
+ if (parameterName != null && BindingMapping.JAVA_RESERVED_WORDS.contains(parameterName)) {
return "_" + parameterName;
}
return parameterName;
char firstChar = correctStr.charAt(0);
firstChar = uppercase ? Character.toUpperCase(firstChar) : Character.toLowerCase(firstChar);
- if ((firstChar >= '0') && (firstChar <= '9')) {
+ if (firstChar >= '0' && firstChar <= '9') {
return '_' + correctStr;
} else {
return firstChar + correctStr.substring(1);
}
for (final MethodSignatureBuilder m : sortedCollection(SUID_MEMBER_COMPARATOR, to.getMethodDefinitions())) {
- if (!(m.getAccessModifier().equals(AccessModifier.PRIVATE))) {
+ if (!m.getAccessModifier().equals(AccessModifier.PRIVATE)) {
dout.writeUTF(m.getName());
dout.write(m.getAccessModifier().ordinal());
}
final byte[] hashBytes = SHA1_MD.get().digest(bout.toByteArray());
long hash = 0;
for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
- hash = (hash << 8) | (hashBytes[i] & 0xFF);
+ hash = hash << 8 | hashBytes[i] & 0xFF;
}
return hash;
}
- private static <T> List<T> currentOrEmpty(final List<T> current, final List<T> base) {
- return current.equals(base) ? ImmutableList.<T>of() : current;
+ private static <T extends Optional<?>> T currentOrEmpty(final T current, final T base) {
+ return current.equals(base) ? (T)Optional.empty() : current;
}
private static boolean containsConstraint(final StringTypeDefinition type, final PatternConstraint constraint) {
public static Restrictions getRestrictions(final TypeDefinition<?> type) {
// Old parser generated types which actually contained based restrictions, but our code deals with that when
// binding to core Java types. Hence we'll emit empty restrictions for base types.
- if ((type == null) || (type.getBaseType() == null)) {
+ if (type == null || type.getBaseType() == null) {
// Handling of decimal64 has changed in the new parser. It contains range restrictions applied to the type
// directly, without an extended type. We need to capture such constraints. In order to retain behavior we
// need to analyze the new semantics and see if the constraints have been overridden. To do that we
tmpBuilder.setFractionDigits(decimal.getFractionDigits());
final DecimalTypeDefinition tmp = tmpBuilder.build();
- if (!tmp.getRangeConstraints().equals(decimal.getRangeConstraints())) {
+ if (!tmp.getRangeConstraint().equals(decimal.getRangeConstraint())) {
return new Restrictions() {
@Override
public boolean isEmpty() {
}
@Override
- public List<RangeConstraint> getRangeConstraints() {
- return decimal.getRangeConstraints();
+ public Optional<? extends RangeConstraint<?>> getRangeConstraint() {
+ return decimal.getRangeConstraint();
}
@Override
}
@Override
- public List<LengthConstraint> getLengthConstraints() {
- return ImmutableList.of();
+ public Optional<LengthConstraint> getLengthConstraint() {
+ return Optional.empty();
}
};
}
return EMPTY_RESTRICTIONS;
}
- final List<LengthConstraint> length;
+ final Optional<LengthConstraint> length;
final List<PatternConstraint> pattern;
- final List<RangeConstraint> range;
+ final Optional<? extends RangeConstraint<?>> range;
/*
* Take care of extended types.
if (type instanceof BinaryTypeDefinition) {
final BinaryTypeDefinition binary = (BinaryTypeDefinition)type;
final BinaryTypeDefinition base = binary.getBaseType();
- if ((base != null) && (base.getBaseType() != null)) {
- length = currentOrEmpty(binary.getLengthConstraints(), base.getLengthConstraints());
+ if (base != null && base.getBaseType() != null) {
+ length = currentOrEmpty(binary.getLengthConstraint(), base.getLengthConstraint());
} else {
- length = binary.getLengthConstraints();
+ length = binary.getLengthConstraint();
}
pattern = ImmutableList.of();
- range = ImmutableList.of();
+ range = Optional.empty();
} else if (type instanceof DecimalTypeDefinition) {
- length = ImmutableList.of();
+ length = Optional.empty();
pattern = ImmutableList.of();
final DecimalTypeDefinition decimal = (DecimalTypeDefinition)type;
final DecimalTypeDefinition base = decimal.getBaseType();
- if ((base != null) && (base.getBaseType() != null)) {
- range = currentOrEmpty(decimal.getRangeConstraints(), base.getRangeConstraints());
+ if (base != null && base.getBaseType() != null) {
+ range = currentOrEmpty(decimal.getRangeConstraint(), base.getRangeConstraint());
} else {
- range = decimal.getRangeConstraints();
+ range = decimal.getRangeConstraint();
}
- } else if (type instanceof IntegerTypeDefinition) {
- length = ImmutableList.of();
+ } else if (type instanceof RangeRestrictedTypeDefinition) {
+ // Integer-like types
+ length = Optional.empty();
pattern = ImmutableList.of();
-
- final IntegerTypeDefinition integer = (IntegerTypeDefinition)type;
- final IntegerTypeDefinition base = integer.getBaseType();
- if ((base != null) && (base.getBaseType() != null)) {
- range = currentOrEmpty(integer.getRangeConstraints(), base.getRangeConstraints());
- } else {
- range = integer.getRangeConstraints();
- }
+ range = extractRangeConstraint((RangeRestrictedTypeDefinition<?, ?>)type);
} else if (type instanceof StringTypeDefinition) {
final StringTypeDefinition string = (StringTypeDefinition)type;
final StringTypeDefinition base = string.getBaseType();
- if ((base != null) && (base.getBaseType() != null)) {
- length = currentOrEmpty(string.getLengthConstraints(), base.getLengthConstraints());
+ if (base != null && base.getBaseType() != null) {
+ length = currentOrEmpty(string.getLengthConstraint(), base.getLengthConstraint());
} else {
- length = string.getLengthConstraints();
+ length = string.getLengthConstraint();
}
pattern = uniquePatterns(string);
- range = ImmutableList.of();
- } else if (type instanceof UnsignedIntegerTypeDefinition) {
- length = ImmutableList.of();
- pattern = ImmutableList.of();
-
- final UnsignedIntegerTypeDefinition unsigned = (UnsignedIntegerTypeDefinition)type;
- final UnsignedIntegerTypeDefinition base = unsigned.getBaseType();
- if ((base != null) && (base.getBaseType() != null)) {
- range = currentOrEmpty(unsigned.getRangeConstraints(), base.getRangeConstraints());
- } else {
- range = unsigned.getRangeConstraints();
- }
+ range = Optional.empty();
} else {
- length = ImmutableList.of();
+ length = Optional.empty();
pattern = ImmutableList.of();
- range = ImmutableList.of();
+ range = Optional.empty();
}
// Now, this may have ended up being empty, too...
- if (length.isEmpty() && pattern.isEmpty() && range.isEmpty()) {
+ if (!length.isPresent() && pattern.isEmpty() && !range.isPresent()) {
return EMPTY_RESTRICTIONS;
}
// Nope, not empty allocate a holder
return new Restrictions() {
@Override
- public List<RangeConstraint> getRangeConstraints() {
+ public Optional<? extends RangeConstraint<?>> getRangeConstraint() {
return range;
}
@Override
return pattern;
}
@Override
- public List<LengthConstraint> getLengthConstraints() {
+ public Optional<LengthConstraint> getLengthConstraint() {
return length;
}
@Override
};
}
+ private static <T extends RangeRestrictedTypeDefinition<?, ?>> Optional<? extends RangeConstraint<?>>
+ extractRangeConstraint(final T def) {
+ final T base = (T) def.getBaseType();
+ if (base != null && base.getBaseType() != null) {
+ return currentOrEmpty(def.getRangeConstraint(), base.getRangeConstraint());
+ }
+
+ return def.getRangeConstraint();
+ }
+
/**
* Encodes angle brackets in yang statement description
* @param description description of a yang statement which is used to generate javadoc comments
package org.opendaylight.mdsal.binding.model.util;
import com.google.common.base.CharMatcher;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.Iterables;
+import com.google.common.collect.Range;
+import com.google.common.collect.RangeSet;
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Future;
import javax.annotation.Nullable;
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.BaseConstraints;
public final class Types {
private static final CacheLoader<Class<?>, ConcreteType> TYPE_LOADER =
}
/**
- *
* Represents concrete JAVA type with changed restriction values.
- *
*/
private static final class BaseTypeWithRestrictionsImpl extends AbstractBaseType implements BaseTypeWithRestrictions {
private final Restrictions restrictions;
}
/**
- *
* Represents parametrized JAVA type.
- *
*/
private static class ParametrizedTypeImpl extends AbstractBaseType implements ParameterizedType {
/**
}
/**
- *
* Represents JAVA bounded wildcard type.
- *
*/
private static class WildcardTypeImpl extends AbstractBaseType implements WildcardType {
/**
}
}
- public static <T extends Number> DefaultRestrictions<T> getDefaultRestrictions(final T min, final T max) {
+ public static <T extends Number& Comparable<T>> DefaultRestrictions<T> getDefaultRestrictions(final T min,
+ final T max) {
return new DefaultRestrictions<>(min, max);
}
- private static final class DefaultRestrictions<T extends Number> implements Restrictions {
+ private static final class DefaultRestrictions<T extends Number & Comparable<T>> implements Restrictions {
private final T min;
private final T max;
- private final List<RangeConstraint> rangeConstraints;
+ private final RangeConstraint<?> rangeConstraint;
private DefaultRestrictions(final T min, final T max) {
this.min = Preconditions.checkNotNull(min);
this.max = Preconditions.checkNotNull(max);
- this.rangeConstraints = Collections.singletonList(BaseConstraints.newRangeConstraint(min, max, Optional
- .<String>absent(), Optional.<String>absent()));
+
+ this.rangeConstraint = new RangeConstraint<T>() {
+
+ @Override
+ public Optional<String> getErrorAppTag() {
+ return Optional.empty();
+ }
+
+ @Override
+ public Optional<String> getErrorMessage() {
+ return Optional.empty();
+ }
+
+ @Override
+ public Optional<String> getDescription() {
+ return Optional.empty();
+ }
+
+ @Override
+ public Optional<String> getReference() {
+ return Optional.empty();
+ }
+
+ @Override
+ public RangeSet<T> getAllowedRanges() {
+ return ImmutableRangeSet.of(Range.closed(min, max));
+ }
+ };
}
@Override
}
@Override
- public List<RangeConstraint> getRangeConstraints() {
- return this.rangeConstraints;
+ public Optional<? extends RangeConstraint<?>> getRangeConstraint() {
+ return Optional.of(rangeConstraint);
}
@Override
}
@Override
- public List<LengthConstraint> getLengthConstraints() {
- return Collections.emptyList();
+ public Optional<LengthConstraint> getLengthConstraint() {
+ return Optional.empty();
}
}
}
\ No newline at end of file
import java.util.Collections;
import java.util.List;
import java.util.Objects;
+import java.util.Optional;
import org.opendaylight.mdsal.binding.model.api.AnnotationType;
import org.opendaylight.mdsal.binding.model.api.Constant;
import org.opendaylight.mdsal.binding.model.api.Enumeration;
@Override
public AnnotationTypeBuilder addAnnotation(final String packageName, final String name) {
- if ((packageName != null) && (name != null)) {
+ if (packageName != null && name != null) {
final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(packageName, name);
if (!this.annotationBuilders.contains(builder)) {
this.annotationBuilders = LazyCollections.lazyAdd(this.annotationBuilders, builder);
if (enums != null) {
for (final EnumPair enumPair : enums) {
if (enumPair != null) {
- this.addValue(enumPair.getName(), enumPair.getValue(), enumPair.getDescription());
+ this.addValue(enumPair.getName(), enumPair.getValue(), enumPair.getDescription().orElse(null));
}
}
}
public int hashCode() {
final int prime = 31;
int result = 1;
- result = (prime * result) + Objects.hashCode(this.name);
- result = (prime * result) + Objects.hashCode(this.value);
+ result = prime * result + Objects.hashCode(this.name);
+ result = prime * result + Objects.hashCode(this.value);
return result;
}
}
@Override
- public String getDescription() {
- return this.description;
+ public Optional<String> getDescription() {
+ return Optional.ofNullable(description);
}
@Override
- public String getReference() {
- return null;
+ public Optional<String> getReference() {
+ return Optional.empty();
}
@Override
builder.append(" (");
builder.append(valPair.getValue());
- if (i == (this.values.size() - 1)) {
+ if (i == this.values.size() - 1) {
builder.append(" );");
} else {
builder.append(" ),");
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
-import java.io.File;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Range;
import java.io.Serializable;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedTypeBuilderImpl;
import org.opendaylight.yangtools.yang.binding.BindingMapping;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.ConstraintMetaDefinition;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.stmt.ValueRange;
import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Int16TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Uint16TypeDefinition;
import org.opendaylight.yangtools.yang.model.util.BaseConstraints;
import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
import org.opendaylight.yangtools.yang.model.util.type.DerivedTypes;
+import org.opendaylight.yangtools.yang.model.util.type.InvalidLengthConstraintException;
import org.opendaylight.yangtools.yang.model.util.type.RestrictedTypes;
import org.opendaylight.yangtools.yang.model.util.type.StringTypeBuilder;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class BindingGeneratorUtilTest {
- private static final SchemaPath ROOT_PATH = SchemaPath.create(true, QName.create("/root"));
+ private static final SchemaPath ROOT_PATH = SchemaPath.create(true, QName.create("test", "/root"));
@Rule
public ExpectedException expectedEx = ExpectedException.none();
- private static List<File> loadTestResources(final String testFile) {
- final List<File> testModels = new ArrayList<>();
- File listModelFile;
- try {
- listModelFile = new File(BindingGeneratorUtilTest.class.getResource(testFile).toURI());
- } catch (URISyntaxException e) {
- throw new IllegalArgumentException("Failed to load sources from " + testFile);
- }
- testModels.add(listModelFile);
- return testModels;
- }
-
/**
* Tests methods:
* <ul>
* - without revision </ul>
*/
@Test
- public void testBindingGeneratorUtilMethods() throws Exception {
- List<File> testModels = loadTestResources("/module.yang");
-
- final Set<Module> modules = YangParserTestUtils.parseYangSources(testModels).getModules();
+ public void testBindingGeneratorUtilMethods() {
+ final Set<Module> modules = YangParserTestUtils.parseYangResources(BindingGeneratorUtilTest.class,
+ "/module.yang").getModules();
String packageName = "";
Module module = null;
for (Module m : modules) {
assertNotNull("Module can't be null", module);
// test of the method moduleNamespaceToPackageName()
- packageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
+ packageName = BindingMapping.getRootPackageName(module.getQNameModule());
assertEquals("Generated package name is incorrect.",
"org.opendaylight.yang.gen.v1.urn.m.o.d.u.l.e.n.a.m.e.t.e.s.t._case._1digit.rev130910", packageName);
}
@Test
- public void getRestrictionsTest() {
- final Optional<String> absent = Optional.absent();
+ public void getRestrictionsTest() throws InvalidLengthConstraintException {
+ final Optional<String> absent = Optional.empty();
final StringTypeBuilder builder =
RestrictedTypes.newStringBuilder(BaseTypes.stringType(), ROOT_PATH);
builder.addPatternConstraint(BaseConstraints.newPatternConstraint(".*", absent, absent));
- builder.setLengthAlternatives(ImmutableList.of(
- BaseConstraints.newLengthConstraint(1, 2, absent, absent)));
+ builder.setLengthConstraint(mock(ConstraintMetaDefinition.class), ImmutableList.of(ValueRange.of(1, 2)));
Restrictions restrictions = BindingGeneratorUtil.getRestrictions(builder.build());
assertNotNull(restrictions);
-
- assertEquals(1, restrictions.getLengthConstraints().size());
- assertEquals(0, restrictions.getRangeConstraints().size());
+ assertEquals(ImmutableSet.of(Range.closed(1, 2)),
+ restrictions.getLengthConstraint().get().getAllowedRanges().asRanges());
+ assertFalse(restrictions.getRangeConstraint().isPresent());
assertEquals(1, restrictions.getPatternConstraints().size());
assertFalse(restrictions.isEmpty());
- assertTrue(restrictions.getLengthConstraints().contains(
- BaseConstraints.newLengthConstraint(1, 2, absent, absent)));
assertTrue(restrictions.getPatternConstraints().contains(
BaseConstraints.newPatternConstraint(".*", absent, absent)));
}
assertNotNull(restrictions);
assertFalse(restrictions.isEmpty());
- assertEquals(((IntegerTypeDefinition) type.getBaseType()).getRangeConstraints(),
- restrictions.getRangeConstraints());
- assertTrue(restrictions.getLengthConstraints().isEmpty());
+ assertEquals(((Int16TypeDefinition) type.getBaseType()).getRangeConstraint(),
+ restrictions.getRangeConstraint());
+ assertFalse(restrictions.getLengthConstraint().isPresent());
assertTrue(restrictions.getPatternConstraints().isEmpty());
}
assertNotNull(restrictions);
assertFalse(restrictions.isEmpty());
- assertEquals(((UnsignedIntegerTypeDefinition) type.getBaseType()).getRangeConstraints(),
- restrictions.getRangeConstraints());
- assertTrue(restrictions.getLengthConstraints().isEmpty());
+ assertEquals(((Uint16TypeDefinition) type.getBaseType()).getRangeConstraint(),
+ restrictions.getRangeConstraint());
+ assertFalse(restrictions.getLengthConstraint().isPresent());
assertTrue(restrictions.getPatternConstraints().isEmpty());
}
assertNotNull(restrictions);
assertFalse(restrictions.isEmpty());
- assertEquals(base.getRangeConstraints(), restrictions.getRangeConstraints());
- assertTrue(restrictions.getLengthConstraints().isEmpty());
+ assertEquals(base.getRangeConstraint(), restrictions.getRangeConstraint());
+ assertFalse(restrictions.getLengthConstraint().isPresent());
assertTrue(restrictions.getPatternConstraints().isEmpty());
}
}
import static org.junit.Assert.assertTrue;
import java.util.List;
+import java.util.Optional;
import org.junit.Test;
import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.mdsal.binding.model.api.Restrictions;
}
@Override
- public List<RangeConstraint> getRangeConstraints() {
- return null;
+ public Optional<? extends RangeConstraint<?>> getRangeConstraint() {
+ return Optional.empty();
}
@Override
}
@Override
- public List<LengthConstraint> getLengthConstraints() {
- return null;
+ public Optional<LengthConstraint> getLengthConstraint() {
+ return Optional.empty();
}
};
genTOBuilder.setRestrictions(restrictions);
import java.io.Serializable;
import java.util.List;
import org.junit.Test;
-import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
-import org.opendaylight.mdsal.binding.model.util.Types;
import org.opendaylight.mdsal.binding.model.api.Constant;
import org.opendaylight.mdsal.binding.model.api.Enumeration;
import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
+import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
+import org.opendaylight.mdsal.binding.model.util.Types;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
generatedTypeBuilder.setDescription("My description ...");
generatedTypeBuilder.setModuleName("myModuleName");
generatedTypeBuilder.setReference("myReference");
- generatedTypeBuilder.setSchemaPath(SchemaPath.create(true, QName.create("/path")).getPathFromRoot());
+ generatedTypeBuilder.setSchemaPath(SchemaPath.create(true, QName.create("test", "/path")).getPathFromRoot());
assertNotNull(generatedTypeBuilder.addComment("My comment.."));
assertEquals(
assertEquals("My description ...", instance.getDescription());
assertEquals("myModuleName", instance.getModuleName());
assertEquals("myReference", instance.getReference());
- assertEquals(SchemaPath.create(true, QName.create("/path")).getPathFromRoot(), instance.getSchemaPath());
+ assertEquals(SchemaPath.create(true, QName.create("test", "/path")).getPathFromRoot(), instance.getSchemaPath());
assertEquals("My comment..", instance.getComment());
}
}
package org.opendaylight.mdsal.binding.java.api.generator;
import com.google.common.collect.Range;
-import java.util.Collection;
+import java.util.Set;
import javax.annotation.Nonnull;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
}
@Override
- protected final String generateRangeCheckerImplementation(final String checkerName, @Nonnull final Collection<RangeConstraint> constraints) {
+ protected final String generateRangeCheckerImplementation(final String checkerName, @Nonnull final RangeConstraint<?> constraint) {
+ final Set<? extends Range<? extends Number>> constraints = constraint.getAllowedRanges().asRanges();
final String fieldName = checkerName.toUpperCase() + "_RANGES";
final StringBuilder sb = new StringBuilder();
.append(") java.lang.reflect.Array.newInstance(").append(RANGE).append(".class, ").append(constraints.size()).append(");\n");
int i = 0;
- for (RangeConstraint r : constraints) {
- final String min = format(getValue(r.getMin()));
- final String max = format(getValue(r.getMax()));
+ for (Range<? extends Number> r : constraints) {
+ final String min = format(getValue(r.lowerEndpoint()));
+ final String max = format(getValue(r.upperEndpoint()));
sb.append(" a[").append(i++).append("] = ").append(RANGE).append(".closed(").append(min).append(", ").append(max).append(");\n");
}
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import java.util.Set;
import javax.annotation.Nonnull;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
import org.slf4j.Logger;
return minValue.compareTo(minToEnforce) < 0;
}
- private Collection<String> createExpressions(final Collection<RangeConstraint> constraints) {
+ private Collection<String> createExpressions(final RangeConstraint<?> constraint) {
+ final Set<? extends Range<? extends Number>> constraints = constraint.getAllowedRanges().asRanges();
final Collection<String> ret = new ArrayList<>(constraints.size());
- for (RangeConstraint r : constraints) {
- final T min = getValue(r.getMin());
+ for (Range<? extends Number> r : constraints) {
+ final T min = getValue(r.lowerEndpoint());
final boolean needMin = needsMinimumEnforcement(min);
- final T max = getValue(r.getMax());
+ final T max = getValue(r.upperEndpoint());
final boolean needMax = needsMaximumEnforcement(max);
if (!needMin && !needMax) {
return ret;
}
- private String createRangeString(final Collection<RangeConstraint> constraints) {
+ private String createRangeString(final RangeConstraint<?> constraint) {
+ final Set<? extends Range<? extends Number>> constraints = constraint.getAllowedRanges().asRanges();
final List<Range<T>> ranges = new ArrayList<>(constraints.size());
- for (RangeConstraint c : constraints) {
- ranges.add(Range.closed(getValue(c.getMin()), getValue(c.getMax())));
+ for (Range<? extends Number> c : constraints) {
+ ranges.add(Range.closed(getValue(c.lowerEndpoint()), getValue(c.upperEndpoint())));
}
return ranges.toString();
}
@Override
- protected final String generateRangeCheckerImplementation(final String checkerName, final Collection<RangeConstraint> constraints) {
+ protected final String generateRangeCheckerImplementation(final String checkerName,
+ final RangeConstraint<?> constraints) {
final StringBuilder sb = new StringBuilder();
final Collection<String> expressions = createExpressions(constraints);
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
-import java.util.Collection;
import java.util.Map;
import javax.annotation.Nonnull;
import org.opendaylight.mdsal.binding.model.api.ConcreteType;
final AbstractRangeGenerator<?> gen = GENERATORS.get(value.getClass().getName());
final Number check = gen.convert(ret);
if (!value.equals(check)) {
- LOG.warn("Number class conversion from {} to {} truncated value {} to {}", value.getClass(), type, value, ret);
+ LOG.warn("Number class conversion from {} to {} truncated value {} to {}", value.getClass(), type, value,
+ ret);
}
return ret;
* @param constraints Restrictions which need to be applied.
* @return Method source code.
*/
- @Nonnull protected abstract String generateRangeCheckerImplementation(@Nonnull final String checkerName, @Nonnull final Collection<RangeConstraint> constraints);
+ @Nonnull protected abstract String generateRangeCheckerImplementation(@Nonnull final String checkerName,
+ @Nonnull final RangeConstraint<?> constraints);
private static String rangeCheckerName(final String member) {
return "check" + member + "Range";
}
- String generateRangeChecker(@Nonnull final String member, @Nonnull final Collection<RangeConstraint> constraints) {
- Preconditions.checkArgument(!constraints.isEmpty(), "Restrictions may not be empty");
+ String generateRangeChecker(@Nonnull final String member, @Nonnull final RangeConstraint<?> constraints) {
return generateRangeCheckerImplementation(rangeCheckerName(member), constraints);
}
import java.util.Map
import java.util.StringTokenizer
import java.util.regex.Pattern
+import org.opendaylight.yangtools.yang.common.QName
import org.opendaylight.mdsal.binding.model.api.ConcreteType
import org.opendaylight.mdsal.binding.model.api.Constant
import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
import org.opendaylight.mdsal.binding.model.api.Type
import org.opendaylight.mdsal.binding.model.api.TypeMember
import org.opendaylight.mdsal.binding.model.util.Types
-import org.opendaylight.yangtools.yang.common.QName
abstract class BaseTemplate {
protected val GeneratedType type;
def protected emitConstant(Constant c) '''
«IF c.value instanceof QName»
«val qname = c.value as QName»
+ «val rev = qname.revision»
public static final «c.type.importedName» «c.name» = «QName.name».create("«qname.namespace.toString»",
- "«qname.formattedRevision»", "«qname.localName»").intern();
+ «IF rev.isPresent»"«rev.get»", «ENDIF»"«qname.localName»").intern();
«ELSE»
public static final «c.type.importedName» «c.name» = «c.value»;
«ENDIF»
«/* FIXME: generate checkers as simple blocks and embed them directly in setters */»
«val restrictions = field.returnType.restrictions»
«IF !(field.returnType instanceof GeneratedType) && restrictions !== null»
- «IF !restrictions.rangeConstraints.nullOrEmpty»
+ «IF restrictions.rangeConstraint.present»
«val rangeGenerator = AbstractRangeGenerator.forType(field.returnType)»
- «rangeGenerator.generateRangeChecker(field.name.toFirstUpper, restrictions.rangeConstraints)»
+ «rangeGenerator.generateRangeChecker(field.name.toFirstUpper, restrictions.rangeConstraint.get)»
«ENDIF»
- «IF !restrictions.lengthConstraints.nullOrEmpty»
- «LengthGenerator.generateLengthChecker(field.fieldName.toString, field.returnType, restrictions.lengthConstraints)»
+ «IF restrictions.lengthConstraint.present»
+ «LengthGenerator.generateLengthChecker(field.fieldName.toString, field.returnType, restrictions.lengthConstraint.get)»
«ENDIF»
«ENDIF»
public «type.name»«BUILDER» set«field.name.toFirstUpper»(final «field.returnType.importedName» value) {
«IF !(field.returnType instanceof GeneratedType) && restrictions !== null»
- «IF restrictions !== null && (!restrictions.rangeConstraints.nullOrEmpty || !restrictions.lengthConstraints.nullOrEmpty)»
+ «IF restrictions !== null && (restrictions.rangeConstraint.present || restrictions.lengthConstraint.present)»
if (value != null) {
- «IF !restrictions.rangeConstraints.nullOrEmpty»
+ «IF restrictions.rangeConstraint.present»
«val rangeGenerator = AbstractRangeGenerator.forType(field.returnType)»
«IF field.returnType instanceof ConcreteType»
«rangeGenerator.generateRangeCheckerCall(field.name.toFirstUpper, "value")»
«rangeGenerator.generateRangeCheckerCall(field.name.toFirstUpper, "value.getValue()")»
«ENDIF»
«ENDIF»
- «IF !restrictions.lengthConstraints.nullOrEmpty»
+ «IF restrictions.lengthConstraint.present»
«IF field.returnType instanceof ConcreteType»
«LengthGenerator.generateLengthCheckerCall(field.fieldName.toString, "value")»
«ELSE»
this.consts = genType.constantDefinitions
this.enclosedGeneratedTypes = genType.enclosedTypes
- if (restrictions !== null && !restrictions.rangeConstraints.nullOrEmpty) {
+ if (restrictions !== null && restrictions.rangeConstraint.present) {
rangeGenerator = AbstractRangeGenerator.forType(findProperty(genType, "value").returnType)
Preconditions.checkNotNull(rangeGenerator)
} else {
«generateFields»
«IF restrictions !== null»
- «IF !restrictions.lengthConstraints.nullOrEmpty»
- «LengthGenerator.generateLengthChecker("_value", findProperty(genTO, "value").returnType, restrictions.lengthConstraints)»
+ «IF restrictions.lengthConstraint.present»
+ «LengthGenerator.generateLengthChecker("_value", findProperty(genTO, "value").returnType, restrictions.lengthConstraint.get)»
«ENDIF»
- «IF !restrictions.rangeConstraints.nullOrEmpty»
- «rangeGenerator.generateRangeChecker("_value", restrictions.rangeConstraints)»
+ «IF restrictions.rangeConstraint.present»
+ «rangeGenerator.generateRangeChecker("_value", restrictions.rangeConstraint.get)»
«ENDIF»
«ENDIF»
def private generateRestrictions(Type type, String paramName, Type returnType) '''
«val restrictions = type.getRestrictions»
«IF restrictions !== null»
- «IF !restrictions.lengthConstraints.empty || !restrictions.rangeConstraints.empty»
+ «IF restrictions.lengthConstraint.present || restrictions.rangeConstraint.present»
if («paramName» != null) {
- «IF !restrictions.lengthConstraints.empty»
+ «IF restrictions.lengthConstraint.present»
«LengthGenerator.generateLengthCheckerCall(paramName, paramValue(returnType, paramName))»
«ENDIF»
- «IF !restrictions.rangeConstraints.empty»
+ «IF restrictions.rangeConstraint.present»
«rangeGenerator.generateRangeCheckerCall(paramName, paramValue(returnType, paramName))»
«ENDIF»
}
def writeEnumeration(Enumeration enumeration)
'''
«FOR v : enumeration.values SEPARATOR ",\n" AFTER ";"»
- «writeEnumItem(v.name, v.mappedName, v.value, v.description)»«
+ «writeEnumItem(v.name, v.mappedName, v.value, v.description.orElse(null))»«
ENDFOR»
'''
}
package org.opendaylight.mdsal.binding.java.api.generator;
import com.google.common.collect.Range;
-import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.List;
+import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.opendaylight.mdsal.binding.model.api.Type;
return "check" + member + "Length";
}
- private static Collection<String> createExpressions(final Collection<LengthConstraint> constraints) {
+ private static Collection<String> createExpressions(final LengthConstraint constraint) {
+ final Set<Range<Integer>> constraints = constraint.getAllowedRanges().asRanges();
final Collection<String> ret = new ArrayList<>(constraints.size());
- for (LengthConstraint l : constraints) {
+ for (Range<Integer> l : constraints) {
// We have to deal with restrictions being out of integer's range
- final long min = l.getMin().longValue();
- final long max = l.getMax().longValue();
+ final int min = l.lowerEndpoint().intValue();
+ final int max = l.upperEndpoint().intValue();
if (min > 0 || max < Integer.MAX_VALUE) {
final StringBuilder sb = new StringBuilder("length >");
return ret;
}
- private static String createLengthString(final Collection<LengthConstraint> constraints) {
- final List<Range<BigInteger>> ranges = new ArrayList<>(constraints.size());
-
- for (LengthConstraint c : constraints) {
- ranges.add(Range.closed(new BigInteger(c.getMin().toString()), new BigInteger(c.getMax().toString())));
- }
-
- return ranges.toString();
+ private static String createLengthString(final LengthConstraint constraint) {
+ return new ArrayList<>(constraint.getAllowedRanges().asRanges()).toString();
}
- private static String generateArrayLengthChecker(final String member,
- final Collection<LengthConstraint> constraints) {
+ private static String generateArrayLengthChecker(final String member, final LengthConstraint constraint) {
final StringBuilder sb = new StringBuilder();
- final Collection<String> expressions = createExpressions(constraints);
+ final Collection<String> expressions = createExpressions(constraint);
sb.append("private static void ").append(lengthCheckerName(member)).append("(final byte[] value) {\n");
}
sb.append(" throw new IllegalArgumentException(String.format(\"Invalid length: %s, expected: ")
- .append(createLengthString(constraints)).append(".\", java.util.Arrays.toString(value)));\n");
+ .append(createLengthString(constraint)).append(".\", java.util.Arrays.toString(value)));\n");
}
sb.append("}\n");
return sb.toString();
}
- private static String generateStringLengthChecker(final String member,
- final Collection<LengthConstraint> constraints) {
+ private static String generateStringLengthChecker(final String member, final LengthConstraint constraint) {
final StringBuilder sb = new StringBuilder();
- final Collection<String> expressions = createExpressions(constraints);
+ final Collection<String> expressions = createExpressions(constraint);
sb.append("private static void ").append(lengthCheckerName(member)).append("(final String value) {\n");
}
sb.append(" throw new IllegalArgumentException(String.format(\"Invalid length: %s, expected: ")
- .append(createLengthString(constraints)).append(".\", value));\n");
+ .append(createLengthString(constraint)).append(".\", value));\n");
}
sb.append("}\n");
}
static String generateLengthChecker(final String member, final Type type,
- final Collection<LengthConstraint> constraints) {
+ final LengthConstraint constraint) {
return TypeUtils.getBaseYangType(type).getName().indexOf('[') != -1
- ? generateArrayLengthChecker(member, constraints) : generateStringLengthChecker(member, constraints);
+ ? generateArrayLengthChecker(member, constraint) : generateStringLengthChecker(member, constraint);
}
static String generateLengthCheckerCall(@Nullable final String member, @Nonnull final String valueReference) {
import com.google.common.collect.ImmutableSet
import java.io.IOException
import java.io.InputStream
-import java.text.DateFormat
-import java.text.SimpleDateFormat
import java.util.Collections
-import java.util.Date
import java.util.HashSet
import java.util.LinkedHashMap
import java.util.Map
import java.util.Set
import java.util.TreeMap
import java.util.function.Function
-import org.eclipse.xtend.lib.Property
+import org.eclipse.xtend.lib.annotations.Accessors
import org.opendaylight.mdsal.binding.model.api.ParameterizedType
import org.opendaylight.mdsal.binding.model.api.Type
import org.opendaylight.mdsal.binding.model.api.WildcardType
import org.opendaylight.yangtools.yang.binding.YangModuleInfo
import org.opendaylight.yangtools.yang.model.api.Module
import org.opendaylight.yangtools.yang.model.api.SchemaContext
+import org.opendaylight.yangtools.yang.common.Revision
class YangModuleInfoTemplate {
val Map<String, String> importMap = new LinkedHashMap()
val Function<Module, Optional<String>> moduleFilePathResolver
- @Property
+ @Accessors
val String packageName;
- @Property
+ @Accessors
val String modelBindingProviderName;
new(Module module, SchemaContext ctx, Function<Module, Optional<String>> moduleFilePathResolver) {
this.module = module
this.ctx = ctx
this.moduleFilePathResolver = moduleFilePathResolver
- _packageName = getRootPackageName(module.getQNameModule());
- _modelBindingProviderName = '''«packageName».«MODEL_BINDING_PROVIDER_CLASS_NAME»''';
+ packageName = getRootPackageName(module.getQNameModule());
+ modelBindingProviderName = '''«packageName».«MODEL_BINDING_PROVIDER_CLASS_NAME»''';
}
def String generate() {
private final «String.importedName» name = "«module.name»";
private final «String.importedName» namespace = "«module.namespace.toString»";
- «val DateFormat df = new SimpleDateFormat("yyyy-MM-dd")»
- private final «String.importedName» revision = "«df.format(module.revision)»";
+ «IF module.revision.isPresent»
+ private final «String.importedName» revision = "«module.revision.get.toString»";
+ «ELSE»
+ private final «String.importedName» revision = null;
+ «ENDIF»
private final «String.importedName» resourcePath = "«sourcePath(module)»";
private final «Set.importedName»<YangModuleInfo> importedModules;
«val rev = imp.revision»
«IF rev === null»
«val Set<Module> modules = ctx.modules»
- «val TreeMap<Date, Module> sorted = new TreeMap()»
+ «val TreeMap<Optional<Revision>, Module> sorted = new TreeMap()»
«FOR module : modules»
«IF module.name.equals(name)»
«sorted.put(module.revision, module)»
«ENDFOR»
set.add(«getRootPackageName(sorted.lastEntry().value.QNameModule)».«MODULE_INFO_CLASS_NAME».getInstance());
«ELSE»
- set.add(«getRootPackageName((ctx.findModuleByName(name, rev).QNameModule))».«MODULE_INFO_CLASS_NAME».getInstance());
+ set.add(«getRootPackageName((ctx.findModule(name, rev).get.QNameModule))».«MODULE_INFO_CLASS_NAME».getInstance());
«ENDIF»
«ENDFOR»
«ENDIF»
private final «String.importedName» name = "«submodule.name»";
private final «String.importedName» namespace = "«submodule.namespace.toString»";
- «val DateFormat df = new SimpleDateFormat("yyyy-MM-dd")»
- private final «String.importedName» revision = "«df.format(submodule.revision)»";
+ «IF submodule.revision.isPresent»
+ private final «String.importedName» revision = "«submodule.revision.get.toString»";
+ «ELSE»
+ private final «String.importedName» revision = null;
+ «ENDIF»
private final «String.importedName» resourcePath = "«sourcePath(submodule)»";
private final «Set.importedName»<YangModuleInfo> importedModules;
}
«ENDFOR»
'''
-
}
import java.lang.reflect.Constructor;
import org.junit.Test;
-import org.opendaylight.mdsal.binding.java.api.generator.Constants;
public class ConstantsTest {
@Test
public void constructTest() throws Throwable {
- final Constructor constructor = Constants.class.getDeclaredConstructor();
+ final Constructor<?> constructor = Constants.class.getDeclaredConstructor();
assertFalse(constructor.isAccessible());
constructor.setAccessible(true);
assertNotNull(constructor.newInstance());
@Test(expected = UnsupportedOperationException.class)
public void constructTest() throws Throwable {
- final Constructor constructor = GeneratorUtil.class.getDeclaredConstructor();
+ final Constructor<GeneratorUtil> constructor = GeneratorUtil.class.getDeclaredConstructor();
constructor.setAccessible(true);
try {
constructor.newInstance();
import java.lang.reflect.Constructor;
import org.junit.Test;
-import org.opendaylight.mdsal.binding.java.api.generator.LengthGenerator;
public class LengthGeneratorTest {
@Test(expected = UnsupportedOperationException.class)
public void constructTest() throws Throwable {
- final Constructor constructor = LengthGenerator.class.getDeclaredConstructor();
+ final Constructor<LengthGenerator> constructor = LengthGenerator.class.getDeclaredConstructor();
constructor.setAccessible(true);
try {
constructor.newInstance();
import com.google.common.collect.ImmutableList;
import java.lang.reflect.Constructor;
import org.junit.Test;
-import org.opendaylight.mdsal.binding.java.api.generator.TypeUtils;
import org.opendaylight.mdsal.binding.model.api.ConcreteType;
import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
@Test(expected = UnsupportedOperationException.class)
public void constructTest() throws Throwable {
- final Constructor constructor = TypeUtils.class.getDeclaredConstructor();
+ final Constructor<TypeUtils> constructor = TypeUtils.class.getDeclaredConstructor();
constructor.setAccessible(true);
try {
constructor.newInstance();
import com.google.common.collect.ImmutableSet;
import java.io.File;
+import java.io.IOException;
+import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
public class AugmentToUsesInAugmentCompilationTest extends BaseCompilationTest {
@Test
- public void testAugmentToUsesInAugment() throws Exception {
+ public void testAugmentToUsesInAugment() throws IOException, URISyntaxException {
final File sourcesOutputDir = new File(CompilationTestUtils.GENERATOR_OUTPUT_PATH + CompilationTestUtils.FS + "augment-uses-to-augment");
assertTrue("Failed to create test file '" + sourcesOutputDir + "'", sourcesOutputDir.mkdir());
final File compiledOutputDir = new File(CompilationTestUtils.COMPILER_OUTPUT_PATH + CompilationTestUtils.FS + "augment-uses-to-augment");
assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdir());
final List<File> sourceFiles = CompilationTestUtils.getSourceFiles("/compilation/augment-uses-to-augment");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final List<Type> types = bindingGenerator.generateTypes(context);
final GeneratorJavaFile generator = new GeneratorJavaFile(ImmutableSet.copyOf(types));
generator.generateToFile(sourcesOutputDir);
import com.google.common.collect.ImmutableSet;
import java.io.File;
+import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
+import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
CompilationTestUtils.cleanUp(sourcesOutputDir, compiledOutputDir);
}
- private void generateTestSources(final String resourceDirPath, final File sourcesOutputDir) throws Exception {
+ private void generateTestSources(final String resourceDirPath, final File sourcesOutputDir)
+ throws IOException, URISyntaxException {
final List<File> sourceFiles = CompilationTestUtils.getSourceFiles(resourceDirPath);
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final List<Type> types = bindingGenerator.generateTypes(context);
final GeneratorJavaFile generator = new GeneratorJavaFile(ImmutableSet.copyOf(types));
generator.generateToFile(sourcesOutputDir);
import com.google.common.collect.Maps;
import java.io.File;
import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
return false;
}
- private void generateTestSources(final String resourceDirPath, final File sourcesOutputDir) throws Exception {
+ private void generateTestSources(final String resourceDirPath, final File sourcesOutputDir)
+ throws IOException, URISyntaxException {
final List<File> sourceFiles = CompilationTestUtils.getSourceFiles(resourceDirPath);
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final List<Type> types = bindingGenerator.generateTypes(context);
final GeneratorJavaFile generator = new GeneratorJavaFile(ImmutableSet.copyOf(types));
generator.generateToFile(sourcesOutputDir);
for (File file : dirFiles) {
if (file.isDirectory()) {
return getFiles(file, files);
- } else {
- files.put(file.getName(), file);
}
+
+ files.put(file.getName(), file);
}
return files;
}
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.io.File;
+import java.io.IOException;
import java.lang.reflect.Constructor;
+import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
cleanUp(sourcesOutputDir, compiledOutputDir);
}
- private void generateTestSources(final String resourceDirPath, final File sourcesOutputDir) throws Exception {
+ private void generateTestSources(final String resourceDirPath, final File sourcesOutputDir)
+ throws IOException, URISyntaxException {
final List<File> sourceFiles = getSourceFiles(resourceDirPath);
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final List<Type> types = bindingGenerator.generateTypes(context);
final GeneratorJavaFile generator = new GeneratorJavaFile(ImmutableSet.copyOf(types));
generator.generateToFile(sourcesOutputDir);
assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdir());
final List<File> sourceFiles = getSourceFiles("/compilation/cascade-uses");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final List<Type> types = bindingGenerator.generateTypes(context);
final GeneratorJavaFile generator = new GeneratorJavaFile(ImmutableSet.copyOf(types));
generator.generateToFile(sourcesOutputDir);
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import java.io.File;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
import java.util.List;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.model.util.Types;
import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedTOBuilderImpl;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class ClassCodeGeneratorTest {
-
- private final static List<File> testModels = new ArrayList<>();
-
- @BeforeClass
- public static void loadTestResources() throws URISyntaxException {
- final File listModelFile = new File(ClassCodeGeneratorTest.class
- .getResource("/list-composite-key.yang").toURI());
- testModels.add(listModelFile);
- }
-
@Test
- public void compositeKeyClassTest() throws IOException, SourceException, ReactorException {
+ public void compositeKeyClassTest() {
- final SchemaContext context = YangParserTestUtils.parseYangSources(testModels);
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/list-composite-key.yang");
assertNotNull(context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
final String outputStr = clsGen.generate(genTO);
assertNotNull(outputStr);
- assertTrue(outputStr.contains("public CompositeKeyListKey(java.lang.Byte _key1, java.lang.String _key2)"));
+ assertTrue(outputStr.contains(
+ "public CompositeKeyListKey(java.lang.Byte _key1, java.lang.String _key2)"));
assertEquals(2, propertyCount);
genTOsCount++;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Range;
import java.io.File;
+import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.WildcardType;
import java.math.BigDecimal;
import java.math.BigInteger;
+import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
CompilationTestUtils.cleanUp(sourcesOutputDir, compiledOutputDir);
}
- private void generateTestSources(final String resourceDirPath, final File sourcesOutputDir) throws Exception {
+ private void generateTestSources(final String resourceDirPath, final File sourcesOutputDir)
+ throws IOException, URISyntaxException {
final List<File> sourceFiles = CompilationTestUtils.getSourceFiles(resourceDirPath);
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final List<Type> types = bindingGenerator.generateTypes(context);
Collections.sort(types, (o1, o2) -> o2.getName().compareTo(o1.getName()));
final GeneratorJavaFile generator = new GeneratorJavaFile(ImmutableSet.copyOf(types));
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.net.URI;
+import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
return result;
}
- static List<File> getSourceFiles(final String path) throws Exception {
+ static List<File> getSourceFiles(final String path) throws FileNotFoundException, URISyntaxException {
final URI resPath = BaseCompilationTest.class.getResource(path).toURI();
final File sourcesDir = new File(resPath);
- if (sourcesDir.exists()) {
- final List<File> sourceFiles = new ArrayList<>();
- final File[] fileArray = sourcesDir.listFiles();
- if (fileArray == null) {
- throw new IllegalArgumentException("Unable to locate files in " + sourcesDir);
- }
- sourceFiles.addAll(Arrays.asList(fileArray));
- return sourceFiles;
- } else {
+ if (!sourcesDir.exists()) {
throw new FileNotFoundException("Testing files were not found(" + sourcesDir.getName() + ")");
}
+
+ final List<File> sourceFiles = new ArrayList<>();
+ final File[] fileArray = sourcesDir.listFiles();
+ if (fileArray == null) {
+ throw new IllegalArgumentException("Unable to locate files in " + sourcesDir);
+ }
+ sourceFiles.addAll(Arrays.asList(fileArray));
+ return sourceFiles;
}
static void deleteTestDir(final File file) {
assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdir());
final List<File> sourceFiles = getSourceFiles("/compilation/encoding-javadoc");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final List<Type> types = bindingGenerator.generateTypes(context);
final GeneratorJavaFile generator = new GeneratorJavaFile(ImmutableSet.copyOf(types));
generator.generateToFile(sourcesOutputDir);
import com.google.common.collect.ImmutableSet;
import java.io.File;
+import java.io.IOException;
+import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
cleanUp(sourcesOutputDir, compiledOutputDir);
}
- private void generateTestSources(final String resourceDirPath, final File sourcesOutputDir) throws Exception {
+ private void generateTestSources(final String resourceDirPath, final File sourcesOutputDir)
+ throws IOException, URISyntaxException {
final List<File> sourceFiles = getSourceFiles(resourceDirPath);
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final List<Type> types = bindingGenerator.generateTypes(context);
final GeneratorJavaFile generator = new GeneratorJavaFile(ImmutableSet.copyOf(types));
generator.generateToFile(sourcesOutputDir);
assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdir());
final List<File> sourceFiles = CompilationTestUtils.getSourceFiles("/compilation/typedef");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final List<Type> types = bindingGenerator.generateTypes(context);
final GeneratorJavaFile generator = new GeneratorJavaFile(ImmutableSet.copyOf(types));
generator.generateToFile(sourcesOutputDir);
assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdir());
final List<File> sourceFiles = getSourceFiles("/compilation/union-typedef");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final List<Type> types = bindingGenerator.generateTypes(context);
final GeneratorJavaFile generator = new GeneratorJavaFile(new HashSet<>(types));
generator.generateToFile(sourcesOutputDir);
private void generateTestSources(final String resourceDirPath, final File sourcesOutputDir) throws Exception {
final List<File> sourceFiles = CompilationTestUtils.getSourceFiles(resourceDirPath);
- final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
+ final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
final List<Type> types = bindingGenerator.generateTypes(context);
final GeneratorJavaFile generator = new GeneratorJavaFile(ImmutableSet.copyOf(types));
generator.generateToFile(sourcesOutputDir);
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.base.CharMatcher;
+import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
-import java.text.SimpleDateFormat;
+import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.common.Revision;
public final class BindingMapping {
public static final String RPC_INPUT_SUFFIX = "Input";
public static final String RPC_OUTPUT_SUFFIX = "Output";
- private static final ThreadLocal<SimpleDateFormat> PACKAGE_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
-
- @Override
- protected SimpleDateFormat initialValue() {
- return new SimpleDateFormat("yyMMdd");
- }
-
- @Override
- public void set(final SimpleDateFormat value) {
- throw new UnsupportedOperationException();
- }
- };
-
private static final Interner<String> PACKAGE_INTERNER = Interners.newWeakInterner();
private BindingMapping() {
if (chars[chars.length - 1] != '.') {
packageNameBuilder.append('.');
}
- packageNameBuilder.append("rev");
- packageNameBuilder.append(PACKAGE_DATE_FORMAT.get().format(module.getRevision()));
+
+ final Optional<Revision> optRev = module.getRevision();
+ if (optRev.isPresent()) {
+ // Revision is in format 2017-10-26, we want the output to be 171026, which is a matter of picking the
+ // right characters.
+ final String rev = optRev.get().toString();
+ Preconditions.checkArgument(rev.length() == 10, "Unsupported revision %s", rev);
+ packageNameBuilder.append("rev");
+ packageNameBuilder.append(rev.substring(2, 4)).append(rev.substring(5, 7)).append(rev.substring(8));
+ } else {
+ // No-revision packages are special
+ packageNameBuilder.append("norev");
+ }
+
return normalizePackageName(packageNameBuilder.toString());
}
import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
public static QNameModule getQNameModule(final YangModuleInfo modInfo) {
- return QNameModule.create(URI.create(modInfo.getNamespace()), QName.parseRevision(modInfo.getRevision()));
+ return QNameModule.create(URI.create(modInfo.getNamespace()), Revision.ofNullable(modInfo.getRevision()));
}
/**
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
-import java.util.Date;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.common.Revision;
public class BindingMappingTest {
@Test
- public void basicTest() throws Exception {
+ public void basicTest() {
assertTrue(BindingMapping.getRootPackageName(QName.create(QNameModule.create(URI.create("test:URI"),
- new Date(System.currentTimeMillis())), "test")).contains("test.uri"));
+ Revision.of("2017-10-26")), "test")).contains("test.uri"));
assertNull(BindingMapping.normalizePackageName(null));
assertTrue(BindingMapping.normalizePackageName("1testpublic").contains("_1testpublic"));
assertTrue(BindingMapping.getMethodName(QName.create("testNS", "testLocalName")).equals("testLocalName"));
assertTrue(BindingMapping.getMethodName("TestYangIdentifier").equals("testYangIdentifier"));
assertTrue(BindingMapping.getClassName(QName.create("testNS", "testClass")).equals("TestClass"));
assertTrue(BindingMapping.getClassName("testClass").equals("TestClass"));
- assertTrue(BindingMapping.getGetterSuffix(QName.create("test")).equals("Test"));
- assertTrue(BindingMapping.getGetterSuffix(QName.create("class")).equals("XmlClass"));
+ assertTrue(BindingMapping.getGetterSuffix(QName.create("test", "test")).equals("Test"));
+ assertTrue(BindingMapping.getGetterSuffix(QName.create("test", "class")).equals("XmlClass"));
assertTrue(BindingMapping.getPropertyName("Test").equals("test"));
assertTrue(BindingMapping.getPropertyName("test").equals("test"));
assertTrue(BindingMapping.getPropertyName("Class").equals("xmlClass"));
throw e.getCause();
}
}
-}
\ No newline at end of file
+}
final InstanceIdentifierBuilder instanceIdentifierBuilder = instanceIdentifier1.builder();
assertEquals(instanceIdentifier1.hashCode(), instanceIdentifierBuilder.hashCode());
assertNotNull(instanceIdentifierBuilder.augmentation(InstantiatedFoo.class));
- assertNotNull(instanceIdentifierBuilder.toInstance());
+ assertNotNull(instanceIdentifierBuilder.build());
}
@Test
@Test
public void keyOfTest() throws Exception {
- final Identifier identifier = mock(Identifier.class);
+ final Identifier<?> identifier = mock(Identifier.class);
assertEquals(identifier, InstanceIdentifier.keyOf(
new KeyedInstanceIdentifier(Identifiable.class, ImmutableList.of(), false, 0, identifier)));
}
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
final ObjectInputStream inputStream = new ObjectInputStream(byteArrayInputStream);
- final InstanceIdentifier deserialized = (InstanceIdentifier) inputStream.readObject();
+ final InstanceIdentifier<?> deserialized = (InstanceIdentifier<?>) inputStream.readObject();
assertEquals(instanceIdentifier, deserialized);
}
public class KeyedInstanceIdentifierTest {
@Test
- public void basicTest() throws Exception {
- final Identifier key = mock(Identifier.class);
- final KeyedInstanceIdentifier keyedInstanceIdentifier =
+ public void basicTest() {
+ final Identifier<?> key = mock(Identifier.class);
+ final KeyedInstanceIdentifier<?, ?> keyedInstanceIdentifier =
new KeyedInstanceIdentifier(Identifiable.class, ImmutableList.of(), false, 0, key);
assertEquals(key, keyedInstanceIdentifier.getKey());
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.DataRoot;
-public interface Nodes extends //
- ChildOf<DataRoot>, //
- DataObject {
+public interface Nodes extends ChildOf<DataRoot>, DataObject {
- Iterable getNode();
+ Iterable<?> getNode();
}
final RpcServiceInvoker testRpcInvoker =
new TestRpcInvokerImpl(ImmutableMap.of(
- "tstWithoutInput", methodWithoutInput,
- "tstWithInput", methodWithInput));
+ "(test)tstWithoutInput", methodWithoutInput,
+ "(test)tstWithInput", methodWithInput));
final Field testInvokerMapField = testRpcInvoker.getClass().getSuperclass().getDeclaredField("map");
testInvokerMapField.setAccessible(true);
final Map<String, RpcMethodInvoker> testInvokerMap =
(Map<String, RpcMethodInvoker>) testInvokerMapField.get(testRpcInvoker);
- assertTrue(testInvokerMap.get("tstWithInput") instanceof RpcMethodInvokerWithInput);
- assertTrue(testInvokerMap.get("tstWithoutInput") instanceof RpcMethodInvokerWithoutInput);
+ assertTrue(testInvokerMap.get("(test)tstWithInput") instanceof RpcMethodInvokerWithInput);
+ assertTrue(testInvokerMap.get("(test)tstWithoutInput") instanceof RpcMethodInvokerWithoutInput);
final Crate crateWithoutInput =
- (Crate) testRpcInvoker.invokeRpc(rpcService, QName.create("tstWithoutInput"), null).get();
+ (Crate) testRpcInvoker.invokeRpc(rpcService, QName.create("test", "tstWithoutInput"), null).get();
assertEquals(TestRpcService.methodWithoutInput(rpcService).get().getRpcService(),
crateWithoutInput.getRpcService());
assertFalse(crateWithoutInput.getDataObject().isPresent());
final DataObject dataObject = mock(DataObject.class);
final Crate crateWithInput =
- (Crate) testRpcInvoker.invokeRpc(rpcService, QName.create("tstWithInput"), dataObject).get();
+ (Crate) testRpcInvoker.invokeRpc(rpcService, QName.create("test", "tstWithInput"), dataObject).get();
assertEquals(TestRpcService.methodWithInput(rpcService, dataObject).get().getRpcService(),
crateWithInput.getRpcService());
assertTrue(crateWithInput.getDataObject().isPresent());
private class TestRpcInvokerImpl extends AbstractMappedRpcInvoker<String> {
- TestRpcInvokerImpl(Map<String, Method> map) {
+ TestRpcInvokerImpl(final Map<String, Method> map) {
super(map);
}
@Override
- protected String qnameToKey(QName qname) {
+ protected String qnameToKey(final QName qname) {
return qname.toString();
}
}
private final RpcService rpcService;
private final ThreadLocal<Optional<DataObject>> dataObject;
- Crate(@Nonnull RpcService rpcService, @Nullable DataObject dataObject) {
+ Crate(@Nonnull final RpcService rpcService, @Nullable final DataObject dataObject) {
this.rpcService = rpcService;
this.dataObject = new ThreadLocal<Optional<DataObject>>() {
@Override
}
static class TestRpcService implements RpcService {
- static Future<Crate> methodWithoutInput(RpcService testArgument) {
+ static Future<Crate> methodWithoutInput(final RpcService testArgument) {
return Futures.immediateFuture(new Crate(testArgument, null));
}
- static Future<Crate> methodWithInput(RpcService testArgument, DataObject testArgument2) {
+ static Future<Crate> methodWithInput(final RpcService testArgument, final DataObject testArgument2) {
return Futures.immediateFuture(new Crate(testArgument, testArgument2));
}
}
assertFalse(BindingReflections.resolveRpcOutputClass(
TestImplementation.class.getDeclaredMethod("rpcMethodTest2")).isPresent());
- assertTrue(BindingReflections.getQName(TestImplementation.class).toString().equals("test"));
+ assertEquals(QName.create("test", "test"), BindingReflections.getQName(TestImplementation.class));
}
@Test(expected = UnsupportedOperationException.class)
private static final class TestImplementation extends BaseIdentity implements Augmentation<TestImplementation>,
RpcService {
- public static final QName QNAME = QName.create("test");
+ public static final QName QNAME = QName.create("test", "test");
Future<List<Object>> rpcMethodTest() {
return null;
}
- Future rpcMethodTest2() {
+ Future<?> rpcMethodTest2() {
return null;
}
}
import com.google.common.collect.ImmutableMap;
import java.net.URI;
-import java.util.Date;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.yangtools.yang.binding.RpcService;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.common.Revision;
public class LocalNameRpcServiceInvokerTest {
private static RpcServiceInvoker rpcServiceInvoker;
- private static final QNameModule Q_NAME_MODULE =
- QNameModule.create(URI.create("testURI"), new Date(System.currentTimeMillis()));
+ private static final QNameModule Q_NAME_MODULE = QNameModule.create(URI.create("testURI"),
+ Revision.of("2017-10-26"));
private static final RpcService RPC_SERVICE = mock(RpcService.class);
@BeforeClass
public static void setUp() throws Exception {
rpcServiceInvoker = LocalNameRpcServiceInvoker.instanceFor(
- Q_NAME_MODULE, ImmutableMap.of(QName.create("test"), Object.class.getDeclaredMethod("hashCode")));
+ Q_NAME_MODULE, ImmutableMap.of(QName.create(Q_NAME_MODULE, "test"),
+ Object.class.getDeclaredMethod("hashCode")));
assertNotNull(rpcServiceInvoker);
}
@Test(expected = IllegalArgumentException.class)
public void qnameToKeyWithNullTest() throws Exception {
- rpcServiceInvoker.invokeRpc(RPC_SERVICE, QName.create("test"), null);
+ rpcServiceInvoker.invokeRpc(RPC_SERVICE, QName.create("", "test"), null);
}
-}
\ No newline at end of file
+}
final NotificationListener notificationListener = mock(NotificationListener.class);
final MethodHandle methodHandle = mock(MethodHandle.class);
final NotificationListenerInvoker notificationListenerInvoker =
- new NotificationListenerInvoker(ImmutableMap.of(QName.create("test"), methodHandle));
+ new NotificationListenerInvoker(ImmutableMap.of(QName.create("test", "test"), methodHandle));
- notificationListenerInvoker.invokeNotification(notificationListener, QName.create("test"), null);
+ notificationListenerInvoker.invokeNotification(notificationListener, QName.create("test", "test"), null);
fail("Expected WrongMethodTypeException, no method to invoke is supplied");
}
public interface TestInterface extends NotificationListener, Augmentation {
- QName QNAME = QName.create("test");
+ QName QNAME = QName.create("test", "test");
void onTestNotificationInterface(TestNotificationInterface notif);
}
private interface TestPrivateInterface extends NotificationListener, Augmentation {
- QName QNAME = QName.create("test");
+ QName QNAME = QName.create("test", "test");
void onTestNotificationInterface(TestNotificationInterface notif);
}
private interface TestNotificationInterface extends Notification {
- QName QNAME = QName.create("test");
+ QName QNAME = QName.create("test", "test");
}
}
\ No newline at end of file
@Test(expected = IllegalArgumentException.class)
public void qnameToKeyTest() throws Exception {
final RpcService rpcService = mock(RpcService.class);
- QNameRpcServiceInvoker.instanceFor(ImmutableMap.of()).invokeRpc(rpcService, QName.create("test"), null);
+ QNameRpcServiceInvoker.instanceFor(ImmutableMap.of()).invokeRpc(rpcService, QName.create("", "test"), null);
fail("Expected exception: constructed with empty map");
}
}
\ No newline at end of file
private static final class TestImplClassWithInput implements RpcService {
- static Future testMethod(RpcService testArg, DataObject data) {
+ static Future<?> testMethod(final RpcService testArg, final DataObject data) {
return Futures.immediateFuture(null);
}
- static Future testMethodWithException(RpcService testArg, DataObject data) throws Exception {
+ static Future<?> testMethodWithException(final RpcService testArg, final DataObject data) throws Exception {
throw new InternalError();
}
}
import com.google.common.collect.ImmutableMap;
import java.lang.reflect.Method;
import java.net.URI;
-import java.util.Date;
import org.junit.Test;
import org.opendaylight.yangtools.yang.binding.RpcService;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.common.Revision;
public class RpcServiceInvokerTest {
final Method method = this.getClass().getDeclaredMethod("testMethod");
method.setAccessible(true);
assertNotNull(RpcServiceInvoker.from(ImmutableMap.of(
- QName.create(QNameModule.create(URI.create("testURI"),
- new Date(System.currentTimeMillis())),"test"), method,
- QName.create(QNameModule.create(URI.create("testURI2"),
- new Date(System.currentTimeMillis())),"test"), method)));
+ QName.create(QNameModule.create(URI.create("testURI"), Revision.of("2017-10-26")),"test"), method,
+ QName.create(QNameModule.create(URI.create("testURI2"), Revision.of("2017-10-26")),"test"), method)));
assertNotNull(RpcServiceInvoker.from(ImmutableMap.of(
- QName.create(QNameModule.create(URI.create("testURI"),
- new Date(System.currentTimeMillis())),"test"), method)));
+ QName.create(QNameModule.create(URI.create("testURI"), Revision.of("2017-10-26")), "test"), method)));
}
@Test(expected = IllegalArgumentException.class)
- public void fromWithExceptionTest() throws Exception {
+ public void fromWithExceptionTest() {
RpcServiceInvoker.from(RpcService.class);
fail("Expected IllegalArgumentException");
}
private void testMethod() {
// NOOP
}
-}
\ No newline at end of file
+}
}
@Override
- public void close() throws Exception {
+ public void close() {
domReg.close();
}
};
}
-}
\ No newline at end of file
+}
import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter;
import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerImplementation;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
@Override
protected AbstractTreeNodeSerializerSource generateCaseSerializer(final GeneratedType type,
- final ChoiceCaseNode node) {
+ final CaseSchemaNode node) {
return new AbstractAugmentableDataNodeContainerEmitterSource(this, type, node) {
@Override
public CharSequence emitStartEvent() {
@Override
protected AbstractTreeNodeSerializerSource generateSerializer(final GeneratedType type,
- final AugmentationSchema schema) {
+ final AugmentationSchemaNode schema) {
return new AbstractDataNodeContainerSerializerSource(this, type, schema) {
@Override
import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerImplementation;
import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerRegistry;
import org.opendaylight.yangtools.util.ClassLoaderUtils;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
} else {
source = generateMapEntrySerializer(generatedType, casted);
}
- } else if (schema instanceof AugmentationSchema) {
- source = generateSerializer(generatedType, (AugmentationSchema) schema);
- } else if (schema instanceof ChoiceCaseNode) {
- source = generateCaseSerializer(generatedType, (ChoiceCaseNode) schema);
+ } else if (schema instanceof AugmentationSchemaNode) {
+ source = generateSerializer(generatedType, (AugmentationSchemaNode) schema);
+ } else if (schema instanceof CaseSchemaNode) {
+ source = generateCaseSerializer(generatedType, (CaseSchemaNode) schema);
} else if (schema instanceof NotificationDefinition) {
source = generateNotificationSerializer(generatedType, (NotificationDefinition) schema);
} else {
* @param node - schema of case
* @return source for case node writer
*/
- protected abstract AbstractTreeNodeSerializerSource generateCaseSerializer(GeneratedType type, ChoiceCaseNode node);
+ protected abstract AbstractTreeNodeSerializerSource generateCaseSerializer(GeneratedType type, CaseSchemaNode node);
/**
* Generates serializer source for supplied list node, which will read
* @return source for augmentation node writer
*/
protected abstract AbstractTreeNodeSerializerSource generateSerializer(GeneratedType type,
- AugmentationSchema schema);
+ AugmentationSchemaNode schema);
/**
* Generates serializer source for notification node, which will read
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
import org.slf4j.Logger;
private static String getGetterName(final DataSchemaNode node) {
final TypeDefinition<?> type;
- if (node instanceof TypedSchemaNode) {
- type = ((TypedSchemaNode) node).getType();
+ if (node instanceof TypedDataSchemaNode) {
+ type = ((TypedDataSchemaNode) node).getType();
} else {
type = null;
}
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableBiMap;
import java.lang.reflect.Method;
-import java.net.URI;
import java.util.AbstractMap.SimpleEntry;
import java.util.Collection;
-import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
private Module getModuleBlocking(final Class<?> modeledClass) {
final QNameModule moduleName = BindingReflections.getQNameModule(modeledClass);
- final URI namespace = moduleName.getNamespace();
- final Date revision = moduleName.getRevision();
BindingRuntimeContext localRuntimeContext = runtimeContext;
Module module = localRuntimeContext == null ? null
- : localRuntimeContext.getSchemaContext().findModuleByNamespaceAndRevision(namespace, revision);
- if (module == null && futureSchema != null && futureSchema.waitForSchema(namespace, revision)) {
+ : localRuntimeContext.getSchemaContext().findModule(moduleName).get();
+ if (module == null && futureSchema != null && futureSchema.waitForSchema(moduleName)) {
localRuntimeContext = runtimeContext;
Preconditions.checkState(localRuntimeContext != null, "BindingRuntimeContext is not available.");
- module = localRuntimeContext.getSchemaContext().findModuleByNamespaceAndRevision(namespace, revision);
+ module = localRuntimeContext.getSchemaContext().findModule(moduleName).get();
}
Preconditions.checkState(module != null, "Schema for %s is not available.", modeledClass);
return module;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.SettableFuture;
-import java.net.URI;
import java.util.Collection;
-import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext;
import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
+import org.opendaylight.yangtools.yang.common.QNameModule;
@Beta
class FutureSchema implements AutoCloseable {
return schema != null;
}
- boolean waitForSchema(final URI namespace, final Date revision) {
+ boolean waitForSchema(final QNameModule module) {
final FutureSchemaPredicate postponedOp = new FutureSchemaPredicate() {
@Override
public boolean apply(final BindingRuntimeContext input) {
- return input.getSchemaContext().findModuleByNamespaceAndRevision(namespace, revision) != null;
+ return input.getSchemaContext().findModule(module).isPresent();
}
};
return postponedOp.waitForSchema();
}
public static void checkModulePresent(final SchemaContext schemaContext, final QName name) {
- if (schemaContext.findModuleByNamespaceAndRevision(name.getNamespace(), name.getRevision()) == null) {
+ if (!schemaContext.findModule(name.getModule()).isPresent()) {
throw MissingSchemaException.create("Module %s is not present in current schema context.",name.getModule());
}
}
import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
/**
* Context for prototype of augmentation node.
*/
@Beta
public final class AugmentationNodeContext<D extends TreeNode & Augmentation<?>>
- extends TreeNodeCodecContext<D, AugmentationSchema> {
+ extends TreeNodeCodecContext<D, AugmentationSchemaNode> {
/**
* Prepare context for augmentation node from prototype.
* @param prototype
* - codec prototype of augmentation node
*/
- public AugmentationNodeContext(final DataContainerCodecPrototype<AugmentationSchema> prototype) {
+ public AugmentationNodeContext(final DataContainerCodecPrototype<AugmentationSchemaNode> prototype) {
super(prototype);
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
/**
* Codec context for serializing and deserializing choice case node and it's
* - type of tree node
*/
@Beta
-public final class CaseNodeCodecContext<D extends TreeNode> extends TreeNodeCodecContext<D, ChoiceCaseNode> {
+public final class CaseNodeCodecContext<D extends TreeNode> extends TreeNodeCodecContext<D, CaseSchemaNode> {
/**
* Prepare context for choice case node from prototype.
* @param prototype
* - codec prototype of choice case node
*/
- public CaseNodeCodecContext(final DataContainerCodecPrototype<ChoiceCaseNode> prototype) {
+ public CaseNodeCodecContext(final DataContainerCodecPrototype<CaseSchemaNode> prototype) {
super(prototype);
}
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.slf4j.Logger;
for (final Class<?> caze : factory().getRuntimeContext().getCases(getBindingClass())) {
// We try to load case using exact match thus name
// and original schema must equals
- final DataContainerCodecPrototype<ChoiceCaseNode> cazeDef = loadCase(caze);
+ final DataContainerCodecPrototype<CaseSchemaNode> cazeDef = loadCase(caze);
// If we have case definition, this case is instantiated
// at current location and thus is valid in context of parent choice
if (cazeDef != null) {
// Updates collection of YANG instance identifier to case
for (final DataSchemaNode cazeChild : cazeDef.getSchema().getChildNodes()) {
if (cazeChild.isAugmenting()) {
- final AugmentationSchema augment =
+ final AugmentationSchemaNode augment =
SchemaUtils.findCorrespondingAugment(cazeDef.getSchema(), cazeChild);
if (augment != null) {
byYangCaseChildBuilder.put(SchemaUtils.getNodeIdentifierForAugmentation(augment), cazeDef);
return byCaseChildClass.keySet();
}
- private DataContainerCodecPrototype<ChoiceCaseNode> loadCase(final Class<?> childClass) {
- final Optional<ChoiceCaseNode> childSchema =
+ private DataContainerCodecPrototype<CaseSchemaNode> loadCase(final Class<?> childClass) {
+ final Optional<CaseSchemaNode> childSchema =
factory().getRuntimeContext().getCaseSchemaDefinition(getSchema(), childClass);
if (childSchema.isPresent()) {
return DataContainerCodecPrototype.from(childClass, childSchema.get(), factory());
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
final DataNodeContainer childSchema) {
final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
- if (leaf instanceof TypedSchemaNode) {
- getterToLeafSchema.put(getGetterName(leaf.getQName(), ((TypedSchemaNode) leaf).getType()), leaf);
+ if (leaf instanceof TypedDataSchemaNode) {
+ getterToLeafSchema.put(getGetterName(leaf.getQName(), ((TypedDataSchemaNode) leaf).getType()), leaf);
}
}
return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
}
private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
- Preconditions.checkArgument(schema instanceof TypedSchemaNode, "Unsupported leaf node type %s", schema);
+ Preconditions.checkArgument(schema instanceof TypedDataSchemaNode, "Unsupported leaf node type %s", schema);
- return getCodec(valueType, ((TypedSchemaNode) schema).getType());
+ return getCodec(valueType, ((TypedDataSchemaNode) schema).getType());
}
/**
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@SuppressWarnings({ "rawtypes", "unchecked" })
static DataContainerCodecPrototype<?> from(final Class<?> augClass, final AugmentationIdentifier arg,
- final AugmentationSchema schema, final CodecContextFactory factory) {
+ final AugmentationSchemaNode schema, final CodecContextFactory factory) {
return new DataContainerCodecPrototype(augClass, arg, schema, factory);
}
}
} else if (schema instanceof ChoiceSchemaNode) {
return new ChoiceNodeCodecContext(this);
- } else if (schema instanceof AugmentationSchema) {
+ } else if (schema instanceof AugmentationSchemaNode) {
return new AugmentationNodeContext(this);
- } else if (schema instanceof ChoiceCaseNode) {
+ } else if (schema instanceof CaseSchemaNode) {
return new CaseNodeCodecContext(this);
}
throw new IllegalArgumentException("Unsupported type " + bindingClass + " " + schema);
boolean isChoice() {
return schema instanceof ChoiceSchemaNode;
}
-}
\ No newline at end of file
+}
import com.google.common.annotations.Beta;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.lang.reflect.InvocationHandler;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
+import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.opendaylight.mdsal.binding.javav2.dom.codec.api.AugmentationReader;
import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections;
result = prime * result + Objects.hashCode(value);
}
if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
- result = prime * result + (getAugmentationsImpl().hashCode());
+ result = prime * result + getAugmentationsImpl().hashCode();
}
cachedHashcode = result;
return result;
Preconditions.checkNotNull(cls,"Supplied augmentation must not be null.");
@SuppressWarnings({"unchecked","rawtypes"})
- final Optional<DataContainerCodecContext<?,?>> augCtx = context.possibleStreamChild((Class) cls);
+ final Optional<DataContainerCodecContext<?,?>> augCtx = context.possibleStreamChild((Class) cls).toJavaUtil();
if (augCtx.isPresent()) {
final Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.get().getDomPathArgument());
if (augData.isPresent()) {
final LazyTreeNode<?> other = (LazyTreeNode<?>) obj;
return Objects.equals(context, other.context) && Objects.equals(data, other.data);
}
-}
\ No newline at end of file
+}
private static Object createDefaultObject(final DataSchemaNode schema, final Codec<Object, Object> codec,
final SchemaContext schemaContext) {
if (schema instanceof LeafSchemaNode) {
- Object defaultValue = ((LeafSchemaNode) schema).getDefault();
TypeDefinition<?> type = ((LeafSchemaNode) schema).getType();
- if (defaultValue != null) {
+ java.util.Optional<? extends Object> defaultValue = type.getDefaultValue();
+ if (defaultValue.isPresent()) {
if (type instanceof IdentityrefTypeDefinition) {
- return qnameDomValueFromString(codec, schema, (String) defaultValue, schemaContext);
+ return qnameDomValueFromString(codec, schema, (String) defaultValue.get(), schemaContext);
}
return domValueFromString(codec, type, defaultValue);
- } else {
- while (type.getBaseType() != null && type.getDefaultValue() == null) {
- type = type.getBaseType();
- }
+ }
+
+ while (type.getBaseType() != null && !type.getDefaultValue().isPresent()) {
+ type = type.getBaseType();
+ }
- defaultValue = type.getDefaultValue();
- if (defaultValue != null) {
- if (type instanceof IdentityrefTypeDefinition) {
- return qnameDomValueFromString(codec, schema, (String) defaultValue, schemaContext);
- }
- return domValueFromString(codec, type, defaultValue);
+ defaultValue = type.getDefaultValue();
+ if (defaultValue != null) {
+ if (type instanceof IdentityrefTypeDefinition) {
+ return qnameDomValueFromString(codec, schema, (String) defaultValue.get(), schemaContext);
}
+ return domValueFromString(codec, type, defaultValue);
}
}
return null;
if (prefixEndIndex != -1) {
final String defaultValuePrefix = defaultValue.substring(0, prefixEndIndex);
- final Module module = schemaContext.findModuleByNamespaceAndRevision(schema.getQName().getNamespace(),
- schema.getQName().getRevision());
+ final Module module = schemaContext.findModule(schema.getQName().getModule()).get();
if (module.getPrefix().equals(defaultValuePrefix)) {
- return codec
- .deserialize(QName.create(module.getQNameModule(), defaultValue.substring(prefixEndIndex + 1)));
- } else {
- final Set<ModuleImport> imports = module.getImports();
- for (final ModuleImport moduleImport : imports) {
- if (moduleImport.getPrefix().equals(defaultValuePrefix)) {
- final Module importedModule = schemaContext.findModuleByName(moduleImport.getModuleName(),
- moduleImport.getRevision());
- return codec.deserialize(QName.create(importedModule.getQNameModule(),
- defaultValue.substring(prefixEndIndex + 1)));
- }
+ return codec.deserialize(QName.create(module.getQNameModule(),
+ defaultValue.substring(prefixEndIndex + 1)));
+ }
+
+ final Set<ModuleImport> imports = module.getImports();
+ for (final ModuleImport moduleImport : imports) {
+ if (moduleImport.getPrefix().equals(defaultValuePrefix)) {
+ final Module importedModule = schemaContext.findModule(moduleImport.getModuleName(),
+ moduleImport.getRevision()).get();
+ return codec.deserialize(QName.create(importedModule.getQNameModule(),
+ defaultValue.substring(prefixEndIndex + 1)));
}
- return null;
}
+ return null;
}
return codec.deserialize(QName.create(schema.getQName(), defaultValue));
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
*/
@SuppressWarnings("rawtypes")
final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
- if ((getBindingClass().equals(augTarget))) {
+ if (getBindingClass().equals(augTarget)) {
for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
&& BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
}
@SuppressWarnings("unchecked")
- final Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
+ final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
.getResolvedAugmentationSchema(getSchema(), augClass);
return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
}
public Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
final NodeCodecContext<?> childContext = byMethod.get(method).get();
@SuppressWarnings("unchecked")
- final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
+ final java.util.Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
if (domChild.isPresent()) {
return childContext.deserializeObject(domChild.get());
} else if (childContext instanceof LeafNodeCodecContext) {
}
}
for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
- final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
+ final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
if (augData.isPresent()) {
map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
}
package org.opendaylight.mdsal.binding.javav2.dom.codec.modification;
import com.google.common.annotations.Beta;
-import com.google.common.base.Optional;
+import java.util.Optional;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
UNKNOWN;
static BindingStructuralType from(final DataTreeCandidateNode domChildNode) {
- final Optional<NormalizedNode<?, ?>> dataBased = domChildNode.getDataAfter().or(domChildNode.getDataBefore());
+ Optional<NormalizedNode<?, ?>> dataBased = domChildNode.getDataAfter();
+ if (!dataBased.isPresent()) {
+ dataBased = domChildNode.getDataBefore();
+ }
if (dataBased.isPresent()) {
return from(dataBased.get());
}
package org.opendaylight.mdsal.binding.javav2.dom.codec.modification;
import com.google.common.annotations.Beta;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
+import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.opendaylight.mdsal.binding.javav2.api.TreeNodeModification;
*/
package org.opendaylight.mdsal.binding.javav2.dom.codec.serialized;
-import com.google.common.base.Optional;
import java.util.Collection;
import java.util.Map;
+import java.util.Optional;
import javax.annotation.Nonnull;
import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder;
import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
@Beta
public final class ModuleContext {
private GeneratedTypeBuilder moduleNode;
- private final Map<SchemaPath,GeneratedTOBuilder> genTOs = new HashMap<>();
+ private final Map<SchemaPath, GeneratedTOBuilder> genTOs = new HashMap<>();
private final Map<SchemaPath, Type> typedefs = new HashMap<>();
private final Map<SchemaPath, GeneratedTypeBuilder> childNodes = new HashMap<>();
private final BiMap<String, GeneratedTypeBuilder> dataTypes = HashBiMap.create();
private final Map<QName,GeneratedTOBuilder> identities = new HashMap<>();
private final Set<GeneratedTypeBuilder> topLevelNodes = new HashSet<>();
private final List<GeneratedTypeBuilder> augmentations = new ArrayList<>();
- private final BiMap<Type,AugmentationSchema> typeToAugmentation = HashBiMap.create();
+ private final BiMap<Type, AugmentationSchemaNode> typeToAugmentation = HashBiMap.create();
private final BiMap<SchemaPath,Type> targetToAugmentation = HashBiMap.create();
private final Map<Type,Object> typeToSchema = new HashMap<>();
private final Multimap<Type, Type> choiceToCases = HashMultimap.create();
- private final BiMap<Type,ChoiceCaseNode> caseTypeToSchema = HashBiMap.create();
+ private final BiMap<Type, CaseSchemaNode> caseTypeToSchema = HashBiMap.create();
private final Map<SchemaPath, Type> innerTypes = new HashMap<>();
- private final Map<SchemaPath,GeneratedTypeBuilder> keyTypes = new HashMap<>();
+ private final Map<SchemaPath, GeneratedTypeBuilder> keyTypes = new HashMap<>();
//map is getting manipulated based on unique YANG module namespace rule
private final ListMultimap<String, String> packagesMap = Multimaps.synchronizedListMultimap
(ArrayListMultimap.create());
return Collections.unmodifiableList(this.augmentations);
}
- public BiMap<Type, AugmentationSchema> getTypeToAugmentation() {
+ public BiMap<Type, AugmentationSchemaNode> getTypeToAugmentation() {
return Maps.unmodifiableBiMap(this.typeToAugmentation);
}
return Maps.unmodifiableBiMap(this.targetToAugmentation);
}
- public void addTypeToAugmentation(final GeneratedTypeBuilder builder, final AugmentationSchema schema) {
+ public void addTypeToAugmentation(final GeneratedTypeBuilder builder, final AugmentationSchemaNode schema) {
this.typeToAugmentation.put(builder, schema);
this.typeToSchema.put(builder, schema);
}
this.targetToAugmentation.put(augmentTarget, builder);
}
- public void addChoiceToCaseMapping(final Type choiceType, final Type caseType, final ChoiceCaseNode schema) {
+ public void addChoiceToCaseMapping(final Type choiceType, final Type caseType, final CaseSchemaNode schema) {
this.choiceToCases.put(choiceType, caseType);
this.caseTypeToSchema.put(caseType, schema);
this.typeToSchema.put(caseType, schema);
}
- public BiMap<Type, ChoiceCaseNode> getCaseTypeToSchemas() {
+ public BiMap<Type, CaseSchemaNode> getCaseTypeToSchemas() {
return Maps.unmodifiableBiMap(this.caseTypeToSchema);
}
*
* Returns mapping of type to its schema.
*
- * Valid values are only instances of {@link DataSchemaNode} or {@link AugmentationSchema}
+ * Valid values are only instances of {@link DataSchemaNode} or {@link AugmentationSchemaNode}
*
* @return Mapping from type to corresponding schema
*/
import com.google.common.annotations.Beta;
import java.util.List;
+import java.util.Optional;
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;
@Beta
public interface Restrictions {
- List<LengthConstraint> getLengthConstraints();
+ Optional<LengthConstraint> getLengthConstraint();
List<PatternConstraint> getPatternConstraints();
- List<RangeConstraint> getRangeConstraints();
+ Optional<? extends RangeConstraint<?>> getRangeConstraint();
boolean isEmpty();
}
import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.processUsesImplements;
import com.google.common.annotations.Beta;
-import com.google.common.base.Optional;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.Optional;
import java.util.stream.Collectors;
import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext;
import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider;
import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
/**
* Comparator based on augment target path.
*/
- private static final Comparator<AugmentationSchema> AUGMENT_COMP = (o1, o2) -> {
+ private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
/**
* Comparator based on augment target path.
*/
- private static final Comparator<Map.Entry<SchemaPath, List<AugmentationSchema>>> AUGMENTS_COMP = (o1, o2) -> {
+ private static final Comparator<Map.Entry<SchemaPath, List<AugmentationSchemaNode>>> AUGMENTS_COMP = (o1, o2) -> {
final Iterator<QName> thisIt = o1.getKey().getPathFromRoot().iterator();
final Iterator<QName> otherIt = o2.getKey().getPathFromRoot().iterator();
Preconditions.checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
final String basePackageName = BindingMapping.getRootPackageName(module);
- final List<AugmentationSchema> augmentations = resolveAugmentations(module, schemaContext);
+ final List<AugmentationSchemaNode> augmentations = resolveAugmentations(module, schemaContext);
Map<Module, ModuleContext> resultCtx = genCtx;
//let's group augments by target path
- Map<SchemaPath, List<AugmentationSchema>> augmentationsGrouped =
- augmentations.stream().collect(Collectors.groupingBy(AugmentationSchema::getTargetPath));
+ Map<SchemaPath, List<AugmentationSchemaNode>> augmentationsGrouped =
+ augmentations.stream().collect(Collectors.groupingBy(AugmentationSchemaNode::getTargetPath));
- List<Map.Entry<SchemaPath, List<AugmentationSchema>>> sortedAugmentationsGrouped =
+ List<Map.Entry<SchemaPath, List<AugmentationSchemaNode>>> sortedAugmentationsGrouped =
new ArrayList<>(augmentationsGrouped.entrySet());
Collections.sort(sortedAugmentationsGrouped, AUGMENTS_COMP);
//process child nodes of grouped augment entries
- for (Map.Entry<SchemaPath, List<AugmentationSchema>> schemaPathAugmentListEntry : sortedAugmentationsGrouped) {
+ for (Map.Entry<SchemaPath, List<AugmentationSchemaNode>> schemaPathAugmentListEntry : sortedAugmentationsGrouped) {
resultCtx = augmentationToGenTypes(basePackageName, schemaPathAugmentListEntry, module, schemaContext,
verboseClassComments, resultCtx, genTypeBuilders, typeProvider);
- for (AugmentationSchema augSchema : schemaPathAugmentListEntry.getValue()) {
+ for (AugmentationSchemaNode augSchema : schemaPathAugmentListEntry.getValue()) {
processUsesImplements(augSchema, module, schemaContext, genCtx, BindingNamespaceType.Data);
}
* @throws IllegalStateException
* if set of module augmentations is null
*/
- private static List<AugmentationSchema> resolveAugmentations(final Module module, final SchemaContext schemaContext) {
+ @VisibleForTesting
+ static List<AugmentationSchemaNode> resolveAugmentations(final Module module,
+ final SchemaContext schemaContext) {
Preconditions.checkArgument(module != null, "Module reference cannot be NULL.");
Preconditions.checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
- final List<AugmentationSchema> sortedAugmentations = module.getAugmentations().stream()
+ final List<AugmentationSchemaNode> sortedAugmentations = module.getAugmentations().stream()
.filter(aug -> !module.equals(findAugmentTargetModule(schemaContext, aug)))
.collect(Collectors.toList());
sortedAugmentations.sort(AUGMENT_COMP);
return sortedAugmentations;
}
- public static Module findAugmentTargetModule(final SchemaContext schemaContext , final AugmentationSchema aug) {
+ public static Module findAugmentTargetModule(final SchemaContext schemaContext,
+ final AugmentationSchemaNode aug) {
Preconditions.checkNotNull(aug, "Augmentation schema can not be null.");
final QName first = aug.getTargetPath().getPathFromRoot().iterator().next();
- return schemaContext.findModuleByNamespaceAndRevision(first.getNamespace(), first.getRevision());
+ return schemaContext.findModule(first.getModule()).orElse(null);
}
/**
* if augment target path is null
* @return generated context
*/
- private static Map<Module, ModuleContext> augmentationToGenTypes(final String basePackageName,
- final Entry<SchemaPath, List<AugmentationSchema>> schemaPathAugmentListEntry, final Module module,
+ @VisibleForTesting
+ static Map<Module, ModuleContext> augmentationToGenTypes(final String basePackageName,
+ final Entry<SchemaPath, List<AugmentationSchemaNode>> schemaPathAugmentListEntry, final Module module,
final SchemaContext schemaContext, final boolean verboseClassComments,
Map<Module, ModuleContext> genCtx, final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders,
final TypeProvider typeProvider) {
Preconditions.checkState(targetPath != null,
"Augmentation List Entry does not contain Target Path (Target Path is NULL).");
- final List<AugmentationSchema> augmentationSchemaList = schemaPathAugmentListEntry.getValue();
+ final List<AugmentationSchemaNode> augmentationSchemaList = schemaPathAugmentListEntry.getValue();
Preconditions.checkState(!augmentationSchemaList.isEmpty(),
"Augmentation List cannot be empty.");
SchemaNode targetSchemaNode = SchemaContextUtil.findDataSchemaNode(schemaContext, targetPath);
if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
if (targetSchemaNode instanceof DerivableSchemaNode) {
- targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
+ targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
}
if (targetSchemaNode == null) {
throw new IllegalStateException("Failed to find target node from grouping in augmentation " +
@Deprecated
static Map<Module, ModuleContext> usesAugmentationToGenTypes(final SchemaContext schemaContext,
- final String augmentPackageName, final List<AugmentationSchema> schemaPathAugmentListEntry, final Module module,
- final UsesNode usesNode, final DataNodeContainer usesNodeParent, Map<Module, ModuleContext> genCtx,
+ final String augmentPackageName, final List<AugmentationSchemaNode> schemaPathAugmentListEntry,
+ final Module module, final UsesNode usesNode, final DataNodeContainer usesNodeParent,
+ Map<Module, ModuleContext> genCtx,
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final boolean verboseClassComments,
final TypeProvider typeProvider, final BindingNamespaceType namespaceType) {
if (usesNodeParent instanceof SchemaNode) {
packageName = BindingGeneratorUtil.packageNameForAugmentedGeneratedType(augmentPackageName,
((SchemaNode) usesNodeParent).getPath());
- } else if (usesNodeParent instanceof AugmentationSchema) {
+ } else if (usesNodeParent instanceof AugmentationSchemaNode) {
Type parentTypeBuilder = genCtx.get(module).getTargetToAugmentation()
- .get(((AugmentationSchema) usesNodeParent).getTargetPath());
- packageName = BindingGeneratorUtil.packageNameForAugmentedGeneratedType(parentTypeBuilder.getPackageName(),
- (AugmentationSchema)usesNodeParent);
+ .get(((AugmentationSchemaNode) usesNodeParent).getTargetPath());
+ packageName = BindingGeneratorUtil.packageNameForAugmentedGeneratedType(
+ parentTypeBuilder.getPackageName(), (AugmentationSchemaNode)usesNodeParent);
}
genCtx = GenHelperUtil.addRawAugmentGenTypeDefinition(module, packageName,
targetTypeBuilder.toInstance(), targetSchemaNode, schemaPathAugmentListEntry, genTypeBuilders, genCtx,
* parent of uses node
* @return node from its original location in grouping
*/
- private static DataSchemaNode findOriginalTargetFromGrouping(final SchemaContext schemaContext, final SchemaPath targetPath,
- final UsesNode parentUsesNode) {
+ @VisibleForTesting
+ static DataSchemaNode findOriginalTargetFromGrouping(final SchemaContext schemaContext,
+ final SchemaPath targetPath, final UsesNode parentUsesNode) {
SchemaNode targetGrouping = null;
QName current = parentUsesNode.getGroupingPath().getPathFromRoot().iterator().next();
- Module module = schemaContext.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
+ Module module = schemaContext.findModule(current.getModule()).orElse(null);
if (module == null) {
throw new IllegalArgumentException("Fialed to find module for grouping in: " + parentUsesNode);
- } else {
- for (GroupingDefinition group : module.getGroupings()) {
- if (group.getQName().equals(current)) {
- targetGrouping = group;
- break;
- }
+ }
+ for (GroupingDefinition group : module.getGroupings()) {
+ if (group.getQName().equals(current)) {
+ targetGrouping = group;
+ break;
}
}
final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
result = ((DataNodeContainer) result).getDataChildByName(resultNode);
} else if (result instanceof ChoiceSchemaNode) {
- result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
+ result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
}
}
if (result == null) {
* <li>if <code>augmentedNodes</code> is null</li>
* </ul>
*/
- private static Map<Module, ModuleContext> generateTypesFromAugmentedChoiceCases(
+ @VisibleForTesting
+ static Map<Module, ModuleContext> generateTypesFromAugmentedChoiceCases(
final SchemaContext schemaContext, final Module module,
final String basePackageName, final Type targetType, final ChoiceSchemaNode targetNode,
- final List<AugmentationSchema> schemaPathAugmentListEntry,
+ final List<AugmentationSchemaNode> schemaPathAugmentListEntry,
final DataNodeContainer usesNodeParent,
final Map<Module, ModuleContext> genCtx, final boolean verboseClassComments,
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final TypeProvider typeProvider,
Preconditions.checkArgument(schemaPathAugmentListEntry != null, "Set of Choice Case Nodes cannot be NULL.");
- for (final AugmentationSchema augmentationSchema : schemaPathAugmentListEntry) {
+ for (final AugmentationSchemaNode augmentationSchema : schemaPathAugmentListEntry) {
for (final DataSchemaNode caseNode : augmentationSchema.getChildNodes()) {
if (caseNode != null) {
final GeneratedTypeBuilder caseTypeBuilder = GenHelperUtil.addDefaultInterfaceDefinition(basePackageName,
GeneratedTypeBuilder childOfType = null;
if (parent instanceof Module) {
childOfType = genCtx.get(parent).getModuleNode();
- } else if (parent instanceof ChoiceCaseNode) {
+ } else if (parent instanceof CaseSchemaNode) {
childOfType = GenHelperUtil.findCaseByPath(parent.getPath(), genCtx);
} else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
childOfType = GenHelperUtil.findChildNodeByPath(parent.getPath(), genCtx);
throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
}
- ChoiceCaseNode node = null;
+ CaseSchemaNode node = null;
final String caseLocalName = caseNode.getQName().getLocalName();
- if (caseNode instanceof ChoiceCaseNode) {
- node = (ChoiceCaseNode) caseNode;
- } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
+ if (caseNode instanceof CaseSchemaNode) {
+ node = (CaseSchemaNode) caseNode;
+ } else if (findNamedCase(targetNode, caseLocalName) == null) {
final String targetNodeLocalName = targetNode.getQName().getLocalName();
for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
().getLocalName())) {
- node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
+ node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
break;
}
}
} else {
- node = targetNode.getCaseNodeByName(caseLocalName);
+ node = findNamedCase(targetNode, caseLocalName);
}
final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
if (childNodes != null) {
}
return genCtx;
}
+
+ private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
+ final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
+ return cases.isEmpty() ? null : cases.get(0);
+ }
}
import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
return (namespaceType.equals(BindingNamespaceType.Data)
&& (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
|| schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition
- || schemaNode instanceof ChoiceCaseNode));
+ || schemaNode instanceof CaseSchemaNode));
}
static Constant qNameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
* @return string with the name of the getter method for
* <code>methodName</code> in JAVA method format
*/
- private static String getterMethodName(final String localName, final Type returnType) {
+ @VisibleForTesting
+ static String getterMethodName(final String localName, final Type returnType) {
final StringBuilder method = new StringBuilder();
if (BOOLEAN.equals(returnType)) {
method.append("is");
final SchemaContext schemaContext, final boolean verboseClassComments,
final BindingNamespaceType namespaceType) {
final StringBuilder sb = new StringBuilder();
- final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
+ final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription().orElse(null));
final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
if (!Strings.isNullOrEmpty(formattedDescription)) {
static String createDescription(final Module module, final boolean verboseClassComments) {
final StringBuilder sb = new StringBuilder();
- final String moduleDescription = encodeAngleBrackets(module.getDescription());
+ final String moduleDescription = encodeAngleBrackets(module.getDescription().orElse(null));
final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
if (!Strings.isNullOrEmpty(formattedDescription)) {
return replaceAllIllegalChars(sb);
}
- private static boolean isNullOrEmpty(final Collection<?> list) {
+ @VisibleForTesting
+ static boolean isNullOrEmpty(final Collection<?> list) {
return list == null || list.isEmpty();
}
final Map<Module, ModuleContext> genCtx, final GeneratedTypeBuilder typeBuilder, final Module module) {
if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName.getLocalName(), genCtx.get(module));
- final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
+ final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null));
enumBuilder.setDescription(enumTypedefDescription);
enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
final ModuleContext ctx = genCtx.get(module);
static Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
final GeneratedTypeBuilder typeBuilder, final Module parentModule, final TypeProvider typeProvider) {
final GeneratedTOBuilderImpl returnType = (GeneratedTOBuilderImpl) genTOBuilder;
- final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
+ final String typedefDescription = encodeAngleBrackets(typeDef.getDescription().orElse(null));
returnType.setDescription(typedefDescription);
- returnType.setReference(typeDef.getReference());
+ returnType.setReference(typeDef.getReference().orElse(null));
returnType.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
returnType.setModuleName(parentModule.getName());
genTOBuilder.setTypedef(true);
genTOBuilder.setIsUnion(true);
- TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
+ TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
return returnType.toInstance();
}
leafGetterName = leafName;
}
- final String leafDesc = encodeAngleBrackets(leaf.getDescription());
+ final String leafDesc = encodeAngleBrackets(leaf.getDescription().orElse(null));
final GeneratedPropertyBuilder propBuilder =
toBuilder.addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(leafGetterName, JavaIdentifier.METHOD));
propBuilder.setReadOnly(isReadOnly);
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AnyDataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
genCtx.get(module));
addImplementedInterfaceFromUses(module, moduleDataTypeBuilder, genCtx);
moduleDataTypeBuilder.addImplementsType(BindingTypes.TREE_ROOT);
- moduleDataTypeBuilder.addComment(module.getDescription());
+ moduleDataTypeBuilder.addComment(module.getDescription().orElse(null));
moduleDataTypeBuilder.setDescription(createDescription(module, verboseClassComments));
- moduleDataTypeBuilder.setReference(module.getReference());
+ moduleDataTypeBuilder.setReference(module.getReference().orElse(null));
return moduleDataTypeBuilder;
}
final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName, context);
moduleBuilder.setDescription(createDescription(module, verboseClassComments));
- moduleBuilder.setReference(module.getReference());
+ moduleBuilder.setReference(module.getReference().orElse(null));
moduleBuilder.setModuleName(moduleName);
return moduleBuilder;
}
}
final QName qname = schemaNode.getPath().getLastComponent();
- final Module originalModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
- qname.getRevision());
+ final Module originalModule = schemaContext.findModule(qname.getModule()).get();
return module.equals(originalModule);
}
childNodeQName = QName.create(((Module) node).getQNameModule(), superChildNode.getQName().getLocalName());
} else if (node instanceof SchemaNode) {
childNodeQName = QName.create(((SchemaNode) node).getQName(), superChildNode.getQName().getLocalName());
- } else if (node instanceof AugmentationSchema) {
+ } else if (node instanceof AugmentationSchemaNode) {
childNodeQName = QName.create(module.getQNameModule(), superChildNode.getQName().getLocalName());
} else {
throw new IllegalArgumentException("Not support node type:" + node);
}
}
} else if (superNode instanceof ChoiceSchemaNode) {
- for (ChoiceCaseNode superCaseNode : ((ChoiceSchemaNode) superNode).getCases()) {
+ for (CaseSchemaNode superCaseNode : ((ChoiceSchemaNode) superNode).getCases().values()) {
final QName childQName = createQNameFromSuperNode(module, node, superCaseNode);
- ChoiceCaseNode caseNode = ((ChoiceSchemaNode) node).getCaseNodeByName(childQName);
+ CaseSchemaNode caseNode = ((ChoiceSchemaNode) node).getCaseNodeByName(childQName);
Preconditions.checkNotNull(caseNode, "%s->%s", node, childQName);
final GeneratedTypeBuilder type = genCtx.get(module).getCase(caseNode.getPath());
final Object parentNode, final UsesNode usesNode) {
SchemaNode groupingNode;
if (parentNode instanceof Module) {
- final Module superModule = schemaContext.findModuleByNamespaceAndRevision(
- usesNode.getGroupingPath().getLastComponent().getModule().getNamespace(),
- usesNode.getGroupingPath().getLastComponent().getModule().getRevision());
+ final Module superModule = schemaContext.findModule(
+ usesNode.getGroupingPath().getLastComponent().getModule()).get();
groupingNode = superModule.getGroupings()
.stream().filter(grouping -> grouping.getPath().equals(usesNode.getGroupingPath()))
.findFirst().orElse(null);
//FIXME: Schema path is not unique for Yang 1.1, findDataSchemaNode always does search from data node first.
final Iterable<QName> prefixedPath = usesNode.getGroupingPath().getPathFromRoot();
final QName current = prefixedPath.iterator().next();
- final Module targetModule = schemaContext.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
+ final Module targetModule = schemaContext.findModule(current.getModule()).orElse(null);
Preconditions.checkArgument(targetModule != null, "Cannot find target module for %s and %s.",
current.getNamespace(), current.getRevision());
- groupingNode = targetModule.getGroupings().stream().filter(grouping -> grouping.getPath().equals(usesNode.getGroupingPath()))
+ groupingNode = targetModule.getGroupings().stream()
+ .filter(grouping -> grouping.getPath().equals(usesNode.getGroupingPath()))
.collect(Collectors.toList()).get(0);
if (groupingNode == null) {
groupingNode = SchemaContextUtil.findDataSchemaNode(schemaContext, usesNode.getGroupingPath());
return null;
}
- static Map<Module, ModuleContext> addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
- final Type targetTypeRef, final SchemaNode targetNode, final List<AugmentationSchema> schemaPathAugmentListEntry,
- final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final Map<Module, ModuleContext> genCtx,
- final SchemaContext schemaContext, final boolean verboseClassComments, final TypeProvider typeProvider,
+ static Map<Module, ModuleContext> addRawAugmentGenTypeDefinition(final Module module,
+ final String augmentPackageName, final Type targetTypeRef, final SchemaNode targetNode,
+ final List<AugmentationSchemaNode> schemaPathAugmentListEntry,
+ final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders,
+ final Map<Module, ModuleContext> genCtx, final SchemaContext schemaContext,
+ final boolean verboseClassComments, final TypeProvider typeProvider,
final BindingNamespaceType namespaceType) {
//pick augmentation grouped by augmentation target, there is always at least one
- final AugmentationSchema augSchema = schemaPathAugmentListEntry.get(0);
+ final AugmentationSchemaNode augSchema = schemaPathAugmentListEntry.get(0);
Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.computeIfAbsent(
augmentPackageName, k -> new HashMap<>());
//this requires valid semantics in YANG model
String augIdentifier = null;
- for (AugmentationSchema aug : schemaPathAugmentListEntry) {
+ for (AugmentationSchemaNode aug : schemaPathAugmentListEntry) {
augIdentifier = getAugmentIdentifier(aug.getUnknownSchemaNodes());
break;
}
annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
//produces getters for augTypeBuilder eventually
- for (AugmentationSchema aug : schemaPathAugmentListEntry) {
+ for (AugmentationSchemaNode aug : schemaPathAugmentListEntry) {
//apply all uses
addImplementedInterfaceFromUses(aug, augTypeBuilder, genCtx);
- augSchemaNodeToMethods(module, BindingMapping.getRootPackageName(module), augTypeBuilder, augTypeBuilder, aug.getChildNodes(),
- genCtx, schemaContext, verboseClassComments, typeProvider, genTypeBuilders, namespaceType);
+ augSchemaNodeToMethods(module, BindingMapping.getRootPackageName(module), augTypeBuilder, augTypeBuilder,
+ aug.getChildNodes(), genCtx, schemaContext, verboseClassComments, typeProvider, genTypeBuilders,
+ namespaceType);
}
augmentBuilders.put(augTypeBuilder.getName(), augTypeBuilder);
listenerInterface.addMethod(JavaIdentifierNormalizer.normalizeSpecificIdentifier(sb.toString(), JavaIdentifier.METHOD))
.setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
- .setComment(encodeAngleBrackets(notification.getDescription())).setReturnType(Types.VOID);
+ .setComment(encodeAngleBrackets(notification.getDescription().orElse(null))).setReturnType(Types.VOID);
return listenerInterface;
}
final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, schemaNodeName, context);
final Module module = SchemaContextUtil.findParentModule(schemaContext, schemaNode);
qNameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
- newType.addComment(schemaNode.getDescription());
+ newType.addComment(schemaNode.getDescription().orElse(null));
newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName(), schemaContext,
verboseClassComments, namespaceType));
- newType.setReference(schemaNode.getReference());
+ newType.setReference(schemaNode.getReference().orElse(null));
newType.setSchemaPath((List<QName>) schemaNode.getPath().getPathFromRoot());
newType.setModuleName(module.getName());
newType.setBasePackageName(BindingMapping.getRootPackageName(module));
final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(basePackageName, choiceNode,
schemaContext, "", "", verboseClasssComments, genTypeBuilders, namespaceType, genCtx.get(module));
constructGetter(parent, choiceNode.getQName().getLocalName(),
- choiceNode.getDescription(), choiceTypeBuilder, choiceNode.getStatus());
+ choiceNode.getDescription().orElse(null), choiceTypeBuilder, choiceNode.getStatus());
if (namespaceType.equals(BindingNamespaceType.Data)) {
choiceTypeBuilder.addImplementsType(parameterizedTypeFor(BindingTypes.INSTANTIABLE, choiceTypeBuilder));
}
schemaContext, verboseClassComments, genCtx, genTypeBuilders, typeProvider, namespaceType);
if (genType != null) {
StringBuilder getterName = new StringBuilder(node.getQName().getLocalName());
- constructGetter(parent, getterName.toString(), node.getDescription(), genType, node.getStatus());
+ constructGetter(parent, getterName.toString(), node.getDescription().orElse(null), genType, node.getStatus());
resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes(), genCtx,
schemaContext, verboseClassComments, genTypeBuilders, typeProvider, namespaceType);
processUsesImplements(node, module, schemaContext, genCtx, namespaceType);
getterReturnType = Types.listTypeFor(wildcardTypeFor(genType.getPackageName(), genType.getName(),
true, true, null));
}
- constructGetter(parent, nodeName, node.getDescription(), getterReturnType, node.getStatus());
+ constructGetter(parent, nodeName, node.getDescription().orElse(null), getterReturnType, node.getStatus());
final List<QName> listKeys = node.getKeyDefinition();
final String packageName = new StringBuilder(packageNameForGeneratedType(basePackageName, node.getPath(),
} else {
if (typeDef.getBaseType() == null && (typeDef instanceof EnumTypeDefinition
|| typeDef instanceof UnionTypeDefinition || typeDef instanceof BitsTypeDefinition)) {
- LeafSchemaNode originalLeaf = (LeafSchemaNode) ((DerivableSchemaNode) leaf).getOriginal().orNull();
+ LeafSchemaNode originalLeaf = (LeafSchemaNode) ((DerivableSchemaNode) leaf).getOriginal().orElse(null);
Preconditions.checkNotNull(originalLeaf);
returnType = genCtx.get(findParentModule(schemaContext, originalLeaf)).getInnerType(typeDef.getPath());
} else {
((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
}
- String leafDesc = leaf.getDescription();
- if (leafDesc == null) {
- leafDesc = "";
- }
-
final String leafGetterName;
if ("key".equals(leafName.toLowerCase())) {
StringBuilder sb = new StringBuilder(leafName)
} else {
leafGetterName = leafName;
}
- constructGetter(typeBuilder, leafGetterName, leafDesc, returnType, leaf.getStatus());
+ constructGetter(typeBuilder, leafGetterName, leaf.getDescription().orElse(""), returnType, leaf.getStatus());
return returnType;
}
}
final ParameterizedType listType = Types.listTypeFor(returnType);
- constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType, node.getStatus());
+ constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription().orElse(null), listType, node.getStatus());
return true;
}
checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
- final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
- if (caseNodes == null) {
- return;
- }
-
- for (final ChoiceCaseNode caseNode : caseNodes) {
+ for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
if (caseNode != null && resolveDataSchemaNodesCheck(module, schemaContext, caseNode)) {
final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(basePackageName, caseNode,
module, genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider, namespaceType);
if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
- if (parent instanceof AugmentationSchema) {
- final AugmentationSchema augSchema = (AugmentationSchema) parent;
+ if (parent instanceof AugmentationSchemaNode) {
+ final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
final SchemaPath targetPath = augSchema.getTargetPath();
SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
if (targetSchemaNode instanceof DataSchemaNode
&& ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
if (targetSchemaNode instanceof DerivableSchemaNode) {
- targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
+ targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
}
if (targetSchemaNode == null) {
throw new IllegalStateException(
return null;
}
- String anyDesc = node.getDescription();
- if (anyDesc == null) {
- anyDesc = "";
- }
-
Type returnType = Types.DOCUMENT;
-
- constructGetter(typeBuilder, anyName, anyDesc, returnType, node.getStatus());
+ constructGetter(typeBuilder, anyName, node.getDescription().orElse(""), returnType, node.getStatus());
return returnType;
}
// GeneratedType for this type definition should be already
// created
final QName qname = typeDef.getQName();
- final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
- qname.getRevision());
+ final Module unionModule = schemaContext.findModule(qname.getModule()).get();
final ModuleContext mc = genCtx.get(unionModule);
returnType = mc.getTypedefs().get(typeDef.getPath());
} else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
// Annonymous enumeration (already generated, since it is inherited via uses).
LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
QName qname = originalLeaf.getQName();
- final Module enumModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
- qname.getRevision());
+ final Module enumModule = schemaContext.findModule(qname.getModule()).orElse(null);
returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
} else {
returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, genCtx.get(module));
final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(basePackageName, node, childOf, module,
genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider, namespaceType);
- genType.addComment(node.getDescription());
+ genType.addComment(node.getDescription().orElse(null));
annotateDeprecatedIfNecessary(node.getStatus(), genType);
genType.setDescription(createDescription(node, genType.getFullyQualifiedName(), schemaContext,
verboseClassComments, namespaceType));
genType.setModuleName(module.getName());
- genType.setReference(node.getReference());
+ genType.setReference(node.getReference().orElse(null));
genType.setSchemaPath((List) node.getPath().getPathFromRoot());
genType.setParentTypeForBuilder(childOf);
if (node instanceof DataNodeContainer) {
}
newType.setAbstract(true);
- newType.addComment(identity.getDescription());
+ newType.addComment(identity.getDescription().orElse(null));
newType.setDescription(createDescription(identity, newType.getFullyQualifiedName(), schemaContext,
verboseClassComments, BindingNamespaceType.Identity));
- newType.setReference(identity.getReference());
+ newType.setReference(identity.getReference().orElse(null));
newType.setModuleName(module.getName());
newType.setSchemaPath((List) identity.getPath().getPathFromRoot());
import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.parameterizedTypeFor;
import com.google.common.annotations.Beta;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.Collection;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
/**
- *
* Util class used for generation of types for RPCs, routedRPCs and Actions (YANG 1.1 only)
* in Binding spec. v2. In case of routed RPC detected in input YANG, RPC is turned to Action.
- *
*/
@Beta
final class RpcActionGenHelper {
-
- private static final QName CONTEXT_REFERENCE =
+ @VisibleForTesting
+ static final QName CONTEXT_REFERENCE =
QName.create("urn:opendaylight:yang:extension:yang-ext", "2013-07-09", "context-reference").intern();
private RpcActionGenHelper() {
* @param schemaNode RPC input node
* @return presence optional
*/
- private static Optional<QName> getRoutingContext(final DataSchemaNode schemaNode) {
+ @VisibleForTesting
+ static Optional<QName> getRoutingContext(final DataSchemaNode schemaNode) {
for (UnknownSchemaNode extension : schemaNode.getUnknownSchemaNodes()) {
if (CONTEXT_REFERENCE.equals(extension.getNodeType())) {
return Optional.fromNullable(extension.getQName());
private static void resolveActions(final DataNodeContainer parent, final Module module,
final SchemaContext schemaContext, final boolean verboseClassComments,
- Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final Map<Module, ModuleContext> genCtx,
- TypeProvider typeProvider, final BindingNamespaceType namespaceType) {
+ final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final Map<Module, ModuleContext> genCtx,
+ final TypeProvider typeProvider, final BindingNamespaceType namespaceType) {
Preconditions.checkNotNull(parent, "Parent should not be NULL.");
final Collection<DataSchemaNode> potentials = parent.getChildNodes();
for (DataSchemaNode potential : potentials) {
* @param verboseClassComments verbosity switch
* @return generated context
*/
- static Map<Module, ModuleContext> actionMethodsToGenType(final Module module, Map<Module, ModuleContext> genCtx,
+ static Map<Module, ModuleContext> actionMethodsToGenType(final Module module, final Map<Module, ModuleContext> genCtx,
final SchemaContext schemaContext, final boolean verboseClassComments,
- Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, TypeProvider typeProvider) {
+ final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final TypeProvider typeProvider) {
checkModuleAndModuleName(module);
resolveActions(module, module, schemaContext, verboseClassComments, genTypeBuilders, genCtx, typeProvider,
*
* @return generated context
*/
- static Map<Module, ModuleContext> rpcMethodsToGenType(final Module module, Map<Module, ModuleContext> genCtx,
- final SchemaContext schemaContext, final boolean verboseClassComments, Map<String, Map<String,
- GeneratedTypeBuilder>> genTypeBuilders, TypeProvider typeProvider) {
+ static Map<Module, ModuleContext> rpcMethodsToGenType(final Module module, final Map<Module, ModuleContext> genCtx,
+ final SchemaContext schemaContext, final boolean verboseClassComments, final Map<String, Map<String,
+ GeneratedTypeBuilder>> genTypeBuilders, final TypeProvider typeProvider) {
checkModuleAndModuleName(module);
final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
*/
private static GeneratedTypeBuilder resolveOperation(final DataSchemaNode parent, final OperationDefinition operation,
final Module module, final SchemaContext schemaContext, final boolean verboseClassComments,
- Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final Map<Module, ModuleContext> genCtx,
- TypeProvider typeProvider, final boolean isAction, final BindingNamespaceType namespaceType) {
+ final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final Map<Module, ModuleContext> genCtx,
+ final TypeProvider typeProvider, final boolean isAction, final BindingNamespaceType namespaceType) {
//operation name
final String operationName = operation.getQName().getLocalName();
interfaceBuilder.setDescription(createDescription(operation, interfaceBuilder.getFullyQualifiedName(),
schemaContext, verboseClassComments, namespaceType));
- final String operationComment = encodeAngleBrackets(operation.getDescription());
+ final String operationComment = encodeAngleBrackets(operation.getDescription().orElse(null));
final MethodSignatureBuilder operationMethod = interfaceBuilder.addMethod("invoke");
//input
return interfaceBuilder;
}
- private static GeneratedTypeBuilder resolveOperationNode(GeneratedTypeBuilder parent, final Module module, final
+ private static GeneratedTypeBuilder resolveOperationNode(final GeneratedTypeBuilder parent, final Module module, final
ContainerSchemaNode operationNode, final String basePackageName, final SchemaContext schemaContext, final String
- operationName, final boolean verboseClassComments, TypeProvider typeProvider, Map<String, Map<String,
+ operationName, final boolean verboseClassComments, final TypeProvider typeProvider, final Map<String, Map<String,
GeneratedTypeBuilder>> genTypeBuilders, final Map<Module, ModuleContext> genCtx, final boolean isInput,
final BindingNamespaceType namespaceType) {
final GeneratedTypeBuilder nodeType = addRawInterfaceDefinition(basePackageName, operationNode, schemaContext,
*/
@Override
public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type, final SchemaNode parentNode,
- ModuleContext context) {
+ final ModuleContext context) {
if (type != null) {
return TYPE_MAP.get(type.getQName().getLocalName());
}
@Override
public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type, final SchemaNode parentNode,
- final Restrictions restrictions, ModuleContext context) {
+ final Restrictions restrictions, final ModuleContext context) {
final String typeName = type.getQName().getLocalName();
switch (typeName) {
}
};
- private static <T extends Number> Restrictions singleRangeRestrictions(final T min, final T max) {
+ private static <T extends Number & Comparable<T>> Restrictions singleRangeRestrictions(final T min, final T max) {
return Types.getDefaultRestrictions(min, max);
}
import java.util.Set;
import org.opendaylight.yangtools.util.TopologicalSort;
import org.opendaylight.yangtools.util.TopologicalSort.Node;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
ret.addAll(usesNodes);
for (UsesNode usesNode : usesNodes) {
- for (AugmentationSchema augment : usesNode.getAugmentations()) {
+ for (AugmentationSchemaNode augment : usesNode.getAugmentations()) {
ret.addAll(getAllUsesNodes(augment));
}
}
if (childNode instanceof DataNodeContainer) {
ret.addAll(getAllUsesNodes((DataNodeContainer) childNode));
} else if (childNode instanceof ChoiceSchemaNode) {
- Set<ChoiceCaseNode> cases = ((ChoiceSchemaNode) childNode).getCases();
- for (ChoiceCaseNode choiceCaseNode : cases) {
+ for (CaseSchemaNode choiceCaseNode : ((ChoiceSchemaNode) childNode).getCases().values()) {
ret.addAll(getAllUsesNodes(choiceCaseNode));
}
}
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.io.Serializable;
-import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Date;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.lang3.StringEscapeUtils;
import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder;
import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
@SuppressWarnings({ "rawtypes", "unchecked" })
static GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef, final
TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName, final SchemaContext
- schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap,
- ModuleContext context) {
+ schemaContext, final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap,
+ final ModuleContext context) {
Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
final String typedefName = typedef.getQName().getLocalName();
final String innerTypeDef = innerExtendedType.getQName().getLocalName();
final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typedefName, context);
- final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
+ final String typedefDescription = encodeAngleBrackets(typedef.getDescription().orElse(null));
genTOBuilder.setDescription(typedefDescription);
- genTOBuilder.setReference(typedef.getReference());
+ genTOBuilder.setReference(typedef.getReference().orElse(null));
genTOBuilder.setSchemaPath((List) typedef.getPath().getPathFromRoot());
genTOBuilder.setModuleName(moduleName);
genTOBuilder.setTypedef(true);
genTOBuilder.setIsUnion(true);
}
- Map<Date, Map<String, Type>> modulesByDate = null;
+ Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
Map<String, Type> typeMap = null;
final Module parentModule = findParentModule(schemaContext, innerExtendedType);
if (parentModule != null) {
genTOBuilder.setExtendsType((GeneratedTransferObject) type);
}
}
- addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+ addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
makeSerializable(genTOBuilder);
return genTOBuilder.toInstance();
* @return generated transfer object which represent<code>javaType</code>
*/
static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
- final Type javaType, final String moduleName, ModuleContext context) {
+ final Type javaType, final String moduleName, final ModuleContext context) {
Preconditions.checkNotNull(javaType, "javaType cannot be null");
final String propertyName = "value";
final List<String> regExps = resolveRegExpressionsFromTypedef(typedef);
addStringRegExAsConstant(genTOBuilder, regExps);
}
- addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+ addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
genTOBuilder.setTypedef(true);
makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
return genTOBuilder.toInstance();
final List<String> regExps = new ArrayList<>(patternConstraints.size());
for (final PatternConstraint patternConstraint : patternConstraints) {
- final String regEx = patternConstraint.getRegularExpression();
+ final String regEx = patternConstraint.getJavaPatternString();
final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
regExps.add(modifiedRegEx);
}
} else if (childNode instanceof ListSchemaNode) {
fillRecursively(list, (ListSchemaNode) childNode);
} else if (childNode instanceof ChoiceSchemaNode) {
- final Set<ChoiceCaseNode> cases = ((ChoiceSchemaNode) childNode).getCases();
- if (cases != null) {
- for (final ChoiceCaseNode caseNode : cases) {
- fillRecursively(list, caseNode);
- }
+ for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) childNode).getCases().values()) {
+ fillRecursively(list, caseNode);
}
}
});
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
static Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
- final SchemaNode parentNode, final SchemaContext schemaContext, ModuleContext context) {
+ final SchemaNode parentNode, final SchemaContext schemaContext, final ModuleContext context) {
Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
"Local Name in EnumTypeDefinition QName cannot be NULL!");
}
final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(packageName, enumName, context);
- final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
+ final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null));
enumBuilder.setDescription(enumTypedefDescription);
- enumBuilder.setReference(enumTypeDef.getReference());
+ enumBuilder.setReference(enumTypeDef.getReference().orElse(null));
enumBuilder.setModuleName(module.getName());
enumBuilder.setSchemaPath((List) enumTypeDef.getPath().getPathFromRoot());
enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName,
- final TypeDefinition<?> typedef, final String moduleName, ModuleContext context) {
+ final TypeDefinition<?> typedef, final String moduleName, final ModuleContext context) {
final String typeDefTOName = typedef.getQName().getLocalName();
- if ((basePackageName != null) && (typeDefTOName != null)) {
+ if (basePackageName != null && typeDefTOName != null) {
final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(basePackageName, typeDefTOName, context);
- final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
+ final String typedefDescription = encodeAngleBrackets(typedef.getDescription().orElse(null));
newType.setDescription(typedefDescription);
- newType.setReference(typedef.getReference());
+ newType.setReference(typedef.getReference().orElse(null));
newType.setSchemaPath((List) typedef.getPath().getPathFromRoot());
newType.setModuleName(moduleName);
}
static Module getParentModule(final SchemaNode node, final SchemaContext schemaContext) {
- final QName qname = node.getPath().getPathFromRoot().iterator().next();
- final URI namespace = qname.getNamespace();
- final Date revision = qname.getRevision();
- return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
+ return schemaContext.findModule(node.getPath().getPathFromRoot().iterator().next().getModule()).orElse(null);
}
}
import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
-import com.google.common.base.Optional;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.Collections;
-import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
/**
* Map<moduleName, Map<moduleDate, Map<typeName, type>>>
*/
- private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
+ private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap;
/**
* Map which maps schema paths to JAVA <code>Type</code>.
@Override
public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type, final SchemaNode parentNode,
- ModuleContext context) {
+ final ModuleContext context) {
return javaTypeForSchemaDefinitionType(type, parentNode, null, context);
}
*/
@Override
public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type, final SchemaNode parentNode, final
- Restrictions restrictions, ModuleContext context) {
+ Restrictions restrictions, final ModuleContext context) {
return javaTypeForSchemaDefType(type, parentNode, restrictions, this.schemaContext, this
.genTypeDefsContextMap, context);
}
return null;
}
- public Map<String, Map<Date, Map<String, Type>>> getGenTypeDefsContextMap() {
+ public Map<String, Map<Optional<Revision>, Map<String, Type>>> getGenTypeDefsContextMap() {
return this.genTypeDefsContextMap;
}
* returned types (generated types).
*
*/
- private void resolveTypeDefsFromContext(final SchemaContext schemaContext, final Map<String, Map<Date, Map<String,
- Type>>> genTypeDefsContextMap, final Map<Module, Set<Type>> additionalTypes) {
+ private void resolveTypeDefsFromContext(final SchemaContext schemaContext,
+ final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap,
+ final Map<Module, Set<Type>> additionalTypes) {
final Set<Module> modules = schemaContext.getModules();
Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
for (final Module module : modulesSortedByDependency) {
- Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
+ Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
if (dateTypeMap == null) {
dateTypeMap = new HashMap<>();
}
final Module module = findParentModule(this.schemaContext, parentNode);
if (module != null) {
- final Map<Date, Map<String, Type>> modulesByDate = this.genTypeDefsContextMap.get(module.getName());
+ final Map<Optional<Revision>, Map<String, Type>> modulesByDate = this.genTypeDefsContextMap.get(module.getName());
final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
if (genTOs != null) {
return genTOs.get(typeDefinition.getQName().getLocalName());
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
- final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName, ModuleContext context) {
+ final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName, final ModuleContext context) {
Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeDefName,
true, false, context);
- final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
+ final String typedefDescription = encodeAngleBrackets(typeDef.getDescription().orElse(null));
genTOBuilder.setDescription(typedefDescription);
- genTOBuilder.setReference(typeDef.getReference());
+ genTOBuilder.setReference(typeDef.getReference().orElse(null));
genTOBuilder.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
genTOBuilder.setModuleName(moduleName);
genTOBuilder.setBaseType(typeDef);
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode,
- final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap, ModuleContext context) {
+ final SchemaContext schemaContext, final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap, final ModuleContext context) {
Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
final GeneratedTOBuilderImpl unionGenTOBuilder;
unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeDefName, true, false,
context);
- final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
+ final String typedefDescription = encodeAngleBrackets(typedef.getDescription().orElse(null));
unionGenTOBuilder.setDescription(typedefDescription);
- unionGenTOBuilder.setReference(typedef.getReference());
+ unionGenTOBuilder.setReference(typedef.getReference().orElse(null));
unionGenTOBuilder.setSchemaPath((List) typedef.getPath().getPathFromRoot());
unionGenTOBuilder.setModuleName(module.getName());
private Type javaTypeForSchemaDefType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
final Restrictions r, final SchemaContext schemaContext,
- final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap, ModuleContext context) {
+ final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap, final ModuleContext context) {
Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
final String typedefName = typeDefinition.getQName().getLocalName();
Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
final String genTOName =
JavaIdentifierNormalizer.normalizeSpecificIdentifier(typedefName, JavaIdentifier.CLASS);
final String name = packageName + "." + genTOName;
- if (module.equals(module1) && !(returnType.getFullyQualifiedName().equals(name))) {
+ if (module.equals(module1) && !returnType.getFullyQualifiedName().equals(name)) {
returnType = shadedTOWithRestrictions(gto, r, context);
}
}
* <code>typedef</code> equals <code>null</code>
*/
private Type typedefToGeneratedType(final String basePackageName, final Module module,
- final TypeDefinition<?> typedef, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap,
- final Map<Module, Set<Type>> additionalTypes, final SchemaContext schemaContext, ModuleContext context) {
+ final TypeDefinition<?> typedef,
+ final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap,
+ final Map<Module, Set<Type>> additionalTypes, final SchemaContext schemaContext, final ModuleContext context) {
final String moduleName = module.getName();
- final Date moduleRevision = module.getRevision();
- if ((basePackageName != null) && (moduleName != null) && (typedef != null)) {
+ final Optional<Revision> moduleRevision = module.getRevision();
+ if (basePackageName != null && moduleName != null && typedef != null) {
final String typedefName = typedef.getQName().getLocalName();
final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
genTypeDefsContextMap, context);
genTOBuilder.setTypedef(true);
genTOBuilder.setIsUnion(true);
- addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+ addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
returnType = genTOBuilder.toInstance();
} else if (innerTypeDefinition instanceof EnumTypeDefinition) {
provideGeneratedTOBuilderForBitsTypeDefinition(
basePackageName, bitsTypeDefinition, typedefName, module.getName(), context);
genTOBuilder.setTypedef(true);
- addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+ addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
returnType = genTOBuilder.toInstance();
} else {
returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName(), context);
}
if (returnType != null) {
- final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
+ final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
if (typeMap != null) {
if (typeMap.isEmpty()) {
* @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
*/
private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final SchemaContext schemaContext,
- final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap, ModuleContext context) {
+ final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap, final ModuleContext context) {
final String typedefName = typeDefinition.getQName().getLocalName();
final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
final Module module = findParentModule(schemaContext, typeDefinition);
final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
if (module != null) {
- final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
+ final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
if (genTOs != null) {
returnType = genTOs.get(typedefName);
* @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
*/
private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
- final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap,
- ModuleContext context) {
+ final SchemaContext schemaContext, final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap,
+ final ModuleContext context) {
if (typeDefinition instanceof LeafrefTypeDefinition) {
final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode, schemaContext),
*
*/
public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
- final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap,
- ModuleContext context) {
+ final SchemaContext schemaContext, final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap,
+ final ModuleContext context) {
Type returnType = null;
Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
if (strXPath.indexOf('[') == -1) {
final Module module;
final SchemaNode actualParentSchemaNode;
- if ((parentNode instanceof DerivableSchemaNode) && ((DerivableSchemaNode) parentNode).isAddedByUses()) {
+ if (parentNode instanceof DerivableSchemaNode && ((DerivableSchemaNode) parentNode).isAddedByUses()) {
final Optional<? extends SchemaNode> originalNode = ((DerivableSchemaNode) parentNode).getOriginal();
Preconditions.checkArgument(originalNode.isPresent(), "originalNode can not be null.");
actualParentSchemaNode = originalNode.get();
* @return JAVA <code>Type</code> representation of <code>dataNode</code>
*/
private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode, final SchemaContext schemaContext,
- final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap, ModuleContext context) {
+ final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap, final ModuleContext context) {
Type returnType = null;
if (dataNode != null) {
if (dataNode instanceof LeafSchemaNode) {
private static Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref, final SchemaContext schemaContext) {
//TODO: incompatibility with Binding spec v2, get first or only one
final QName baseIdQName = idref.getIdentities().iterator().next().getQName();
- final Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
- baseIdQName.getRevision());
+ final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
IdentitySchemaNode identity = null;
for (final IdentitySchemaNode id : module.getIdentities()) {
if (id.getQName().equals(baseIdQName)) {
}
private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
- final Restrictions r, ModuleContext context) {
+ final Restrictions r, final ModuleContext context) {
final GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName(), context);
final GeneratedTransferObject parent = gto.getSuperType();
if (parent != null) {
*/
private GeneratedTOBuilder resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode,
- final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap,
- ModuleContext context) {
+ final SchemaContext schemaContext, final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap,
+ final ModuleContext context) {
final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
final GeneratedTOBuilder subUnionGenTOBUilder = provideGeneratedTOBuilderForUnionTypeDef(
*/
public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode,
- final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap,
- ModuleContext context) {
+ final SchemaContext schemaContext, final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap,
+ final ModuleContext context) {
final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
typedef, typeDefName, parentNode, schemaContext, genTypeDefsContextMap, context);
*/
private static void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
final TypeDefinition<?> unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode,
- final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+ final SchemaContext schemaContext, final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap) {
final String unionTypeName = unionSubtype.getQName().getLocalName();
final Type genTO = findGenTO(unionTypeName, unionSubtype, schemaContext, genTypeDefsContextMap);
* <code>null</code> it it doesn't exist
*/
private static Type findGenTO(final String searchedTypeName, final SchemaNode parentNode,
- final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+ final SchemaContext schemaContext, final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap) {
final Module typeModule = findParentModule(schemaContext, parentNode);
if (typeModule != null && typeModule.getName() != null) {
- final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
+ final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
if (genTOs != null) {
return genTOs.get(searchedTypeName);
*
*/
private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
- final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder, ModuleContext context) {
+ final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder, final ModuleContext context) {
Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
"Local Name in EnumTypeDefinition QName cannot be NULL!");
Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName, context);
- final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
+ final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null));
enumBuilder.setDescription(enumTypedefDescription);
enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
return enumBuilder.toInstance(enumBuilder);
} else {
leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
}
- return (leafRefValueNode != null) && leafRefValueNode.equals(parentNode);
+ return leafRefValueNode != null && leafRefValueNode.equals(parentNode);
}
***********************************************************@
@import org.opendaylight.mdsal.binding.javav2.generator.impl.util.YangTextTemplate
-@import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil
@import org.opendaylight.yangtools.yang.model.api.Module
@import org.opendaylight.yangtools.yang.model.api.DocumentedNode
@import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement
@if(module.getImports() != null && !module.getImports().isEmpty()) {
@for(moduleImport <- module.getImports()) {
@if(moduleImport != null && moduleImport.getModuleName() != "") {
- import @{moduleImport.getModuleName()} { prefix "@{moduleImport.getPrefix()}"; revision-date @{SimpleDateFormatUtil.getRevisionFormat().format(moduleImport.getRevision())}; }
+ import @{moduleImport.getModuleName()} {
+ prefix "@{moduleImport.getPrefix()}";
+ @if(moduleImport.getRevision().isPresent()) {
+ revision-date @{moduleImport.getRevision().get().toString()};
+ }
+ }
}
}
}
- @if(module.getRevision() != null) {
+ @if(module.getRevision().isPresent()) {
@for(effectiveStatement <- module.asInstanceOf[EffectiveStatement[_, _]].effectiveSubstatements()){
@if(effectiveStatement.getDeclared().isInstanceOf[RevisionStatement]){
- @if(effectiveStatement.asInstanceOf[DocumentedNode].getDescription() == null || effectiveStatement.asInstanceOf[DocumentedNode].getDescription().isEmpty()){
- revision @{SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision())};
- } else {
- revision @{SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision())} {
- description "@{effectiveStatement.asInstanceOf[DocumentedNode].getDescription()}";
+ @if(effectiveStatement.asInstanceOf[DocumentedNode].getDescription().isPresent()){
+ revision @{module.getRevision().get().toString()} {
+ description "@{effectiveStatement.asInstanceOf[DocumentedNode].getDescription().get()}";
}
+ } else {
+ revision @{module.getRevision().get().toString()};
}
}
}
@yangTemplateWriteUsesNodes(module.getUses(), module)
}
}
-}
\ No newline at end of file
+}
@(action: ActionDefinition, module: Module)
action @{action.getQName().getLocalName()} {
- @if(action.getDescription() != null && !action.getDescription().isEmpty()) {
- "@{action.getDescription()}";
+ @if(action.getDescription().isPresent()) {
+ "@{action.getDescription().get()}";
}
@if(action.getGroupings() != null && !action.getGroupings().isEmpty()) {
@yangTemplateWriteGroupingDefs(action.getGroupings(), module)
@yangTemplateWriteDataSchemaNodes(action.getOutput().getChildNodes, module)
}
}
- @if(action.getReference() != null && !action.getReference().isEmpty()) {
- reference "@{action.getReference()}";
+ @if(action.getReference().isPresent()) {
+ reference "@{action.getReference().get()}";
}
@if(action.getStatus() != Status.CURRENT) {
status @{action.getStatus()};
}
-}
\ No newline at end of file
+}
***********************************************************@
@import org.opendaylight.mdsal.binding.javav2.generator.impl.util.YangTextTemplate
-@import org.opendaylight.yangtools.yang.model.api.AugmentationSchema
+@import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode
@import org.opendaylight.yangtools.yang.model.api.Module
@import org.opendaylight.yangtools.yang.model.api.Status
-@(augments: Set[_ <: AugmentationSchema], module: Module)
+@(augments: Set[_ <: AugmentationSchemaNode], module: Module)
@for(augment <- augments) {
@if(augment != null) {
augment "@{YangTextTemplate.formatToAugmentPath(augment.getTargetPath().getPathFromRoot())}" {
@if(augment.getWhenCondition() != null && !augment.getWhenCondition().toString().isEmpty()) {
when "@augment.getWhenCondition().toString()";
}
- @if(augment.getDescription() != null && !augment.getDescription().isEmpty()) {
- description "@augment.getDescription().toString()";
+ @if(augment.getDescription().isPresent()) {
+ description "@augment.getDescription().get()";
}
- @if(augment.getReference() != null && !augment.getReference().isEmpty()) {
- reference "@augment.getReference().toString()";
+ @if(augment.getReference().isPresent()) {
+ reference "@augment.getReference().get()";
}
@if(augment.getStatus() != Status.CURRENT) {
status "@augment.getStatus()";
}
}
}
-}
\ No newline at end of file
+}
+++ /dev/null
-@*
- * Copyright (c) 2016 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
- *@
-
-@**********************************************************
-* Twirl YangTemplate for generating yang snippets. *
-* Twirl is transformed to Scala and compiled. Then, *
-* it can be called from Java with particular input *
-* parameters to render desired output code. *
-***********************************************************@
-
-@import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition
-@import org.opendaylight.yangtools.yang.model.api.Status
-
-@(constraint: ConstraintDefinition)
-@if(constraint.isMandatory()) {
- mandatory true;
-}
-@if(constraint.getMinElements() != null) {
- min-elements @(constraint.getMinElements());
-}
-@if(constraint.getMaxElements() != null) {
- max-elements @(constraint.getMaxElements());
-}
\ No newline at end of file
@import org.opendaylight.yangtools.yang.model.api.AnyDataSchemaNode
@import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode
-@import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
+@import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode
@import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode
@import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
@import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
+@import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus
+@import org.opendaylight.yangtools.yang.model.api.ElementCountConstraintAware
@import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode
@import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
@import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
+@import org.opendaylight.yangtools.yang.model.api.MandatoryAware
@import org.opendaylight.yangtools.yang.model.api.Module
@import org.opendaylight.yangtools.yang.model.api.SchemaNode
@import org.opendaylight.yangtools.yang.model.api.Status
@(dataSchemaNode: DataSchemaNode, module: Module)
@if(dataSchemaNode.isInstanceOf[ContainerSchemaNode]) {
- @writeContSchemaNode(dataSchemaNode.asInstanceOf[ContainerSchemaNode], module)
+ @container(dataSchemaNode.asInstanceOf[ContainerSchemaNode], module)
}
@if(dataSchemaNode.isInstanceOf[AnyXmlSchemaNode]) {
- anyxml @{dataSchemaNode.asInstanceOf[AnyXmlSchemaNode].getQName().getLocalName()}@if(dataSchemaNode.asInstanceOf[AnyXmlSchemaNode].getStatus() == Status.CURRENT && !dataSchemaNode.asInstanceOf[AnyXmlSchemaNode].getConstraints().isMandatory()){;} else { {
- @if(dataSchemaNode.asInstanceOf[AnyXmlSchemaNode].getConstraints().isMandatory()){
- mandatory true;
- }
- @if(dataSchemaNode.asInstanceOf[AnyXmlSchemaNode].getStatus() != Status.CURRENT) {
- status @{dataSchemaNode.asInstanceOf[AnyXmlSchemaNode].getStatus()};
- }
+ anyxml @{dataSchemaNode.asInstanceOf[AnyXmlSchemaNode].getQName().getLocalName()}@if(dataSchemaNode.asInstanceOf[AnyXmlSchemaNode].getStatus() == Status.CURRENT && !dataSchemaNode.asInstanceOf[AnyXmlSchemaNode].isMandatory()){;} else { {
+ @mandatory(dataSchemaNode.asInstanceOf[AnyXmlSchemaNode])
+ @status(dataSchemaNode)
}}
}
@if(dataSchemaNode.isInstanceOf[AnyDataSchemaNode]) {
- anydata @{dataSchemaNode.asInstanceOf[AnyDataSchemaNode].getQName().getLocalName()}@if(dataSchemaNode.asInstanceOf[AnyDataSchemaNode].getStatus() == Status.CURRENT && !dataSchemaNode.asInstanceOf[AnyDataSchemaNode].getConstraints().isMandatory()){;} else { {
- @if(dataSchemaNode.asInstanceOf[AnyDataSchemaNode].getConstraints().isMandatory()){
- mandatory true;
- }
- @if(dataSchemaNode.asInstanceOf[AnyDataSchemaNode].getStatus() != Status.CURRENT) {
- status @{dataSchemaNode.asInstanceOf[AnyDataSchemaNode].getStatus()};
- }
+ anydata @{dataSchemaNode.asInstanceOf[AnyDataSchemaNode].getQName().getLocalName()}@if(dataSchemaNode.asInstanceOf[AnyDataSchemaNode].getStatus() == Status.CURRENT && !dataSchemaNode.asInstanceOf[AnyDataSchemaNode].isMandatory()){;} else { {
+ @mandatory(dataSchemaNode.asInstanceOf[AnyDataSchemaNode])
+ @status(dataSchemaNode)
}}
}
@if(dataSchemaNode.isInstanceOf[LeafSchemaNode]) {
description "@{dataSchemaNode.asInstanceOf[LeafSchemaNode].getDescription()}";
}
@yangTemplateWriteType(dataSchemaNode.asInstanceOf[LeafSchemaNode].getType())
- @if(dataSchemaNode.asInstanceOf[LeafSchemaNode].getConstraints() != null){
- @yangTemplateWriteConstraints(dataSchemaNode.asInstanceOf[LeafSchemaNode].getConstraints())
- }
- @if(dataSchemaNode.asInstanceOf[LeafSchemaNode].getStatus() != Status.CURRENT) {
- status @{dataSchemaNode.asInstanceOf[LeafSchemaNode].getStatus()};
- }
+ @mandatory(dataSchemaNode.asInstanceOf[LeafSchemaNode])
+ @status(dataSchemaNode)
}
}
}
ordered-by user;
}
type @{dataSchemaNode.asInstanceOf[LeafListSchemaNode].getType().getQName().getLocalName()};
- @if(dataSchemaNode.asInstanceOf[LeafListSchemaNode].getConstraints() != null){
- @yangTemplateWriteConstraints(dataSchemaNode.asInstanceOf[LeafListSchemaNode].getConstraints())
- }
- @if(dataSchemaNode.asInstanceOf[LeafListSchemaNode].getStatus() != Status.CURRENT) {
- status @{dataSchemaNode.asInstanceOf[LeafListSchemaNode].getStatus()};
- }
+ @minmaxelements(dataSchemaNode.asInstanceOf[LeafListSchemaNode])
+ @status(dataSchemaNode)
}
}
-@if(dataSchemaNode.isInstanceOf[ChoiceCaseNode]) {
- case @{dataSchemaNode.asInstanceOf[ChoiceCaseNode].getQName().getLocalName()} {
- @for(childNode <- dataSchemaNode.asInstanceOf[ChoiceCaseNode].getChildNodes()) {
+@if(dataSchemaNode.isInstanceOf[CaseSchemaNode]) {
+ case @{dataSchemaNode.asInstanceOf[CaseSchemaNode].getQName().getLocalName()} {
+ @for(childNode <- dataSchemaNode.asInstanceOf[CaseSchemaNode].getChildNodes()) {
@yangTemplateWriteDataSchemaNode(childNode, module)
}
- @if(dataSchemaNode.asInstanceOf[ChoiceCaseNode].getStatus() != Status.CURRENT) {
- status @{dataSchemaNode.asInstanceOf[ChoiceCaseNode].getStatus()};
- }
+ @status(dataSchemaNode)
}
}
@if(dataSchemaNode.isInstanceOf[ChoiceSchemaNode]) {
choice @{dataSchemaNode.asInstanceOf[ChoiceSchemaNode].getQName().getLocalName()} {
- @if(dataSchemaNode.asInstanceOf[ChoiceSchemaNode].getConstraints() != null){
- @yangTemplateWriteConstraints(dataSchemaNode.asInstanceOf[ChoiceSchemaNode].getConstraints())
- }
- @for(childNode <- dataSchemaNode.asInstanceOf[ChoiceSchemaNode].getCases()) {
+ @mandatory(dataSchemaNode.asInstanceOf[ChoiceSchemaNode])
+ @for(childNode <- dataSchemaNode.asInstanceOf[ChoiceSchemaNode].getCases().values()) {
@yangTemplateWriteDataSchemaNode(childNode, module)
}
- @if(dataSchemaNode.asInstanceOf[ChoiceSchemaNode].getStatus() != Status.CURRENT) {
- status @{dataSchemaNode.asInstanceOf[ChoiceSchemaNode].getStatus()};
- }
+ @status(dataSchemaNode)
}
}
@if(dataSchemaNode.isInstanceOf[ListSchemaNode]) {
- @writeListSchemaNode(dataSchemaNode.asInstanceOf[ListSchemaNode], module)
+ @list(dataSchemaNode.asInstanceOf[ListSchemaNode], module)
}
-@writeContSchemaNode(container: ContainerSchemaNode, module: Module) = {
+@mandatory(aware: MandatoryAware) = {
+ @if(aware.isMandatory()) {
+ mandatory true;
+ }
+}
+
+@minmaxelements(aware: ElementCountConstraintAware) = {
+ @if(aware.getElementCountConstraint().isPresent()) {
+ @defining(aware.getElementCountConstraint().get()) { constraint =>
+ @if(constraint.getMinElements() != null) {
+ min-elements @{constraint.getMinElements()}
+ }
+ @if(constraint.getMaxElements() != null) {
+ max-elements @{constraint.getMaxElements()}
+ }
+ }
+ }
+}
+
+@status(aware: WithStatus) = {
+ @if(aware.getStatus() != Status.CURRENT) {
+ status @{aware.getStatus()};
+ }
+}
+@container(container: ContainerSchemaNode, module: Module) = {
container @{container.getQName().getLocalName()} {
@if(container.getChildNodes() != null && !container.getChildNodes().isEmpty()) {
@yangTemplateWriteDataSchemaNodes(container.getChildNodes(), module)
@if(container.getActions() != null && !container.getActions().isEmpty()) {
@yangTemplateWriteActions(container.getActions(), module)
}
- @if(container.getStatus() != Status.CURRENT) {
- status @{container.getStatus()};
- }
+ @status(container)
}
}
-@writeListSchemaNode(list: ListSchemaNode, module: Module) = {
+@list(list: ListSchemaNode, module: Module) = {
list @{list.getQName().getLocalName()} {
@if(list.isUserOrdered()){
ordered-by user;
}
- @if(dataSchemaNode.asInstanceOf[ListSchemaNode].getConstraints() != null){
- @yangTemplateWriteConstraints(dataSchemaNode.asInstanceOf[ListSchemaNode].getConstraints())
- }
+ @minmaxelements(list)
key "@for(listKey <- list.getKeyDefinition()) {@{listKey.getLocalName()} }";
@if(!list.getUniqueConstraints().isEmpty()){
@for(listUnique <- list.getUniqueConstraints()){
@if(list.getActions() != null && !list.getActions().isEmpty()) {
@yangTemplateWriteActions(list.getActions(), module)
}
- @if(list.getStatus() != Status.CURRENT) {
- status @{list.getStatus()};
- }
+ @status(list)
}
-}
\ No newline at end of file
+}
@import org.opendaylight.yangtools.yang.model.api.Deviation
@import org.opendaylight.yangtools.yang.model.api.Status
-@import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.DeviationEffectiveStatementImpl
+@import org.opendaylight.yangtools.yang.model.api.stmt.DeviationEffectiveStatement
@(deviation: Deviation)
-deviation @{deviation.asInstanceOf[DeviationEffectiveStatementImpl].getDeclared().rawArgument()} {
- @if(deviation.getReference() != null && !deviation.getReference().isEmpty()) {
- reference "@{deviation.getReference()}";
+deviation @{deviation.asInstanceOf[DeviationEffectiveStatement].getDeclared().rawArgument()} {
+ @if(deviation.getReference().isPresent()) {
+ reference "@{deviation.getReference().get()}";
}
- @if(deviation.getDescription() != null && !deviation.getDescription().isEmpty()) {
- description "@{deviation.getDescription()}";
+ @if(deviation.getDescription().isPresent()) {
+ description "@{deviation.getDescription().get()}";
}
@for(deviate <- deviation.getDeviates()) {
@if(deviate != null && deviate.getDeviateType() != null ) {
}
}
}
-}
\ No newline at end of file
+}
@(extension: ExtensionDefinition)
extension @{extension.getQName().getLocalName()}@if(extension.getArgument() == null || extension.getArgument().isEmpty()){;} else { {
- @if(extension.getDescription() != null && !extension.getDescription().isEmpty()) {
- description "@{extension.getDescription()}";
+ @if(extension.getDescription().isPresent()) {
+ description "@{extension.getDescription().get()}";
}
@if(extension.getArgument() != null && !extension.getArgument().isEmpty()) {
argument @{extension.getArgument()};
}
- @if(extension.getReference() != null && !extension.getReference().isEmpty()) {
- reference "@{extension.getReference()}";
+ @if(extension.getReference().isPresent()) {
+ reference "@{extension.getReference().get()}";
}
@if(extension.getStatus() != Status.CURRENT) {
status @{extension.getStatus()};
}}
-}
\ No newline at end of file
+}
@(feature: FeatureDefinition)
feature @{feature.getQName().getLocalName()} {
- @if(feature.getDescription() != null && !feature.getDescription().isEmpty()) {
- description "@{feature.getDescription()}";
+ @if(feature.getDescription().isPresent()) {
+ description "@{feature.getDescription().get()}";
}
- @if(feature.getReference() != null && !feature.getReference().isEmpty()) {
- reference "@{feature.getReference()}";
+ @if(feature.getReference().isPresent()) {
+ reference "@{feature.getReference().get()}";
}
@if(feature.getStatus() != Status.CURRENT) {
status @{feature.getStatus()};
}
-}
\ No newline at end of file
+}
@(identity: IdentitySchemaNode)
identity @{identity.getQName().getLocalName()} {
- @if(identity.getBaseIdentity() != null) {
- base "(@writeIdentityNs(identity.getBaseIdentity()))@{identity.getBaseIdentity()}";
+ @for(baseIdentity <- identity.getBaseIdentities()) {
+ base "(@writeIdentityNs(baseIdentity))@{baseIdentity}";
}
- @if(identity.getDescription() != null && !identity.getDescription().isEmpty()) {
- description "@{identity.getDescription()}";
+ @if(identity.getDescription().isPresent()) {
+ description "@{identity.getDescription().get()}";
}
- @if(identity.getReference() != null && !identity.getReference().isEmpty()) {
- reference "@{identity.getReference()}";
+ @if(identity.getReference().isPresent()) {
+ reference "@{identity.getReference().get()}";
}
@if(identity.getStatus() != Status.CURRENT) {
status @{identity.getStatus()};
@if(identity.getQName().getNamespace() != null) {
@{identity.getQName().getNamespace()}:
}
-}
\ No newline at end of file
+}
@(notification: NotificationDefinition, module: Module)
notification @{notification.getQName().getLocalName()} {
- @if(notification.getDescription() != null && !notification.getDescription().isEmpty()) {
- description "@{notification.getDescription()}";
+ @if(notification.getDescription().isPresent()) {
+ description "@{notification.getDescription().get()}";
}
@if(notification.getChildNodes() != null && !notification.getChildNodes().isEmpty()) {
@yangTemplateWriteDataSchemaNodes(notification.getChildNodes(), module)
@if(notification.getUses() != null && !notification.getUses().isEmpty()) {
@yangTemplateWriteUsesNodes(notification.getUses(), module)
}
- @if(notification.getReference() != null && !notification.getReference().isEmpty()) {
- reference "@{notification.getReference()}";
+ @if(notification.getReference().isPresent()) {
+ reference "@{notification.getReference().get()}";
}
@if(notification.getStatus() != Status.CURRENT) {
status @{notification.getStatus()};
}
-}
\ No newline at end of file
+}
@(rpc: RpcDefinition, module: Module)
rpc @{rpc.getQName().getLocalName()} {
- @if(rpc.getDescription() != null && !rpc.getDescription().isEmpty()) {
- "@{rpc.getDescription()}";
+ @if(rpc.getDescription().isPresent()) {
+ "@{rpc.getDescription().get()}";
}
@if(rpc.getGroupings() != null && !rpc.getGroupings().isEmpty()) {
@yangTemplateWriteGroupingDefs(rpc.getGroupings(), module)
@yangTemplateWriteDataSchemaNodes(rpc.getOutput().getChildNodes, module)
}
}
- @if(rpc.getReference() != null && !rpc.getReference().isEmpty()) {
- reference "@{rpc.getReference()}";
+ @if(rpc.getReference().isPresent()) {
+ reference "@{rpc.getReference().get()}";
}
@if(rpc.getStatus() != Status.CURRENT) {
status @{rpc.getStatus()};
}
-}
\ No newline at end of file
+}
@import org.opendaylight.yangtools.yang.model.api.`type`.IdentityrefTypeDefinition
@import org.opendaylight.yangtools.yang.model.api.`type`.IdentityTypeDefinition
@import org.opendaylight.yangtools.yang.model.api.`type`.InstanceIdentifierTypeDefinition
-@import org.opendaylight.yangtools.yang.model.api.`type`.IntegerTypeDefinition
+@import org.opendaylight.yangtools.yang.model.api.`type`.Int8TypeDefinition
+@import org.opendaylight.yangtools.yang.model.api.`type`.Int16TypeDefinition
+@import org.opendaylight.yangtools.yang.model.api.`type`.Int32TypeDefinition
+@import org.opendaylight.yangtools.yang.model.api.`type`.Int64TypeDefinition
@import org.opendaylight.yangtools.yang.model.api.`type`.LeafrefTypeDefinition
@import org.opendaylight.yangtools.yang.model.api.`type`.StringTypeDefinition
+@import org.opendaylight.yangtools.yang.model.api.`type`.Uint8TypeDefinition
+@import org.opendaylight.yangtools.yang.model.api.`type`.Uint16TypeDefinition
+@import org.opendaylight.yangtools.yang.model.api.`type`.Uint32TypeDefinition
+@import org.opendaylight.yangtools.yang.model.api.`type`.Uint64TypeDefinition
@import org.opendaylight.yangtools.yang.model.api.`type`.UnionTypeDefinition
@import org.opendaylight.yangtools.yang.model.api.`type`.UnknownTypeDefinition
-@import org.opendaylight.yangtools.yang.model.api.`type`.UnsignedIntegerTypeDefinition
@(typeDefinition: TypeDefinition[_])
@if(typeDefinition.getBaseType() != null) {
@if(typeDefinition.isInstanceOf[InstanceIdentifierTypeDefinition]){
type @(typeDefinition.asInstanceOf[InstanceIdentifierTypeDefinition].getBaseType().getQName().getLocalName());
}
- @if(typeDefinition.isInstanceOf[IntegerTypeDefinition]){
- type @(typeDefinition.asInstanceOf[IntegerTypeDefinition].getBaseType().getQName().getLocalName());
+ @if(typeDefinition.isInstanceOf[Int8TypeDefinition]){
+ type @(typeDefinition.asInstanceOf[Int8TypeDefinition].getBaseType().getQName().getLocalName());
+ }
+ @if(typeDefinition.isInstanceOf[Int16TypeDefinition]){
+ type @(typeDefinition.asInstanceOf[Int16TypeDefinition].getBaseType().getQName().getLocalName());
+ }
+ @if(typeDefinition.isInstanceOf[Int32TypeDefinition]){
+ type @(typeDefinition.asInstanceOf[Int32TypeDefinition].getBaseType().getQName().getLocalName());
+ }
+ @if(typeDefinition.isInstanceOf[Int64TypeDefinition]){
+ type @(typeDefinition.asInstanceOf[Int64TypeDefinition].getBaseType().getQName().getLocalName());
}
@if(typeDefinition.isInstanceOf[LeafrefTypeDefinition]){
type @(typeDefinition.asInstanceOf[LeafrefTypeDefinition].getBaseType().getQName().getLocalName());
@if(typeDefinition.isInstanceOf[UnknownTypeDefinition]){
type @(typeDefinition.asInstanceOf[UnknownTypeDefinition].getBaseType().getQName().getLocalName());
}
- @if(typeDefinition.isInstanceOf[UnsignedIntegerTypeDefinition]){
- type @(typeDefinition.asInstanceOf[UnsignedIntegerTypeDefinition].getBaseType().getQName().getLocalName());
+ @if(typeDefinition.isInstanceOf[Uint8TypeDefinition]){
+ type @(typeDefinition.asInstanceOf[Uint8TypeDefinition].getBaseType().getQName().getLocalName());
+ }
+ @if(typeDefinition.isInstanceOf[Uint16TypeDefinition]){
+ type @(typeDefinition.asInstanceOf[Uint16TypeDefinition].getBaseType().getQName().getLocalName());
+ }
+ @if(typeDefinition.isInstanceOf[Uint32TypeDefinition]){
+ type @(typeDefinition.asInstanceOf[Uint32TypeDefinition].getBaseType().getQName().getLocalName());
+ }
+ @if(typeDefinition.isInstanceOf[Uint64TypeDefinition]){
+ type @(typeDefinition.asInstanceOf[Uint64TypeDefinition].getBaseType().getQName().getLocalName());
}
} else {
type @(typeDefinition.getQName().getLocalName());
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import org.junit.Test;
import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext;
import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
public class AugmentToGenTypeTest {
- @SuppressWarnings("unchecked")
@Test(expected = UnsupportedOperationException.class)
public void constructorTest() throws Throwable {
- final Constructor<AugmentToGenType> constructor =
- (Constructor<AugmentToGenType>) AugmentToGenType.class.getDeclaredConstructors()[0];
+ final Constructor<AugmentToGenType> constructor = AugmentToGenType.class.getDeclaredConstructor();
constructor.setAccessible(true);
final Object[] objs = {};
try {
}
}
- @SuppressWarnings("rawtypes")
@Test
- public void generateNullModuleTest() throws Exception {
- final Class[] parameterTypes =
- { Module.class, SchemaContext.class, TypeProvider.class, Map.class, Map.class, boolean.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("generate", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void generateNullModuleTest() {
final SchemaContext context = null;
final TypeProvider typeProvider = null;
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
final Module m = null;
- final Object[] args = { m, context, typeProvider, genCtx, genTypeBuilders, false };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.generate(m, context, typeProvider, genCtx, genTypeBuilders, false);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalArgumentException);
- assertEquals("Module reference cannot be NULL.", cause.getMessage());
+ } catch (final IllegalArgumentException e) {
+ assertEquals("Module reference cannot be NULL.", e.getMessage());
}
}
- @SuppressWarnings("rawtypes")
@Test
- public void generateNullModuleNameTest() throws Exception {
- final Class[] parameterTypes =
- { Module.class, SchemaContext.class, TypeProvider.class, Map.class, Map.class, boolean.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("generate", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void generateNullModuleNameTest() {
final SchemaContext context = null;
final TypeProvider typeProvider = null;
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final Module m = mock(Module.class);
when(m.getName()).thenReturn(null);
- final Object[] args = { m, context, typeProvider, genCtx, genTypeBuilders, false };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.generate(m, context, typeProvider, genCtx, genTypeBuilders, false);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalArgumentException);
- assertEquals("Module name cannot be NULL.", cause.getMessage());
+ } catch (final IllegalArgumentException e) {
+ assertEquals("Module name cannot be NULL.", e.getMessage());
}
}
- @SuppressWarnings("rawtypes")
@Test
- public void generateNullModuleAugmentationsTest() throws Exception {
- final Class[] parameterTypes =
- { Module.class, SchemaContext.class, TypeProvider.class, Map.class, Map.class, boolean.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("generate", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void generateNullModuleAugmentationsTest() {
final SchemaContext context = null;
final TypeProvider typeProvider = null;
final Map<Module, ModuleContext> genCtx = new HashMap<>();
when(m.getName()).thenReturn("name");
when(m.getAugmentations()).thenReturn(null);
- final Object[] args = { m, context, typeProvider, genCtx, genTypeBuilders, false };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.generate(m, context, typeProvider, genCtx, genTypeBuilders, false);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalStateException);
- assertEquals("Augmentations Set cannot be NULL.", cause.getMessage());
+ } catch (final IllegalStateException e) {
+ assertEquals("Augmentations Set cannot be NULL.", e.getMessage());
}
}
- @SuppressWarnings("rawtypes")
@Test
- public void generateWithoutAugmentationsTest() throws Exception {
- final Class[] parameterTypes =
- { Module.class, SchemaContext.class, TypeProvider.class, Map.class, Map.class, boolean.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("generate", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final SchemaContext context = YangParserTestUtils.parseYangSource("/generator/test.yang");
+ public void generateWithoutAugmentationsTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/generator/test.yang");
final TypeProvider typeProvider = new TypeProviderImpl(context);
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
-
- final Object[] args =
- { context.getModules().iterator().next(), context, typeProvider, genCtx, genTypeBuilders, false };
- final Map invoke = (Map) generate.invoke(AugmentToGenType.class, args);
+ final Map<Module, ModuleContext> invoke = AugmentToGenType.generate(context.getModules().iterator().next(),
+ context, typeProvider, genCtx, genTypeBuilders, false);
assertNotNull(invoke);
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void generateWithAugmentationsTest() throws Exception {
- final Class[] parameterTypes =
- { Module.class, SchemaContext.class, TypeProvider.class, Map.class, Map.class, boolean.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("generate", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final SchemaContext context = YangParserTestUtils.parseYangSource("/generator/test-augment.yang");
+ public void generateWithAugmentationsTest() {
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/generator/test-augment.yang");
final TypeProvider typeProvider = new TypeProviderImpl(context);
final Map<Module, ModuleContext> genCtx = mock(Map.class);
final Collection<ModuleContext> moduleContexts = new ArrayList<>();
when(genCtx.get(context.getModules().iterator().next())).thenReturn(moduleContext);
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
- final Object[] args =
- { context.getModules().iterator().next(), context, typeProvider, genCtx, genTypeBuilders, false };
- final Map invoke = (Map) generate.invoke(AugmentToGenType.class, args);
+ final Map<Module, ModuleContext> invoke = AugmentToGenType.generate(context.getModules().iterator().next(),
+ context, typeProvider, genCtx, genTypeBuilders, false);
assertNotNull(invoke);
}
- @SuppressWarnings("rawtypes")
@Test
- public void resolveAugmentationsNullModuleTest() throws Exception {
- final Class[] parameterTypes = { Module.class, SchemaContext.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("resolveAugmentations", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final Module m = null;
- final SchemaContext schemaContext = null;
-
- final Object[] args = { m, schemaContext };
+ public void resolveAugmentationsNullModuleTest() {
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.resolveAugmentations(null, null);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalArgumentException);
- assertEquals("Module reference cannot be NULL.", cause.getMessage());
+ } catch (final IllegalArgumentException e) {
+ assertEquals("Module reference cannot be NULL.", e.getMessage());
}
}
- @SuppressWarnings("rawtypes")
@Test
- public void resolveAugmentationsNullAugmentationsTest() throws Exception {
- final Class[] parameterTypes = { Module.class, SchemaContext.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("resolveAugmentations", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void resolveAugmentationsNullAugmentationsTest() {
final Module m = mock(Module.class);
when(m.getAugmentations()).thenReturn(null);
final SchemaContext schemaContext = mock(SchemaContext.class);
- final Object[] args = { m, schemaContext };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.resolveAugmentations(m, schemaContext);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalStateException);
- assertEquals("Augmentations Set cannot be NULL.", cause.getMessage());
+ } catch (final IllegalStateException e) {
+ assertEquals("Augmentations Set cannot be NULL.", e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void resolveAugmentationsTest() throws Exception {
- final Class[] parameterTypes = { Module.class, SchemaContext.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("resolveAugmentations", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void resolveAugmentationsTest() {
final Module m = mock(Module.class);
final Module m2 = mock(Module.class);
final SchemaContext schemaContext = mock(SchemaContext.class);
- final Set<AugmentationSchema> augmentations = new HashSet<>();
+ final Set<AugmentationSchemaNode> augmentations = new HashSet<>();
final QName q1 = QName.create("q1", "2017-04-04", "q1");
final QName q2 = QName.create("q2", "2017-04-04", "q2");
final QName q4 = QName.create("q4", "2017-04-04", "q4");
final QName q5 = QName.create("q5", "2017-04-04", "q5");
- final AugmentationSchema augmentationSchema1 = mock(AugmentationSchema.class);
- when(augmentationSchema1.getTargetPath()).thenReturn(SchemaPath.create(true, q1, q2));
- final AugmentationSchema augmentationSchema2 = mock(AugmentationSchema.class);
- when(augmentationSchema2.getTargetPath()).thenReturn(SchemaPath.create(true, q3, q4, q5));
- augmentations.add(augmentationSchema1);
- augmentations.add(augmentationSchema2);
+ final AugmentationSchemaNode AugmentationSchemaNode1 = mock(AugmentationSchemaNode.class);
+ when(AugmentationSchemaNode1.getTargetPath()).thenReturn(SchemaPath.create(true, q1, q2));
+ final AugmentationSchemaNode AugmentationSchemaNode2 = mock(AugmentationSchemaNode.class);
+ when(AugmentationSchemaNode2.getTargetPath()).thenReturn(SchemaPath.create(true, q3, q4, q5));
+ augmentations.add(AugmentationSchemaNode1);
+ augmentations.add(AugmentationSchemaNode2);
when(m.getAugmentations()).thenReturn(augmentations);
- when(schemaContext.findModuleByNamespaceAndRevision(q1.getNamespace(), q1.getRevision())).thenReturn(m2);
- when(schemaContext.findModuleByNamespaceAndRevision(q3.getNamespace(), q3.getRevision())).thenReturn(m2);
+ when(schemaContext.findModule(q1.getModule())).thenReturn(Optional.of(m2));
+ when(schemaContext.findModule(q3.getModule())).thenReturn(Optional.of(m2));
- final Object[] args = { m, schemaContext };
-
- final List<AugmentationSchema> result =
- (List<AugmentationSchema>) generate.invoke(AugmentToGenType.class, args);
+ final List<AugmentationSchemaNode> result = AugmentToGenType.resolveAugmentations(m, schemaContext);
assertNotNull(result);
assertTrue(!result.isEmpty());
- assertEquals(result.get(0), augmentationSchema1);
- assertEquals(result.get(1), augmentationSchema2);
+ assertEquals(result.get(0), AugmentationSchemaNode1);
+ assertEquals(result.get(1), AugmentationSchemaNode2);
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void augmentationToGenTypesNullPckgNameTest() throws Exception {
- final Class[] parameterTypes = { String.class, Map.Entry.class, Module.class, SchemaContext.class,
- boolean.class, Map.class, Map.class, TypeProvider.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("augmentationToGenTypes", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void augmentationToGenTypesNullPckgNameTest() {
final String augmPackName = null;
- final Map.Entry<SchemaPath, List<AugmentationSchema>> schemaPathAugmentListEntry = null;
+ final Map.Entry<SchemaPath, List<AugmentationSchemaNode>> schemaPathAugmentListEntry = null;
final SchemaContext context = null;
final TypeProvider typeProvider = null;
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
final Module m = null;
- final Object[] args = { augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, genTypeBuilders, typeProvider };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx,
+ genTypeBuilders, typeProvider);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalArgumentException);
- assertEquals("Package Name cannot be NULL.", cause.getMessage());
+ } catch (final IllegalArgumentException e) {
+ assertEquals("Package Name cannot be NULL.", e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void augmentationToGenTypesNullAugSchemaTest() throws Exception {
- final Class[] parameterTypes = { String.class, Map.Entry.class, Module.class, SchemaContext.class,
- boolean.class, Map.class, Map.class, TypeProvider.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("augmentationToGenTypes", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void augmentationToGenTypesNullAugSchemaTest() {
final String augmPackName = "pckg.name";
- final Map.Entry<SchemaPath, List<AugmentationSchema>> schemaPathAugmentListEntry = null;
+ final Map.Entry<SchemaPath, List<AugmentationSchemaNode>> schemaPathAugmentListEntry = null;
final SchemaContext context = null;
final TypeProvider typeProvider = null;
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
final Module m = null;
- final Object[] args = { augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, genTypeBuilders, typeProvider };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx,
+ genTypeBuilders, typeProvider);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalArgumentException);
- assertEquals("Augmentation List Entry cannot be NULL.", cause.getMessage());
+ } catch (final IllegalArgumentException e) {
+ assertEquals("Augmentation List Entry cannot be NULL.", e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void augmentationToGenTypesNullAugSchemaTargetPathTest() throws Exception {
- final Class[] parameterTypes = { String.class, Map.Entry.class, Module.class, SchemaContext.class,
- boolean.class, Map.class, Map.class, TypeProvider.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("augmentationToGenTypes", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void augmentationToGenTypesNullAugSchemaTargetPathTest() {
final String augmPackName = "pckg.name";
- final AugmentationSchema augmSchema = mock(AugmentationSchema.class);
+ final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class);
when(augmSchema.getTargetPath()).thenReturn(null);
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
- final Map.Entry<SchemaPath, List<AugmentationSchema>> schemaPathAugmentListEntry = mock(Map.Entry.class);
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
+ final Map.Entry<SchemaPath, List<AugmentationSchemaNode>> schemaPathAugmentListEntry = mock(Map.Entry.class);
when(schemaPathAugmentListEntry.getKey()).thenReturn(null);
- when(schemaPathAugmentListEntry.getValue()).thenReturn(augmentationSchemaList);
+ when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList);
final SchemaContext context = null;
final TypeProvider typeProvider = null;
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
final Module m = null;
- final Object[] args = { augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, genTypeBuilders, typeProvider };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx,
+ genTypeBuilders, typeProvider);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalStateException);
- assertEquals("Augmentation List Entry does not contain Target Path (Target Path is NULL).", cause.getMessage());
+ } catch (final IllegalStateException e) {
+ assertEquals("Augmentation List Entry does not contain Target Path (Target Path is NULL).", e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void augmentationToGenTypesNullAugSchemaListTest() throws Exception {
- final Class[] parameterTypes = { String.class, Map.Entry.class, Module.class, SchemaContext.class,
- boolean.class, Map.class, Map.class, TypeProvider.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("augmentationToGenTypes", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void augmentationToGenTypesNullAugSchemaListTest() {
final String augmPackName = "pckg.name";
- final AugmentationSchema augmSchema = mock(AugmentationSchema.class);
+ final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class);
final QName qnamePath = QName.create("test", "2017-04-04", "aug");
final SchemaPath path = SchemaPath.create(true, qnamePath);
when(augmSchema.getTargetPath()).thenReturn(path);
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
- final Map.Entry<SchemaPath, List<AugmentationSchema>> schemaPathAugmentListEntry = mock(Map.Entry.class);
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
+ final Map.Entry<SchemaPath, List<AugmentationSchemaNode>> schemaPathAugmentListEntry = mock(Map.Entry.class);
when(schemaPathAugmentListEntry.getKey()).thenReturn(path);
- when(schemaPathAugmentListEntry.getValue()).thenReturn(augmentationSchemaList);
+ when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList);
final SchemaContext context = null;
final TypeProvider typeProvider = null;
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
final Module m = null;
- final Object[] args = { augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, genTypeBuilders, typeProvider };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx,
+ genTypeBuilders, typeProvider);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalStateException);
- assertEquals("Augmentation List cannot be empty.", cause.getMessage());
+ } catch (final IllegalStateException e) {
+ assertEquals("Augmentation List cannot be empty.", e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void augmentationToGenTypesNullAugSchemaTargetNodeTest() throws Exception {
- final Class[] parameterTypes = { String.class, Map.Entry.class, Module.class, SchemaContext.class,
- boolean.class, Map.class, Map.class, TypeProvider.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("augmentationToGenTypes", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void augmentationToGenTypesNullAugSchemaTargetNodeTest() {
final String augmPackName = "pckg.name";
- final AugmentationSchema augmSchema = mock(AugmentationSchema.class);
+ final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class);
final QName qnamePath = QName.create("test", "2017-04-04", "aug");
final SchemaPath path = SchemaPath.create(true, qnamePath);
when(augmSchema.getTargetPath()).thenReturn(path);
final Set<UsesNode> uses = new HashSet<>();
when(augmSchema.getUses()).thenReturn(uses);
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
- augmentationSchemaList.add(augmSchema);
- final Map.Entry<SchemaPath, List<AugmentationSchema>> schemaPathAugmentListEntry = mock(Map.Entry.class);
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
+ AugmentationSchemaNodeList.add(augmSchema);
+ final Map.Entry<SchemaPath, List<AugmentationSchemaNode>> schemaPathAugmentListEntry = mock(Map.Entry.class);
when(schemaPathAugmentListEntry.getKey()).thenReturn(path);
- when(schemaPathAugmentListEntry.getValue()).thenReturn(augmentationSchemaList);
+ when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList);
final SchemaContext context = mock(SchemaContext.class);
final Module moduleAug = mock(Module.class);
final DataSchemaNode schNode = null;
when(moduleAug.getDataChildByName(qnamePath)).thenReturn(schNode);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(moduleAug);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug));
final TypeProvider typeProvider = null;
final Map<Module, ModuleContext> genCtx = new HashMap<>();
when(m.getNamespace()).thenReturn(qnamePath.getNamespace());
when(m.getRevision()).thenReturn(qnamePath.getRevision());
- final Object[] args = { augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, genTypeBuilders, typeProvider };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx,
+ genTypeBuilders, typeProvider);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalArgumentException);
- assertEquals("augment target not found: " + path, cause.getMessage());
+ } catch (final IllegalArgumentException e) {
+ assertEquals("augment target not found: " + path, e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void augmentationToGenTypesNullAugTargetGTBTest() throws Exception {
- final Class[] parameterTypes = { String.class, Map.Entry.class, Module.class, SchemaContext.class,
- boolean.class, Map.class, Map.class, TypeProvider.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("augmentationToGenTypes", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void augmentationToGenTypesNullAugTargetGTBTest() {
final String augmPackName = "pckg.name";
- final AugmentationSchema augmSchema = mock(AugmentationSchema.class);
+ final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class);
final QName qnamePath = QName.create("test", "2017-04-04", "aug");
final SchemaPath path = SchemaPath.create(true, qnamePath);
when(augmSchema.getTargetPath()).thenReturn(path);
final Set<UsesNode> uses = new HashSet<>();
when(augmSchema.getUses()).thenReturn(uses);
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
- augmentationSchemaList.add(augmSchema);
- final Map.Entry<SchemaPath, List<AugmentationSchema>> schemaPathAugmentListEntry = mock(Map.Entry.class);
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
+ AugmentationSchemaNodeList.add(augmSchema);
+ final Map.Entry<SchemaPath, List<AugmentationSchemaNode>> schemaPathAugmentListEntry = mock(Map.Entry.class);
when(schemaPathAugmentListEntry.getKey()).thenReturn(path);
- when(schemaPathAugmentListEntry.getValue()).thenReturn(augmentationSchemaList);
+ when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList);
final SchemaContext context = mock(SchemaContext.class);
final Module moduleAug = mock(Module.class);
final DataSchemaNode schNode = mock(DataSchemaNode.class);
when(moduleAug.getDataChildByName(qnamePath)).thenReturn(schNode);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(moduleAug);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug));
final TypeProvider typeProvider = null;
final Map<Module, ModuleContext> genCtx = new HashMap<>();
when(m.getNamespace()).thenReturn(qnamePath.getNamespace());
when(m.getRevision()).thenReturn(qnamePath.getRevision());
- final Object[] args = { augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, genTypeBuilders, typeProvider };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx,
+ genTypeBuilders, typeProvider);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof NullPointerException);
- assertEquals("Target type not yet generated: " + schNode, cause.getMessage());
+ } catch (final NullPointerException e) {
+ assertEquals("Target type not yet generated: " + schNode, e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void augmentationToGenTypesAugUsesNullOrigTargetTest() throws Exception {
- final Class[] parameterTypes = { String.class, Map.Entry.class, Module.class, SchemaContext.class,
- boolean.class, Map.class, Map.class, TypeProvider.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("augmentationToGenTypes", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void augmentationToGenTypesAugUsesNullOrigTargetTest() {
final String augmPackName = "pckg.name";
- final AugmentationSchema augmSchema = mock(AugmentationSchema.class);
+ final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class);
final QName qnamePath = QName.create("test", "2017-04-04", "aug");
final SchemaPath path = SchemaPath.create(true, qnamePath);
when(augmSchema.getTargetPath()).thenReturn(path);
final Set<UsesNode> uses = new HashSet<>();
when(augmSchema.getUses()).thenReturn(uses);
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
- augmentationSchemaList.add(augmSchema);
- final Map.Entry<SchemaPath, List<AugmentationSchema>> schemaPathAugmentListEntry = mock(Map.Entry.class);
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
+ AugmentationSchemaNodeList.add(augmSchema);
+ final Map.Entry<SchemaPath, List<AugmentationSchemaNode>> schemaPathAugmentListEntry = mock(Map.Entry.class);
when(schemaPathAugmentListEntry.getKey()).thenReturn(path);
- when(schemaPathAugmentListEntry.getValue()).thenReturn(augmentationSchemaList);
+ when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList);
final SchemaContext context = mock(SchemaContext.class);
final Module moduleAug = mock(Module.class);
final DerivableSchemaNode targetSchNode = mock(DerivableSchemaNode.class);
when(targetSchNode.getPath()).thenReturn(path);
when(targetSchNode.isAddedByUses()).thenReturn(true);
- final Optional optionalSchemaNode = Optional.absent();
- when(targetSchNode.getOriginal()).thenReturn(optionalSchemaNode);
+ when(targetSchNode.getOriginal()).thenReturn(Optional.empty());
when(moduleAug.getDataChildByName(qnamePath)).thenReturn(targetSchNode);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(moduleAug);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug));
final TypeProvider typeProvider = null;
final Map<Module, ModuleContext> genCtx = new HashMap<>();
when(m.getNamespace()).thenReturn(qnamePath.getNamespace());
when(m.getRevision()).thenReturn(qnamePath.getRevision());
- final Object[] args = { augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, genTypeBuilders, typeProvider };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx,
+ genTypeBuilders, typeProvider);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalStateException);
+ } catch (final IllegalStateException e) {
assertEquals("Failed to find target node from grouping in augmentation " + augmSchema + " in module "
- + m.getName(), cause.getMessage());
+ + m.getName(), e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void augmentationToGenTypesTargetChoicSchemaNodeTest() throws Exception {
- final Class[] parameterTypes = { String.class, Map.Entry.class, Module.class, SchemaContext.class,
- boolean.class, Map.class, Map.class, TypeProvider.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("augmentationToGenTypes", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void augmentationToGenTypesTargetChoicSchemaNodeTest() {
final String augmPackName = "pckg.name";
- final AugmentationSchema augmSchema = mock(AugmentationSchema.class);
+ final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class);
final QName qnamePath = QName.create("test", "2017-04-04", "aug");
final SchemaPath path = SchemaPath.create(true, qnamePath);
when(augmSchema.getTargetPath()).thenReturn(path);
final Set<UsesNode> uses = new HashSet<>();
when(augmSchema.getUses()).thenReturn(uses);
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
- augmentationSchemaList.add(augmSchema);
- final Map.Entry<SchemaPath, List<AugmentationSchema>> schemaPathAugmentListEntry = mock(Map.Entry.class);
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
+ AugmentationSchemaNodeList.add(augmSchema);
+ final Map.Entry<SchemaPath, List<AugmentationSchemaNode>> schemaPathAugmentListEntry = mock(Map.Entry.class);
when(schemaPathAugmentListEntry.getKey()).thenReturn(path);
- when(schemaPathAugmentListEntry.getValue()).thenReturn(augmentationSchemaList);
+ when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList);
final SchemaContext context = mock(SchemaContext.class);
final Module moduleAug = mock(Module.class);
final ChoiceSchemaNode targetSchNode = mock(ChoiceSchemaNode.class);
when(targetSchNode.getPath()).thenReturn(path);
when(moduleAug.getDataChildByName(qnamePath)).thenReturn(targetSchNode);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(moduleAug);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug));
final TypeProvider typeProvider = null;
- final Map genCtx = mock(Map.class);
+ final Map<Module, ModuleContext> genCtx = mock(Map.class);
final Collection<ModuleContext> moduleContexts = new ArrayList<>();
final ModuleContext mc = new ModuleContext();
final GeneratedTypeBuilder gtb = new GeneratedTypeBuilderImpl(augmPackName, "augm", mc);
when(m.getNamespace()).thenReturn(qnamePath.getNamespace());
when(m.getRevision()).thenReturn(qnamePath.getRevision());
- final Object[] args = { augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, genTypeBuilders, typeProvider };
- final Map result = (Map) generate.invoke(AugmentToGenType.class, args);
+ final Map<Module, ModuleContext> result = AugmentToGenType.augmentationToGenTypes(augmPackName,
+ schemaPathAugmentListEntry, m, context, false, genCtx, genTypeBuilders, typeProvider);
assertNotNull(result);
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void augmentationToGenTypesTest() throws Exception {
- final Class[] parameterTypes = { String.class, Map.Entry.class, Module.class, SchemaContext.class,
- boolean.class, Map.class, Map.class, TypeProvider.class };
- final Method generate = AugmentToGenType.class.getDeclaredMethod("augmentationToGenTypes", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void augmentationToGenTypesTest() {
final String augmPackName = "pckg.name";
- final AugmentationSchema augmSchema = mock(AugmentationSchema.class);
+ final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class);
final QName qnamePath = QName.create("test", "2017-04-04", "aug");
final SchemaPath path = SchemaPath.create(true, qnamePath);
when(augmSchema.getTargetPath()).thenReturn(path);
final List<UnknownSchemaNode> unknownSchemaNodes = new ArrayList<>();
when(augmSchema.getUnknownSchemaNodes()).thenReturn(unknownSchemaNodes);
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
- augmentationSchemaList.add(augmSchema);
- final Map.Entry<SchemaPath, List<AugmentationSchema>> schemaPathAugmentListEntry = mock(Map.Entry.class);
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
+ AugmentationSchemaNodeList.add(augmSchema);
+ final Map.Entry<SchemaPath, List<AugmentationSchemaNode>> schemaPathAugmentListEntry = mock(Map.Entry.class);
when(schemaPathAugmentListEntry.getKey()).thenReturn(path);
- when(schemaPathAugmentListEntry.getValue()).thenReturn(augmentationSchemaList);
+ when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList);
final SchemaContext context = mock(SchemaContext.class);
final Module moduleAug = mock(Module.class);
final Optional optionalSchemaNode = Optional.of(origSchNode);
when(targetSchNode.getOriginal()).thenReturn(optionalSchemaNode);
when(moduleAug.getDataChildByName(qnamePath)).thenReturn(targetSchNode);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(moduleAug);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug));
final TypeProvider typeProvider = null;
when(moduleAug.getNamespace()).thenReturn(qnamePath.getNamespace());
when(moduleAug.getRevision()).thenReturn(qnamePath.getRevision());
- final Object[] args =
- { augmPackName, schemaPathAugmentListEntry, moduleAug, context, false, genCtx, genTypeBuilders, typeProvider };
final Map<Module, ModuleContext> result =
- (Map<Module, ModuleContext>) generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, moduleAug, context,
+ false, genCtx, genTypeBuilders, typeProvider);
assertNotNull(result);
final ModuleContext moduleContext = result.get(moduleAug);
assertTrue(moduleContext.getAugmentations().get(0).getName().contains("Augm"));
@Deprecated
@Test
- public void usesAugmentationToGenTypesNullPckgNameTest() throws Exception {
+ public void usesAugmentationToGenTypesNullPckgNameTest() {
try {
AugmentToGenType.usesAugmentationToGenTypes(null, null, null, null, null, null, null, null, false, null, null);
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof IllegalArgumentException);
+ } catch (final IllegalArgumentException e) {
assertEquals(e.getMessage(), "Package Name cannot be NULL.");
}
}
@Deprecated
@Test
- public void usesAugmentationToGenTypesNullAugSchemaListEntryTest() throws Exception {
+ public void usesAugmentationToGenTypesNullAugSchemaListEntryTest() {
try {
AugmentToGenType.usesAugmentationToGenTypes(null, "", null, null, null, null, null, null, false, null, null);
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof IllegalArgumentException);
+ } catch (final IllegalArgumentException e) {
assertEquals(e.getMessage(), "Augmentation Schema List Entry cannot be NULL.");
}
}
@Deprecated
@Test
- public void usesAugmentationToGenTypesEmptyAugSchemaListTest() throws Exception {
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
+ public void usesAugmentationToGenTypesEmptyAugSchemaListTest() {
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
try {
- AugmentToGenType.usesAugmentationToGenTypes(null, "", augmentationSchemaList, null, null, null, null, null,
+ AugmentToGenType.usesAugmentationToGenTypes(null, "", AugmentationSchemaNodeList, null, null, null, null, null,
false, null, null);
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof IllegalStateException);
+ } catch (final IllegalStateException e) {
assertEquals(e.getMessage(), "Augmentation Schema List cannot be empty");
}
}
@Deprecated
@Test
- public void usesAugmentationToGenTypesNullAugSchemaNodeTargetPathTest() throws Exception {
- final AugmentationSchema augmentationSchema = mock(AugmentationSchema.class);
- when(augmentationSchema.getTargetPath()).thenReturn(null);
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
- augmentationSchemaList.add(augmentationSchema);
+ public void usesAugmentationToGenTypesNullAugSchemaNodeTargetPathTest() {
+ final AugmentationSchemaNode AugmentationSchemaNode = mock(AugmentationSchemaNode.class);
+ when(AugmentationSchemaNode.getTargetPath()).thenReturn(null);
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
+ AugmentationSchemaNodeList.add(AugmentationSchemaNode);
try {
- AugmentToGenType.usesAugmentationToGenTypes(null, "", augmentationSchemaList, null, null, null, null, null,
+ AugmentToGenType.usesAugmentationToGenTypes(null, "", AugmentationSchemaNodeList, null, null, null, null, null,
false, null, null);
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof IllegalStateException);
+ } catch (final IllegalStateException e) {
assertEquals(e.getMessage(), "Augmentation Schema does not contain Target Path (Target Path is NULL).");
}
}
@Deprecated
@Test
- public void usesAugmentationToGenTypesNullAugmentTargetTest() throws Exception {
+ public void usesAugmentationToGenTypesNullAugmentTargetTest() {
final QName qnamePath = QName.create("test", "2017-04-04", "aug");
final SchemaPath path = SchemaPath.create(true, qnamePath);
- final AugmentationSchema augmentationSchema = mock(AugmentationSchema.class);
- when(augmentationSchema.getTargetPath()).thenReturn(path);
+ final AugmentationSchemaNode AugmentationSchemaNode = mock(AugmentationSchemaNode.class);
+ when(AugmentationSchemaNode.getTargetPath()).thenReturn(path);
final Set<UsesNode> uses = new HashSet<>();
- when(augmentationSchema.getUses()).thenReturn(uses);
+ when(AugmentationSchemaNode.getUses()).thenReturn(uses);
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
- augmentationSchemaList.add(augmentationSchema);
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
+ AugmentationSchemaNodeList.add(AugmentationSchemaNode);
final SchemaContext context = mock(SchemaContext.class);
final Module moduleAug = mock(Module.class);
groupings.add(groupingDefinition);
when(moduleAug.getGroupings()).thenReturn(groupings);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(moduleAug);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug));
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
when(usesNode.getGroupingPath()).thenReturn(path);
try {
- AugmentToGenType.usesAugmentationToGenTypes(context, "pckg.test.augm", augmentationSchemaList, moduleAug,
+ AugmentToGenType.usesAugmentationToGenTypes(context, "pckg.test.augm", AugmentationSchemaNodeList, moduleAug,
usesNode, usesNodeParent, genCtx, genTypeBuilders, false, null, null);
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof IllegalArgumentException);
+ } catch (final IllegalArgumentException e) {
assertEquals(e.getMessage(), "augment target not found: " + path);
}
}
@Deprecated
@Test
- public void usesAugmentationToGenTypesNullTargetGTBTest() throws Exception {
+ public void usesAugmentationToGenTypesNullTargetGTBTest() {
final QName qnamePath = QName.create("test", "2017-04-04", "aug");
final SchemaPath path = SchemaPath.create(true, qnamePath);
- final AugmentationSchema augmentationSchema = mock(AugmentationSchema.class);
- when(augmentationSchema.getTargetPath()).thenReturn(path);
+ final AugmentationSchemaNode AugmentationSchemaNode = mock(AugmentationSchemaNode.class);
+ when(AugmentationSchemaNode.getTargetPath()).thenReturn(path);
final Set<UsesNode> uses = new HashSet<>();
- when(augmentationSchema.getUses()).thenReturn(uses);
+ when(AugmentationSchemaNode.getUses()).thenReturn(uses);
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
- augmentationSchemaList.add(augmentationSchema);
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
+ AugmentationSchemaNodeList.add(AugmentationSchemaNode);
final SchemaContext context = mock(SchemaContext.class);
final Module moduleAug = mock(Module.class);
groupings.add(groupingDefinition);
when(moduleAug.getGroupings()).thenReturn(groupings);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(moduleAug);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug));
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
when(usesNode.getGroupingPath()).thenReturn(path);
try {
- AugmentToGenType.usesAugmentationToGenTypes(context, "pckg.test.augm", augmentationSchemaList, moduleAug,
+ AugmentToGenType.usesAugmentationToGenTypes(context, "pckg.test.augm", AugmentationSchemaNodeList, moduleAug,
usesNode, usesNodeParent, genCtx, genTypeBuilders, false, null, null);
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof NullPointerException);
+ } catch (final NullPointerException e) {
assertEquals(e.getMessage(), "Target type not yet generated: " + schNode);
}
}
@Deprecated
@Test
- public void usesAugmentationToGenTypesTest() throws Exception {
+ public void usesAugmentationToGenTypesTest() {
final QName qnamePath = QName.create("test", "2017-04-04", "aug");
final SchemaPath path = SchemaPath.create(true, qnamePath);
- final AugmentationSchema augmentationSchema = mock(AugmentationSchema.class);
- when(augmentationSchema.getTargetPath()).thenReturn(path);
+ final AugmentationSchemaNode AugmentationSchemaNode = mock(AugmentationSchemaNode.class);
+ when(AugmentationSchemaNode.getTargetPath()).thenReturn(path);
final Set<UsesNode> uses = new HashSet<>();
- when(augmentationSchema.getUses()).thenReturn(uses);
+ when(AugmentationSchemaNode.getUses()).thenReturn(uses);
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
- augmentationSchemaList.add(augmentationSchema);
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
+ AugmentationSchemaNodeList.add(AugmentationSchemaNode);
final SchemaContext context = mock(SchemaContext.class);
final Module moduleAug = mock(Module.class);
groupings.add(groupingDefinition);
when(moduleAug.getGroupings()).thenReturn(groupings);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(moduleAug);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug));
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final ModuleContext mc = new ModuleContext();
when(usesNode.getGroupingPath()).thenReturn(path);
final Map<Module, ModuleContext> result = AugmentToGenType.usesAugmentationToGenTypes(context, "pckg.test.augm",
- augmentationSchemaList, moduleAug, usesNode, usesNodeParent, genCtx, genTypeBuilders, false, null,
+ AugmentationSchemaNodeList, moduleAug, usesNode, usesNodeParent, genCtx, genTypeBuilders, false, null,
BindingNamespaceType.Data);
assertNotNull(result);
}
@Deprecated
@Test
- public void usesAugmentationToGenTypesChoiceTest() throws Exception {
+ public void usesAugmentationToGenTypesChoiceTest() {
final QName qnamePath = QName.create("test", "2017-04-04", "aug");
final SchemaPath path = SchemaPath.create(true, qnamePath);
- final AugmentationSchema augmentationSchema = mock(AugmentationSchema.class);
- when(augmentationSchema.getTargetPath()).thenReturn(path);
+ final AugmentationSchemaNode AugmentationSchemaNode = mock(AugmentationSchemaNode.class);
+ when(AugmentationSchemaNode.getTargetPath()).thenReturn(path);
final Set<UsesNode> uses = new HashSet<>();
- when(augmentationSchema.getUses()).thenReturn(uses);
+ when(AugmentationSchemaNode.getUses()).thenReturn(uses);
- final List<AugmentationSchema> augmentationSchemaList = new ArrayList<>();
- augmentationSchemaList.add(augmentationSchema);
+ final List<AugmentationSchemaNode> AugmentationSchemaNodeList = new ArrayList<>();
+ AugmentationSchemaNodeList.add(AugmentationSchemaNode);
final SchemaContext context = mock(SchemaContext.class);
final Module moduleAug = mock(Module.class);
groupings.add(groupingDefinition);
when(moduleAug.getGroupings()).thenReturn(groupings);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(moduleAug);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug));
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final ModuleContext mc = new ModuleContext();
when(usesNode.getGroupingPath()).thenReturn(path);
final Map<Module, ModuleContext> result = AugmentToGenType.usesAugmentationToGenTypes(context, "pckg.test.augm",
- augmentationSchemaList, moduleAug, usesNode, usesNodeParent, genCtx, genTypeBuilders, false, null,
+ AugmentationSchemaNodeList, moduleAug, usesNode, usesNodeParent, genCtx, genTypeBuilders, false, null,
BindingNamespaceType.Data);
assertNotNull(result);
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void findOriginalTargetFromGroupingNonGroupingTest() throws Exception {
- final Class[] parameterTypes = { SchemaContext.class, SchemaPath.class, UsesNode.class };
- final Method generate =
- AugmentToGenType.class.getDeclaredMethod("findOriginalTargetFromGrouping", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void findOriginalTargetFromGroupingNonGroupingTest() {
final Module module = mock(Module.class);
final QName qnamePath = QName.create("test", "2017-04-04", "test");
final SchemaPath schemaPath = SchemaPath.create(true, qnamePath);
when(module.getDataChildByName(qnamePath)).thenReturn(schNode);
final SchemaContext context = mock(SchemaContext.class);
- when(context.findModuleByNamespaceAndRevision(qnamePath .getNamespace(), qnamePath.getRevision()))
- .thenReturn(module);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(module));
final UsesNode usesNode = mock(UsesNode.class);
when(usesNode.getGroupingPath()).thenReturn(schemaPath);
- final Object[] args = { context, schemaPath, usesNode };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.findOriginalTargetFromGrouping(context, schemaPath, usesNode);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalArgumentException);
- assertEquals("Failed to generate code for augment in " + usesNode, cause.getMessage());
+ } catch (final IllegalArgumentException e) {
+ assertEquals("Failed to generate code for augment in " + usesNode, e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void findOriginalTargetFromGroupingAsUsesFailedTest() throws Exception {
- final Class[] parameterTypes = { SchemaContext.class, SchemaPath.class, UsesNode.class };
- final Method generate =
- AugmentToGenType.class.getDeclaredMethod("findOriginalTargetFromGrouping", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void findOriginalTargetFromGroupingAsUsesFailedTest() {
final Module module = mock(Module.class);
final QName qnamePath = QName.create("test", "2017-04-04", "test");
final SchemaPath schemaPath = SchemaPath.create(true, qnamePath);
when(module.getGroupings()).thenReturn(groupings);
final SchemaContext context = mock(SchemaContext.class);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(module);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(module));
final UsesNode usesNode = mock(UsesNode.class);
when(usesNode.getGroupingPath()).thenReturn(schemaPath);
- final Object[] args = { context, schemaPath, usesNode };
+ final Object[] args = { };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.findOriginalTargetFromGrouping(context, schemaPath, usesNode);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalStateException);
- assertEquals("Failed to generate code for augment in " + usesNode, cause.getMessage());
+ } catch (final IllegalStateException e) {
+ assertEquals("Failed to generate code for augment in " + usesNode, e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void findOriginalTargetFromGroupingReturnNullTest() throws Exception {
- final Class[] parameterTypes = { SchemaContext.class, SchemaPath.class, UsesNode.class };
- final Method generate =
- AugmentToGenType.class.getDeclaredMethod("findOriginalTargetFromGrouping", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void findOriginalTargetFromGroupingReturnNullTest() {
final Module module = mock(Module.class);
final QName qnamePath = QName.create("test", "2017-04-04", "test");
final SchemaPath schemaPath = SchemaPath.create(true, qnamePath);
when(module.getGroupings()).thenReturn(groupings);
final SchemaContext context = mock(SchemaContext.class);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(module);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(module));
final UsesNode usesNode = mock(UsesNode.class);
when(usesNode.getGroupingPath()).thenReturn(schemaPath);
- final Object[] args = { context, schemaPath, usesNode };
- final DataSchemaNode result = (DataSchemaNode) generate.invoke(AugmentToGenType.class, args);
+ final Object[] args = { };
+ final DataSchemaNode result = AugmentToGenType.findOriginalTargetFromGrouping(context, schemaPath, usesNode);
assertEquals(null, result);
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void findOriginalTargetFromGroupingTest() throws Exception {
- final Class[] parameterTypes = { SchemaContext.class, SchemaPath.class, UsesNode.class };
- final Method generate =
- AugmentToGenType.class.getDeclaredMethod("findOriginalTargetFromGrouping", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void findOriginalTargetFromGroupingTest() {
final Module module = mock(Module.class);
final QName qnamePath = QName.create("test", "2017-04-04", "test");
final SchemaPath schemaPath = SchemaPath.create(true, qnamePath);
when(module.getGroupings()).thenReturn(groupings);
final SchemaContext context = mock(SchemaContext.class);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(module);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(module));
final UsesNode usesNode = mock(UsesNode.class);
when(usesNode.getGroupingPath()).thenReturn(schemaPath);
- final Object[] args = { context, schemaPath, usesNode };
- final DataSchemaNode result = (DataSchemaNode) generate.invoke(AugmentToGenType.class, args);
+ final DataSchemaNode result = AugmentToGenType.findOriginalTargetFromGrouping(context, schemaPath, usesNode);
assertEquals(schNode, result);
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void findOriginalTargetFromGroupingChoiceTest() throws Exception {
- final Class[] parameterTypes = { SchemaContext.class, SchemaPath.class, UsesNode.class };
- final Method generate =
- AugmentToGenType.class.getDeclaredMethod("findOriginalTargetFromGrouping", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void findOriginalTargetFromGroupingChoiceTest() {
final Module module = mock(Module.class);
final QName qnamePath = QName.create("test", "2017-04-04", "test");
final SchemaPath schemaPath = SchemaPath.create(true, qnamePath);
when(module.getGroupings()).thenReturn(groupings);
final SchemaContext context = mock(SchemaContext.class);
- when(context.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(module);
+ when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(module));
final UsesNode usesNode = mock(UsesNode.class);
when(usesNode.getGroupingPath()).thenReturn(schemaPath);
- final Object[] args = { context, schemaPath, usesNode };
- final DataSchemaNode result = (DataSchemaNode) generate.invoke(AugmentToGenType.class, args);
+ final DataSchemaNode result = AugmentToGenType.findOriginalTargetFromGrouping(context, schemaPath, usesNode);
assertEquals(schNode, result);
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void generateTypesFromAugmentedChoiceCasesNullPckgNameTest() throws Exception {
- final Class[] parameterTypes =
- { SchemaContext.class, Module.class, String.class, Type.class, ChoiceSchemaNode.class, List.class,
- DataNodeContainer.class, Map.class, boolean.class, Map.class, TypeProvider.class,
- BindingNamespaceType.class};
- final Method generate =
- AugmentToGenType.class.getDeclaredMethod("generateTypesFromAugmentedChoiceCases", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void generateTypesFromAugmentedChoiceCasesNullPckgNameTest() {
final SchemaContext schemaContext = null;
final Module module = null;
final String pckgName = null;
final Type targetType = null;
final ChoiceSchemaNode targetNode = null;
- final List<AugmentationSchema> schemaPathAugmentListEntry = null;
+ final List<AugmentationSchemaNode> schemaPathAugmentListEntry = null;
final DataNodeContainer usesNodeParent = null;
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilder = new HashMap<>();
- final Object[] args = { schemaContext, module, pckgName, targetType, targetNode, schemaPathAugmentListEntry,
- usesNodeParent, genCtx, false, genTypeBuilder, null, BindingNamespaceType.Data };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.generateTypesFromAugmentedChoiceCases(schemaContext, module, pckgName, targetType,
+ targetNode, schemaPathAugmentListEntry, usesNodeParent, genCtx, false, genTypeBuilder, null,
+ BindingNamespaceType.Data);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalArgumentException);
- assertEquals("Base Package Name cannot be NULL.", cause.getMessage());
+ } catch (final IllegalArgumentException e) {
+ assertEquals("Base Package Name cannot be NULL.", e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void generateTypesFromAugmentedChoiceCasesNullTargetType() throws Exception {
- final Class[] parameterTypes =
- { SchemaContext.class, Module.class, String.class, Type.class, ChoiceSchemaNode.class, List.class,
- DataNodeContainer.class, Map.class, boolean.class, Map.class, TypeProvider.class,
- BindingNamespaceType.class };
- final Method generate =
- AugmentToGenType.class.getDeclaredMethod("generateTypesFromAugmentedChoiceCases", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void generateTypesFromAugmentedChoiceCasesNullTargetType() {
final SchemaContext schemaContext = null;
final Module module = null;
final String pckgName = "";
final Type targetType = null;
final ChoiceSchemaNode targetNode = null;
- final List<AugmentationSchema> schemaPathAugmentListEntry = null;
+ final List<AugmentationSchemaNode> schemaPathAugmentListEntry = null;
final DataNodeContainer usesNodeParent = null;
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilder = new HashMap<>();
- final Object[] args = { schemaContext, module, pckgName, targetType, targetNode, schemaPathAugmentListEntry,
- usesNodeParent, genCtx, false, genTypeBuilder, null, BindingNamespaceType.Data };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.generateTypesFromAugmentedChoiceCases(schemaContext, module, pckgName, targetType,
+ targetNode, schemaPathAugmentListEntry, usesNodeParent, genCtx, false, genTypeBuilder, null,
+ BindingNamespaceType.Data);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalArgumentException);
- assertEquals("Referenced Choice Type cannot be NULL.", cause.getMessage());
+ } catch (final IllegalArgumentException e) {
+ assertEquals("Referenced Choice Type cannot be NULL.", e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void generateTypesFromAugmentedChoiceCasesNullAugmentNodes() throws Exception {
- final Class[] parameterTypes =
- { SchemaContext.class, Module.class, String.class, Type.class, ChoiceSchemaNode.class, List.class,
- DataNodeContainer.class, Map.class, boolean.class, Map.class, TypeProvider.class,
- BindingNamespaceType.class };
- final Method generate =
- AugmentToGenType.class.getDeclaredMethod("generateTypesFromAugmentedChoiceCases", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void generateTypesFromAugmentedChoiceCasesNullAugmentNodes() {
final SchemaContext schemaContext = null;
final Module module = null;
final String pckgName = "";
final Type targetType = mock(Type.class);
final ChoiceSchemaNode targetNode = null;
- final List<AugmentationSchema> schemaPathAugmentListEntry = null;
+ final List<AugmentationSchemaNode> schemaPathAugmentListEntry = null;
final DataNodeContainer usesNodeParent = null;
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilder = new HashMap<>();
- final Object[] args = { schemaContext, module, pckgName, targetType, targetNode, schemaPathAugmentListEntry, usesNodeParent,
- genCtx, false, genTypeBuilder, null, BindingNamespaceType.Data };
+ final Object[] args = { };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.generateTypesFromAugmentedChoiceCases(schemaContext, module, pckgName, targetType,
+ targetNode, schemaPathAugmentListEntry, usesNodeParent, genCtx, false, genTypeBuilder, null,
+ BindingNamespaceType.Data);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalArgumentException);
- assertEquals("Set of Choice Case Nodes cannot be NULL.", cause.getMessage());
+ } catch (final IllegalArgumentException e) {
+ assertEquals("Set of Choice Case Nodes cannot be NULL.", e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void generateTypesFromAugmentedChoiceCasesNullCaseNodeTest() throws Exception {
- final Class[] parameterTypes =
- { SchemaContext.class, Module.class, String.class, Type.class, ChoiceSchemaNode.class, List.class,
- DataNodeContainer.class, Map.class, boolean.class, Map.class, TypeProvider.class,
- BindingNamespaceType.class };
- final Method generate =
- AugmentToGenType.class.getDeclaredMethod("generateTypesFromAugmentedChoiceCases", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void generateTypesFromAugmentedChoiceCasesNullCaseNodeTest() {
final SchemaContext schemaContext = null;
final Module module = null;
final String pckgName = "";
final DataSchemaNode caseNode = null;
augmentNodes.add(caseNode);
- final AugmentationSchema augmentationSchema = mock(AugmentationSchema.class);
- when(augmentationSchema.getChildNodes()).thenReturn(augmentNodes);
- final List<AugmentationSchema> schemaPathAugmentListEntry = new ArrayList<>();
- schemaPathAugmentListEntry.add(augmentationSchema);
+ final AugmentationSchemaNode AugmentationSchemaNode = mock(AugmentationSchemaNode.class);
+ when(AugmentationSchemaNode.getChildNodes()).thenReturn(augmentNodes);
+ final List<AugmentationSchemaNode> schemaPathAugmentListEntry = new ArrayList<>();
+ schemaPathAugmentListEntry.add(AugmentationSchemaNode);
final DataNodeContainer usesNodeParent = null;
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilder = new HashMap<>();
- final Object[] args = { schemaContext, module, pckgName, targetType, targetNode, schemaPathAugmentListEntry, usesNodeParent,
- genCtx, false, genTypeBuilder, null, BindingNamespaceType.Data };
- final Map<Module, ModuleContext> result =
- (Map<Module, ModuleContext>) generate.invoke(AugmentToGenType.class, args);
+ final Map<Module, ModuleContext> result = AugmentToGenType.generateTypesFromAugmentedChoiceCases(schemaContext,
+ module, pckgName, targetType, targetNode, schemaPathAugmentListEntry, usesNodeParent, genCtx, false,
+ genTypeBuilder, null, BindingNamespaceType.Data);
assertEquals(genCtx, result);
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void generateTypesFromAugmentedChoiceCasesNullChildTest() throws Exception {
- final Class[] parameterTypes =
- { SchemaContext.class, Module.class, String.class, Type.class, ChoiceSchemaNode.class, List.class,
- DataNodeContainer.class, Map.class, boolean.class, Map.class, TypeProvider.class,
- BindingNamespaceType.class };
- final Method generate =
- AugmentToGenType.class.getDeclaredMethod("generateTypesFromAugmentedChoiceCases", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void generateTypesFromAugmentedChoiceCasesNullChildTest() {
final QName qnamePath = QName.create("test", "2017-04-04", "chcase");
final QName qnamePath2 = QName.create("test", "2017-04-04", "chcase2");
final SchemaPath path = SchemaPath.create(true, qnamePath, qnamePath2);
final Type targetType = mock(Type.class);
when(targetType.getFullyQualifiedName()).thenReturn(Augmentable.class.getName());
final Set<DataSchemaNode> augmentNodes = new HashSet<>();
- final ChoiceCaseNode caseNode = mock(ChoiceCaseNode.class);
+ final CaseSchemaNode caseNode = mock(CaseSchemaNode.class);
when(caseNode.getPath()).thenReturn(path);
when(caseNode.getQName()).thenReturn(qnamePath);
+ when(caseNode.getDescription()).thenReturn(Optional.empty());
+ when(caseNode.getReference()).thenReturn(Optional.empty());
+
augmentNodes.add(caseNode);
- final AugmentationSchema augmentationSchema = mock(AugmentationSchema.class);
- when(augmentationSchema.getChildNodes()).thenReturn(augmentNodes);
- final List<AugmentationSchema> schemaPathAugmentListEntry = new ArrayList<>();
- schemaPathAugmentListEntry.add(augmentationSchema);
+ final AugmentationSchemaNode AugmentationSchemaNode = mock(AugmentationSchemaNode.class);
+ when(AugmentationSchemaNode.getChildNodes()).thenReturn(augmentNodes);
+ final List<AugmentationSchemaNode> schemaPathAugmentListEntry = new ArrayList<>();
+ schemaPathAugmentListEntry.add(AugmentationSchemaNode);
final DataNodeContainer usesNodeParent = null;
final ChoiceSchemaNode targetNode = mock(ChoiceSchemaNode.class);
when(targetNode.getPath()).thenReturn(path);
+ when(targetNode.getDescription()).thenReturn(Optional.empty());
+ when(targetNode.getReference()).thenReturn(Optional.empty());
+
final Map<Module, ModuleContext> genCtx = new HashMap<>();
genCtx.put(module, new ModuleContext());
final GeneratedTypeBuilder gtb = new GeneratedTypeBuilderImpl(pckgName, "test-case-node-augment", genCtx.get(module));
genCtx.get(module).addCaseType(path, gtb);
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilder = new HashMap<>();
- when(schemaContext.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(module);
+ when(schemaContext.findModule(qnamePath.getModule())).thenReturn(Optional.of(module));
- final Object[] args = { schemaContext, module, pckgName, targetType, targetNode, schemaPathAugmentListEntry, usesNodeParent,
- genCtx, false, genTypeBuilder, null, BindingNamespaceType.Data };
try {
- generate.invoke(AugmentToGenType.class, args);
+ AugmentToGenType.generateTypesFromAugmentedChoiceCases(schemaContext, module, pckgName, targetType,
+ targetNode, schemaPathAugmentListEntry, usesNodeParent, genCtx, false, genTypeBuilder, null,
+ BindingNamespaceType.Data);
fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalArgumentException);
- assertEquals("Failed to find parent type of choice " + targetNode, cause.getMessage());
+ } catch (final IllegalArgumentException e) {
+ assertEquals("Failed to find parent type of choice " + targetNode, e.getMessage());
}
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void generateTypesFromAugmentedChoiceCasesTest() throws Exception {
- final Class[] parameterTypes =
- { SchemaContext.class, Module.class, String.class, Type.class, ChoiceSchemaNode.class, List.class,
- DataNodeContainer.class, Map.class, boolean.class, Map.class, TypeProvider.class,
- BindingNamespaceType.class };
- final Method generate =
- AugmentToGenType.class.getDeclaredMethod("generateTypesFromAugmentedChoiceCases", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void generateTypesFromAugmentedChoiceCasesTest() {
final QName qnamePath = QName.create("test", "2017-04-04", "chcase");
final QName qnamePath2 = QName.create("test", "2017-04-04", "chcase2");
final SchemaPath path = SchemaPath.create(true, qnamePath, qnamePath2);
final SchemaContext schemaContext = mock(SchemaContext.class);
final Module module = mock(Module.class);
when(module.getName()).thenReturn("test-module-case");
- final ChoiceCaseNode schemaNode = mock(ChoiceCaseNode.class);
+ final CaseSchemaNode schemaNode = mock(CaseSchemaNode.class);
when(schemaNode.getPath()).thenReturn(path);
when(module.getDataChildByName(qnamePath)).thenReturn(schemaNode);
when(module.getRevision()).thenReturn(qnamePath.getRevision());
final Type targetType = mock(Type.class);
when(targetType.getFullyQualifiedName()).thenReturn(Augmentable.class.getName());
final Set<DataSchemaNode> augmentNodes = new HashSet<>();
- final ChoiceCaseNode caseNode = mock(ChoiceCaseNode.class);
+ final CaseSchemaNode caseNode = mock(CaseSchemaNode.class);
when(caseNode.getPath()).thenReturn(path);
when(caseNode.getQName()).thenReturn(qnamePath);
+ when(caseNode.getDescription()).thenReturn(Optional.empty());
+ when(caseNode.getReference()).thenReturn(Optional.empty());
augmentNodes.add(caseNode);
- final AugmentationSchema augmentationSchema = mock(AugmentationSchema.class);
- when(augmentationSchema.getChildNodes()).thenReturn(augmentNodes);
- final List<AugmentationSchema> schemaPathAugmentListEntry = new ArrayList<>();
- schemaPathAugmentListEntry.add(augmentationSchema);
+ final AugmentationSchemaNode AugmentationSchemaNode = mock(AugmentationSchemaNode.class);
+ when(AugmentationSchemaNode.getChildNodes()).thenReturn(augmentNodes);
+ final List<AugmentationSchemaNode> schemaPathAugmentListEntry = new ArrayList<>();
+ schemaPathAugmentListEntry.add(AugmentationSchemaNode);
final DataNodeContainer usesNodeParent = null;
final ChoiceSchemaNode targetNode = mock(ChoiceSchemaNode.class);
when(targetNode.getPath()).thenReturn(path);
+ when(targetNode.getDescription()).thenReturn(Optional.empty());
+ when(targetNode.getReference()).thenReturn(Optional.empty());
final Map<Module, ModuleContext> genCtx = new HashMap<>();
final ModuleContext moduleContext = new ModuleContext();
final GeneratedTypeBuilder gtb = new GeneratedTypeBuilderImpl(pckgName, "test-case-node-augment", moduleContext);
genCtx.put(module, moduleContext);
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilder = new HashMap<>();
- when(schemaContext.findModuleByNamespaceAndRevision(qnamePath.getNamespace(), qnamePath.getRevision()))
- .thenReturn(module);
+ when(schemaContext.findModule(qnamePath.getModule())).thenReturn(Optional.of(module));
- final Object[] args = { schemaContext, module, pckgName, targetType, targetNode, schemaPathAugmentListEntry, usesNodeParent,
- genCtx, false, genTypeBuilder, null ,BindingNamespaceType.Data };
- final Map<Module, ModuleContext> result =
- (Map<Module, ModuleContext>) generate.invoke(AugmentToGenType.class, args);
+ final Map<Module, ModuleContext> result = AugmentToGenType.generateTypesFromAugmentedChoiceCases(schemaContext,
+ module, pckgName, targetType, targetNode, schemaPathAugmentListEntry, usesNodeParent, genCtx, false,
+ genTypeBuilder, null, BindingNamespaceType.Data);
assertNotNull(result);
assertEquals(result.get(module), moduleContext);
}
package org.opendaylight.mdsal.binding.javav2.generator.impl;
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 static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import java.io.FileNotFoundException;
import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import org.junit.Test;
import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext;
-import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider;
import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class AuxiliaryGenUtilsTest {
- @SuppressWarnings("unchecked")
@Test(expected = UnsupportedOperationException.class)
public void constructorTest() throws Throwable {
- final Constructor<AuxiliaryGenUtils> constructor =
- (Constructor<AuxiliaryGenUtils>) AuxiliaryGenUtils.class.getDeclaredConstructors()[0];
+ final Constructor<AuxiliaryGenUtils> constructor = AuxiliaryGenUtils.class.getDeclaredConstructor();
constructor.setAccessible(true);
- final Object[] objs = {};
try {
- constructor.newInstance(objs);
+ constructor.newInstance();
} catch (final Exception e) {
throw e.getCause();
}
}
- @SuppressWarnings("rawtypes")
@Test
- public void annotateDeprecatedIfNecessaryNonDepricatedTest() throws Exception {
- final Class[] parameterTypes = { Status.class, GeneratedTypeBuilder.class };
- final Method generate =
- AuxiliaryGenUtils.class.getDeclaredMethod("annotateDeprecatedIfNecessary", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void annotateDeprecatedIfNecessaryNonDepricatedTest() {
final GeneratedTypeBuilderImpl generatedTypeBuilder =
new GeneratedTypeBuilderImpl("test.deprecated", "Non_Deprecated", new ModuleContext());
final Status status = Status.CURRENT;
- final Object[] args = { status, generatedTypeBuilder };
- generate.invoke(AuxiliaryGenUtils.class, args);
+ AuxiliaryGenUtils.annotateDeprecatedIfNecessary(status, generatedTypeBuilder);
assertTrue(generatedTypeBuilder.toInstance().getAnnotations().isEmpty());
}
- @SuppressWarnings("rawtypes")
@Test
- public void annotateDeprecatedIfNecessaryDepricatedTest() throws Exception {
- final Class[] parameterTypes = { Status.class, GeneratedTypeBuilder.class };
- final Method generate =
- AuxiliaryGenUtils.class.getDeclaredMethod("annotateDeprecatedIfNecessary", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void annotateDeprecatedIfNecessaryDepricatedTest() {
final GeneratedTypeBuilderImpl generatedTypeBuilder =
new GeneratedTypeBuilderImpl("test.deprecated", "Deprecated", new ModuleContext());
final Status status = Status.DEPRECATED;
- final Object[] args = { status, generatedTypeBuilder };
- generate.invoke(AuxiliaryGenUtils.class, args);
- assertTrue(!generatedTypeBuilder.toInstance().getAnnotations().isEmpty());
+ AuxiliaryGenUtils.annotateDeprecatedIfNecessary(status, generatedTypeBuilder);
+ assertFalse(generatedTypeBuilder.toInstance().getAnnotations().isEmpty());
assertEquals("Deprecated", generatedTypeBuilder.toInstance().getAnnotations().get(0).getName());
}
@Test
- public void hasBuilderClassFalseTest() throws Exception {
+ public void hasBuilderClassFalseTest() {
assertEquals(false, hasBuilderClass(LeafSchemaNode.class));
}
@Test
- public void hasBuilderClassContainerTest() throws Exception {
+ public void hasBuilderClassContainerTest() {
assertEquals(true, hasBuilderClass(ContainerSchemaNode.class));
}
@Test
- public void hasBuilderClassListTest() throws Exception {
+ public void hasBuilderClassListTest() {
assertEquals(true, hasBuilderClass(ListSchemaNode.class));
}
@Test
- public void hasBuilderClassRpcTest() throws Exception {
+ public void hasBuilderClassRpcTest() {
assertEquals(true, hasBuilderClass(RpcDefinition.class));
}
@Test
- public void hasBuilderClassNotificationTest() throws Exception {
+ public void hasBuilderClassNotificationTest() {
assertEquals(true, hasBuilderClass(NotificationDefinition.class));
}
- @SuppressWarnings("rawtypes")
@Test
- public void qNameConstantTest() throws Exception {
- final Class[] parameterTypes = { GeneratedTypeBuilderBase.class, String.class, QName.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("qNameConstant", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final GeneratedTypeBuilderBase gtbb = new GeneratedTypeBuilderImpl("test", "qname_constants", new ModuleContext());
+ public void qNameConstantTest() {
+ final GeneratedTypeBuilderBase<?> gtbb = new GeneratedTypeBuilderImpl("test", "qname_constants",
+ new ModuleContext());
final String constantName = "ConstantName";
final QName constantQName = QName.create("urn:constant", "2017-04-06", constantName);
- final Object[] args = { gtbb, constantName, constantQName };
- final Constant result = (Constant) generate.invoke(AuxiliaryGenUtils.class, args);
+ final Constant result = AuxiliaryGenUtils.qNameConstant(gtbb, constantName, constantQName);
assertEquals(constantName, result.getName());
}
- @SuppressWarnings("rawtypes")
@Test
- public void constructGetterTest() throws Exception {
- final Class[] parameterTypes =
- { GeneratedTypeBuilder.class, String.class, String.class, Type.class, Status.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("constructGetter", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void constructGetterTest() {
final GeneratedTypeBuilder gtb = new GeneratedTypeBuilderImpl("test", "Getter_of", new ModuleContext());
final String schemaNodeName = "schema_node_getter";
final String comment = null;
final Type returnType = Types.STRING;
final Status status = Status.DEPRECATED;
- final Object[] args = { gtb, schemaNodeName, comment, returnType, status };
- final MethodSignatureBuilder result = (MethodSignatureBuilder) generate.invoke(AuxiliaryGenUtils.class, args);
- assertEquals(new StringBuilder("get").append("SchemaNodeGetter").toString(),
- result.toInstance(returnType).getName());
+ final MethodSignatureBuilder result = AuxiliaryGenUtils.constructGetter(gtb, schemaNodeName, comment,
+ returnType, status);
+ assertEquals("getSchemaNodeGetter", result.toInstance(returnType).getName());
}
@Test
public void getterMethodNameBooleanTest() throws Exception {
- assertEquals("isBooleanMethod", getterMethodName("boolean_method", Types.BOOLEAN));
+ assertEquals("isBooleanMethod", AuxiliaryGenUtils.getterMethodName("boolean_method", Types.BOOLEAN));
}
@Test
public void getterMethodNameTest() throws Exception {
- assertEquals("getClazz", getterMethodName("clazz", Types.CLASS));
+ assertEquals("getClazz", AuxiliaryGenUtils.getterMethodName("clazz", Types.CLASS));
}
- @SuppressWarnings("rawtypes")
@Test
- public void createDescriptionWithSchemaNodeTest() throws Exception {
- final Class[] parameterTypes = { SchemaNode.class, String.class, SchemaContext.class, boolean.class,
- BindingNamespaceType.class};
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("createDescription", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final SchemaContext schemaContext = YangParserTestUtils.parseYangSource("/generator/test-list.yang");
+ public void createDescriptionWithSchemaNodeTest() {
+ final SchemaContext schemaContext = YangParserTestUtils.parseYangResource("/generator/test-list.yang");
final ListSchemaNode containerSchemaNode =
(ListSchemaNode) schemaContext.getModules().iterator().next().getChildNodes().iterator().next();
final String fullyQualifiedName =
"org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.list.rev170314.data.MyList";
- final Object[] args = { containerSchemaNode, fullyQualifiedName, schemaContext, true, BindingNamespaceType.Data };
- final String result = (String) generate.invoke(AuxiliaryGenUtils.class, args);
+ final String result = AuxiliaryGenUtils.createDescription(containerSchemaNode, fullyQualifiedName,
+ schemaContext, true, BindingNamespaceType.Data);
assertNotNull(result);
assertTrue(result.contains("list my-list"));
assertTrue(result.contains("leaf key"));
assertTrue(result.contains("@see org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.list.rev170314.key.my_list.MyListKey"));
}
- @SuppressWarnings("rawtypes")
@Test
- public void createDescriptionWithSchemaNodeWithDescriptionTest() throws Exception {
- final Class[] parameterTypes = { SchemaNode.class, String.class, SchemaContext.class, boolean.class,
- BindingNamespaceType.class};
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("createDescription", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void createDescriptionWithSchemaNodeWithDescriptionTest() {
final SchemaContext schemaContext =
- YangParserTestUtils.parseYangSource("/base/test-leaf-with-description.yang");
+ YangParserTestUtils.parseYangResource("/base/test-leaf-with-description.yang");
final LeafSchemaNode containerSchemaNode =
(LeafSchemaNode) schemaContext.getModules().iterator().next().getChildNodes().iterator().next();
final String fullyQualifiedName = "test.base.cont.with.leaf.MyList";
- final Object[] args = { containerSchemaNode, fullyQualifiedName, schemaContext, true, BindingNamespaceType.Data};
- final String result = (String) generate.invoke(AuxiliaryGenUtils.class, args);
+ final String result = AuxiliaryGenUtils.createDescription(containerSchemaNode, fullyQualifiedName,
+ schemaContext, true, BindingNamespaceType.Data);
assertNotNull(result);
assertTrue(result.contains("I am leaf."));
}
- @SuppressWarnings("rawtypes")
@Test
- public void createDescriptionTest() throws Exception {
- final Class[] parameterTypes = { Module.class, boolean.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("createDescription", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final SchemaContext schemaContext = YangParserTestUtils.parseYangSource("/base/test-module.yang");
-
- final Object[] args = { schemaContext.getModules().iterator().next(), true };
- final String result = (String) generate.invoke(AuxiliaryGenUtils.class, args);
+ public void createDescriptionTest() {
+ final SchemaContext schemaContext = YangParserTestUtils.parseYangResource("/base/test-module.yang");
+ final String result = AuxiliaryGenUtils.createDescription(schemaContext.getModules().iterator().next(), true);
assertNotNull(result);
assertTrue(result.contains("Base test module description"));
assertTrue(result.contains("test-module"));
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void createDescriptionWithSchemaNodesTest() throws Exception {
- final Class[] parameterTypes = { Set.class, Module.class, boolean.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("createDescription", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final SchemaContext schemaContext = YangParserTestUtils.parseYangSource("/base/test-rpc-and-notification.yang");
+ public void createDescriptionWithSchemaNodesTest() {
+ final SchemaContext schemaContext = YangParserTestUtils.parseYangResource("/base/test-rpc-and-notification.yang");
final Module module = schemaContext.getModules().iterator().next();
- Set schemaNodes = new HashSet<>();
+ Set<SchemaNode> schemaNodes = new HashSet<>();
schemaNodes.add(module.getRpcs().iterator().next());
- final Object[] args = { schemaNodes, module, true };
- String result = (String) generate.invoke(AuxiliaryGenUtils.class, args);
+ String result = AuxiliaryGenUtils.createDescription(schemaNodes, module, true);
assertNotNull(result);
assertTrue(result.contains(
"Interface for implementing the following YANG RPCs defined in module <b>test-rpc-and-notification-module</b>"));
schemaNodes = new HashSet<>();
schemaNodes.add(module.getNotifications().iterator().next());
- final Object[] args_n = { schemaNodes, module, true };
- result = (String) generate.invoke(AuxiliaryGenUtils.class, args_n);
+ result = AuxiliaryGenUtils.createDescription(schemaNodes, module, true);
assertNotNull(result);
assertTrue(result.contains(
"Interface for receiving the following YANG notifications defined in module <b>test-rpc-and-notification-module</b>"));
assertTrue(result.contains("notification my-notification"));
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void isNullOrEmptyIsNullTest() throws Exception {
- final Class[] parameterTypes = { Collection.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("isNullOrEmpty", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final Collection list = null;
-
- final Object[] args_n = { list };
- final boolean result = (boolean) generate.invoke(AuxiliaryGenUtils.class, args_n);
- assertTrue(result);
+ public void isNullOrEmptyIsNullTest() {
+ assertTrue(AuxiliaryGenUtils.isNullOrEmpty(null));
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void isNullOrEmptyIsEmptyTest() throws Exception {
- final Class[] parameterTypes = { Collection.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("isNullOrEmpty", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final Collection list = new ArrayList<>();
-
- final Object[] args_n = { list };
- final boolean result = (boolean) generate.invoke(AuxiliaryGenUtils.class, args_n);
- assertTrue(result);
+ public void isNullOrEmptyIsEmptyTest() {
+ assertTrue(AuxiliaryGenUtils.isNullOrEmpty(new ArrayList<>()));
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void isNullOrEmptyNotNullNotEmptyTest() throws Exception {
- final Class[] parameterTypes = { Collection.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("isNullOrEmpty", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final Collection list = new ArrayList<>();
+ public void isNullOrEmptyNotNullNotEmptyTest() {
+ final Collection<Object> list = new ArrayList<>();
list.add(new Object());
-
- final Object[] args_n = { list };
- final boolean result = (boolean) generate.invoke(AuxiliaryGenUtils.class, args_n);
- assertTrue(!result);
+ assertFalse(AuxiliaryGenUtils.isNullOrEmpty(list));
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void augGenTypeNameTest() throws Exception {
- final Class[] parameterTypes = { Map.class, String.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("augGenTypeName", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void augGenTypeNameTest() {
final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
builders.put("genTypeName1", new GeneratedTypeBuilderImpl("pckg.a1", "gen_a_1", new ModuleContext()));
builders.put("genTypeName2", new GeneratedTypeBuilderImpl("pckg.a2", "gen_a_2", new ModuleContext()));
final String genTypeName = "genTypeName";
-
- final Object[] args_n = { builders, genTypeName };
- final String result = (String) generate.invoke(AuxiliaryGenUtils.class, args_n);
- assertEquals("genTypeName3", result);
+ assertEquals("genTypeName3", AuxiliaryGenUtils.augGenTypeName(builders, genTypeName));
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void getAugmentIdentifierNullTest() throws Exception {
- final Class[] parameterTypes = { List.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("getAugmentIdentifier", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final List<UnknownSchemaNode> list = new ArrayList<>();
-
- final Object[] args_n = { list };
- final String result = (String) generate.invoke(AuxiliaryGenUtils.class, args_n);
- assertEquals(null, result);
+ public void getAugmentIdentifierNullTest() {
+ assertNull(AuxiliaryGenUtils.getAugmentIdentifier(new ArrayList<>()));
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void getAugmentIdentifierTest() throws Exception {
- final Class[] parameterTypes = { List.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("getAugmentIdentifier", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void getAugmentIdentifierTest() {
final List<UnknownSchemaNode> list = new ArrayList<>();
final UnknownSchemaNode unknownSchemaNode = mock(UnknownSchemaNode.class);
final QName qname =
when(unknownSchemaNode.getNodeParameter()).thenReturn(value);
list.add(unknownSchemaNode);
- final Object[] args_n = { list };
- final String result = (String) generate.invoke(AuxiliaryGenUtils.class, args_n);
- assertEquals(value, result);
+ assertEquals(value, AuxiliaryGenUtils.getAugmentIdentifier(list));
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void resolveInnerEnumFromTypeDefinitionNullTest() throws Exception {
- final Class[] parameterTypes =
- { EnumTypeDefinition.class, QName.class, Map.class, GeneratedTypeBuilder.class, Module.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("resolveInnerEnumFromTypeDefinition", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void resolveInnerEnumFromTypeDefinitionNullTest() {
EnumTypeDefinition enumTypeDefinition = null;
final QName qname = null;
final GeneratedTypeBuilder gtb = null;
- final Map map = new HashMap<>();
+ final Map<Module, ModuleContext> map = new HashMap<>();
final Module module = null;
- final Object[] args_n = { enumTypeDefinition, qname, map, gtb, module };
- EnumBuilder result = (EnumBuilder) generate.invoke(AuxiliaryGenUtils.class, args_n);
+ EnumBuilder result = AuxiliaryGenUtils.resolveInnerEnumFromTypeDefinition(enumTypeDefinition, qname, map, gtb,
+ module);
assertEquals(null, result);
enumTypeDefinition = mock(EnumTypeDefinition.class);
- final Object[] args1 = { enumTypeDefinition, qname, map, gtb, module };
- result = (EnumBuilder) generate.invoke(AuxiliaryGenUtils.class, args1);
+ result = AuxiliaryGenUtils.resolveInnerEnumFromTypeDefinition(enumTypeDefinition, qname, map, gtb, module);
assertEquals(null, result);
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void resolveInnerEnumFromTypeDefinitionTest() throws Exception {
- final Class[] parameterTypes =
- { EnumTypeDefinition.class, QName.class, Map.class, GeneratedTypeBuilder.class, Module.class };
- final Method generate =
- AuxiliaryGenUtils.class.getDeclaredMethod("resolveInnerEnumFromTypeDefinition", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void resolveInnerEnumFromTypeDefinitionTest() {
final QName qname = QName.create("urn:enum:test", "2017-12-04", "enum-test");
final EnumTypeDefinition enumTypeDefinition = mock(EnumTypeDefinition.class);
final QName enumQName = QName.create(qname, "enum-qname-test");
when(enumTypeDefinition.getQName()).thenReturn(enumQName);
final SchemaPath schemaPath = SchemaPath.create(true, enumQName);
when(enumTypeDefinition.getPath()).thenReturn(schemaPath);
- final GeneratedTypeBuilder gtb = new GeneratedTypeBuilderImpl("urn.enum.test.pckg", "enum-test", new ModuleContext());
+ when(enumTypeDefinition.getDescription()).thenReturn(Optional.empty());
+ when(enumTypeDefinition.getReference()).thenReturn(Optional.empty());
+ final GeneratedTypeBuilder gtb = new GeneratedTypeBuilderImpl("urn.enum.test.pckg", "enum-test",
+ new ModuleContext());
final Map<Module, ModuleContext> map = new HashMap<>();
final Module module = mock(Module.class);
final ModuleContext moduleContext = new ModuleContext();
map.put(module, moduleContext);
- final Object[] args1 = { enumTypeDefinition, qname, map, gtb, module };
- final EnumBuilder result = (EnumBuilder) generate.invoke(AuxiliaryGenUtils.class, args1);
+ final EnumBuilder result = AuxiliaryGenUtils.resolveInnerEnumFromTypeDefinition(enumTypeDefinition, qname, map,
+ gtb, module);
assertNotNull(result);
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void addTOToTypeBuilderNullTest() throws Exception {
- final Class[] parameterTypes =
- { TypeDefinition.class, GeneratedTypeBuilder.class, DataSchemaNode.class, Module.class,
- TypeProvider.class, SchemaContext.class, ModuleContext.class, Map.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("addTOToTypeBuilder", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void addTOToTypeBuilderNullTest() {
final BooleanTypeDefinition typeDef = mock(BooleanTypeDefinition.class);
final GeneratedTypeBuilder typeBuilder =
new GeneratedTypeBuilderImpl("test.boolean.type.def", "boolean-type-def", new ModuleContext());
final Map<Module, ModuleContext> genCtx = new HashMap<>();
genCtx.put(parentModule, new ModuleContext());
- final Object[] args1 = { typeDef, typeBuilder, leaf, parentModule, typeProvider, schemaContext, new ModuleContext(), genCtx };
- final GeneratedTOBuilder result = (GeneratedTOBuilder) generate.invoke(AuxiliaryGenUtils.class, args1);
+ final GeneratedTOBuilder result = AuxiliaryGenUtils.addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule,
+ typeProvider, schemaContext, new ModuleContext(), genCtx);
assertEquals(null, result);
}
@Test
- public void addTOToTypeBuilderUnionTest() throws Exception {
+ public void addTOToTypeBuilderUnionTest() {
assertNotNull(addTOToBuilder("/base/test-union.yang"));
}
@Test
- public void addTOToTypeBuilderBitsTest() throws Exception {
+ public void addTOToTypeBuilderBitsTest() {
assertNotNull(addTOToBuilder("/base/test-bits.yang"));
}
- @SuppressWarnings({ "rawtypes" })
- private GeneratedTOBuilder addTOToBuilder(final String yangPath)
- throws NoSuchMethodException, ReactorException, FileNotFoundException, URISyntaxException,
- IllegalAccessException, InvocationTargetException {
- final Class[] parameterTypes = { TypeDefinition.class, GeneratedTypeBuilder.class, DataSchemaNode.class,
- Module.class, TypeProvider.class, SchemaContext.class, ModuleContext.class, Map.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("addTOToTypeBuilder", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final GeneratedTypeBuilder typeBuilder =
- new GeneratedTypeBuilderImpl("test.boolean.spc.def", "spec-type-def", new ModuleContext());
- final SchemaContext schemaContext = YangParserTestUtils.parseYangSource(yangPath);
+ private static GeneratedTOBuilder addTOToBuilder(final String yangPath) {
+ final GeneratedTypeBuilder typeBuilder = new GeneratedTypeBuilderImpl("test.boolean.spc.def", "spec-type-def",
+ new ModuleContext());
+ final SchemaContext schemaContext = YangParserTestUtils.parseYangResource(yangPath);
final TypeProviderImpl typeProvider = new TypeProviderImpl(schemaContext);
final LeafSchemaNode leafSchemaNode =
(LeafSchemaNode) schemaContext.getModules().iterator().next().getChildNodes().iterator().next();
final Map<Module, ModuleContext> genCtx = new HashMap<>();
genCtx.put(schemaContext.getModules().iterator().next(), new ModuleContext());
- final Object[] args1 = { typeDef, typeBuilder, leafSchemaNode, schemaContext.getModules().iterator().next(),
- typeProvider, schemaContext, new ModuleContext(), genCtx };
- return (GeneratedTOBuilder) generate.invoke(AuxiliaryGenUtils.class, args1);
+ return AuxiliaryGenUtils.addTOToTypeBuilder(typeDef, typeBuilder, leafSchemaNode,
+ schemaContext.getModules().iterator().next(), typeProvider, schemaContext, new ModuleContext(), genCtx);
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void createReturnTypeForUnionTest() throws Exception {
- final Class[] parameterTypes = { GeneratedTOBuilder.class, TypeDefinition.class, GeneratedTypeBuilder.class,
- Module.class, TypeProvider.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("createReturnTypeForUnion", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void createReturnTypeForUnionTest() {
final GeneratedTypeBuilder typeBuilder = new GeneratedTypeBuilderImpl("test.boolean.spc.def",
"spec-type-def", new ModuleContext());
- final SchemaContext schemaContext = YangParserTestUtils.parseYangSource("/base/test-union.yang");
+ final SchemaContext schemaContext = YangParserTestUtils.parseYangResource("/base/test-union.yang");
final TypeProviderImpl typeProvider = new TypeProviderImpl(schemaContext);
final LeafSchemaNode leafSchemaNode =
(LeafSchemaNode) schemaContext.getModules().iterator().next().getChildNodes().iterator().next();
final TypeDefinition<? extends TypeDefinition<?>> typeDef = leafSchemaNode.getType();
- final Object[] args1 = { addTOToBuilder("/base/test-union.yang"), typeDef, typeBuilder,
- schemaContext.getModules().iterator().next(), typeProvider };
- final Type result = (Type) generate.invoke(AuxiliaryGenUtils.class, args1);
+ final Type result = AuxiliaryGenUtils.createReturnTypeForUnion(addTOToBuilder("/base/test-union.yang"), typeDef,
+ typeBuilder, schemaContext.getModules().iterator().next(), typeProvider);
assertNotNull(result);
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void isInnerTypeTrueTest() throws Exception {
- final Class[] parameterTypes = { LeafSchemaNode.class, TypeDefinition.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("isInnerType", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void isInnerTypeTrueTest() {
final LeafSchemaNode leaf = mock(LeafSchemaNode.class);
- final TypeDefinition type = mock(TypeDefinition.class);
+ final TypeDefinition<?> type = mock(TypeDefinition.class);
final QName qname = QName.create("namespace", "2017-12-04", "localName");
final SchemaPath path = SchemaPath.create(true, qname);
when(leaf.getPath()).thenReturn(path);
when(type.getPath()).thenReturn(path);
- final Object[] args1 = { leaf, type };
- boolean result = (boolean) generate.invoke(AuxiliaryGenUtils.class, args1);
- assertNotNull(result);
- assertTrue(result);
+ assertTrue(AuxiliaryGenUtils.isInnerType(leaf, type));
final QName qnameParent = QName.create(qname, "qnameParent");
final SchemaPath parent = SchemaPath.create(true, qname, qnameParent);
when(type.getPath()).thenReturn(parent);
- final Object[] args2 = { leaf, type };
- result = (boolean) generate.invoke(AuxiliaryGenUtils.class, args2);
- assertNotNull(result);
- assertTrue(result);
+ assertTrue(AuxiliaryGenUtils.isInnerType(leaf, type));
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void isInnerTypeFalseTest() throws Exception {
- final Class[] parameterTypes = { LeafSchemaNode.class, TypeDefinition.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("isInnerType", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void isInnerTypeFalseTest() {
final LeafSchemaNode leaf = mock(LeafSchemaNode.class);
- final TypeDefinition type = mock(TypeDefinition.class);
+ final TypeDefinition<?> type = mock(TypeDefinition.class);
final QName qname = QName.create("namespace", "2017-12-04", "localName");
final SchemaPath path = SchemaPath.create(true, qname);
when(leaf.getPath()).thenReturn(path);
when(type.getPath()).thenReturn(parent);
- final Object[] args2 = { leaf, type };
- final boolean result = (boolean) generate.invoke(AuxiliaryGenUtils.class, args2);
- assertNotNull(result);
- assertTrue(!result);
+ assertFalse(AuxiliaryGenUtils.isInnerType(leaf, type));
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void resolveListKeyTOBuilderTest() throws Exception {
- final Class[] parameterTypes = { String.class, ListSchemaNode.class, ModuleContext.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("resolveListKeyTOBuilder", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void resolveListKeyTOBuilderTest() {
final String pckgName = "pckg.name.test";
final ListSchemaNode list = mock(ListSchemaNode.class);
final List<QName> keyDefs = new ArrayList<>();
when(list.getKeyDefinition()).thenReturn(keyDefs);
when(list.getQName()).thenReturn(qname);
- final Object[] args1 = { pckgName, list, new ModuleContext() };
- final GeneratedTOBuilder result = (GeneratedTOBuilder) generate.invoke(AuxiliaryGenUtils.class, args1);
+ final GeneratedTOBuilder result = AuxiliaryGenUtils.resolveListKeyTOBuilder(pckgName, list,
+ new ModuleContext());
assertNotNull(result);
assertEquals("LocalnameKey", result.getName());
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void resolveLeafSchemaNodeAsPropertyFalseTest() throws Exception {
- final Class[] parameterTypes = { String.class, GeneratedTOBuilder.class, LeafSchemaNode.class, Type.class, boolean.class };
- final Method generate =
- AuxiliaryGenUtils.class.getDeclaredMethod("resolveLeafSchemaNodeAsProperty", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void resolveLeafSchemaNodeAsPropertyFalseTest() {
final GeneratedTOBuilder gtob = mock(GeneratedTOBuilder.class);
final LeafSchemaNode leaf = mock(LeafSchemaNode.class);
final boolean isReadOnly = true;
final Type type = null;
- final Object[] args2 = { "list", gtob, leaf, type, isReadOnly };
- final boolean result = (boolean) generate.invoke(AuxiliaryGenUtils.class, args2);
- assertNotNull(result);
- assertTrue(!result);
+ assertFalse(AuxiliaryGenUtils.resolveLeafSchemaNodeAsProperty("list", gtob, leaf, type, isReadOnly));
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void resolveLeafSchemaNodeAsPropertyTrueTest() throws Exception {
- final Class[] parameterTypes = { String.class, GeneratedTOBuilder.class, LeafSchemaNode.class, Type.class, boolean.class };
- final Method generate =
- AuxiliaryGenUtils.class.getDeclaredMethod("resolveLeafSchemaNodeAsProperty", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void resolveLeafSchemaNodeAsPropertyTrueTest() {
final GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl("pckg.name.gto.tst", "gto_name", true);
final LeafSchemaNode leaf = mock(LeafSchemaNode.class);
+ when(leaf.getDescription()).thenReturn(Optional.empty());
+ when(leaf.getReference()).thenReturn(Optional.empty());
+
final boolean isReadOnly = true;
final Type type = mock(Type.class);
when(leaf.getQName()).thenReturn(QName.create("ns", "2017-12-04", "ln"));
- final Object[] args2 = { "list", gtob, leaf, type, isReadOnly };
- final boolean result = (boolean) generate.invoke(AuxiliaryGenUtils.class, args2);
- assertNotNull(result);
- assertTrue(result);
+ assertTrue(AuxiliaryGenUtils.resolveLeafSchemaNodeAsProperty("list", gtob, leaf, type, isReadOnly));
}
- @SuppressWarnings({ "rawtypes" })
@Test
- public void checkModuleAndModuleNameTest() throws Exception {
- final Class[] parameterTypes = { Module.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("checkModuleAndModuleName", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void checkModuleAndModuleNameTest() {
final Module module = mock(Module.class);
when(module.getName()).thenReturn("moduleName");
- final Object[] args2 = { module };
- generate.invoke(AuxiliaryGenUtils.class, args2);
+ AuxiliaryGenUtils.checkModuleAndModuleName(module);
}
- @SuppressWarnings("rawtypes")
- private String getterMethodName(final String schemaNodeName, final Type returnType)
- throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
- final Class[] parameterTypes =
- { String.class, Type.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("getterMethodName", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final Object[] args = { schemaNodeName, returnType };
- return (String) generate.invoke(AuxiliaryGenUtils.class, args);
- }
-
- @SuppressWarnings("rawtypes")
- private <T extends SchemaNode> boolean hasBuilderClass(final Class<T> clazz) throws Exception {
- final Class[] parameterTypes = { SchemaNode.class, BindingNamespaceType.class };
- final Method generate = AuxiliaryGenUtils.class.getDeclaredMethod("hasBuilderClass", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
- final T schemaNode = mock(clazz);
-
- final Object[] args = { schemaNode, BindingNamespaceType.Data };
- return (boolean) generate.invoke(AuxiliaryGenUtils.class, args);
+ private static <T extends SchemaNode> boolean hasBuilderClass(final Class<T> clazz) {
+ return AuxiliaryGenUtils.hasBuilderClass(mock(clazz), BindingNamespaceType.Data);
}
}
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.javav2.generator.api.BindingGenerator;
@Test
public void genTypesTypeDefTest() throws Exception {
final BindingGeneratorImpl bg = new BindingGeneratorImpl(false);
- final SchemaContext schemaContext = YangParserTestUtils.parseYangSource("/generator/test-typedef.yang");
+ final SchemaContext schemaContext = YangParserTestUtils.parseYangResource("/generator/test-typedef.yang");
final List<Type> generateTypes = bg.generateTypes(schemaContext);
assertNotNull(generateTypes);
for (final Type genType : generateTypes) {
@Test
public void generatedTypesEnumTest() throws Exception {
final BindingGenerator bg = new BindingGeneratorImpl(false);
- final SchemaContext context = YangParserTestUtils.parseYangSource("/generator/apple-test.yang");
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/generator/apple-test.yang");
final List<Type> generateTypes = bg.generateTypes(context);
assertNotNull(generateTypes);
assertTrue(!generateTypes.isEmpty());
}
@Test
- public void generatedTypesUsesEnumLeafTest() throws Exception {
+ public void generatedTypesUsesEnumLeafTest() {
final BindingGenerator bg = new BindingGeneratorImpl(false);
- final List<String> sources = new ArrayList<>();
- sources.add("/uses-statement/test-uses-leaf-innertype-base.yang");
- sources.add("/uses-statement/test-uses-leaf-innertype.yang");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sources);
+ final SchemaContext context = YangParserTestUtils.parseYangResources(BindingGeneratorImplTest.class,
+ "/uses-statement/test-uses-leaf-innertype-base.yang", "/uses-statement/test-uses-leaf-innertype.yang");
final List<Type> generateTypes = bg.generateTypes(context);
assertNotNull(generateTypes);
assertTrue(!generateTypes.isEmpty());
}
@Test
- public void generatedTypesUsesBitsLeafTest() throws Exception {
+ public void generatedTypesUsesBitsLeafTest() {
final BindingGenerator bg = new BindingGeneratorImpl(false);
- final List<String> sources = new ArrayList<>();
- sources.add("/uses-statement/test-uses-leaf-innertype2-base.yang");
- sources.add("/uses-statement/test-uses-leaf-innertype2.yang");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sources);
+ final SchemaContext context = YangParserTestUtils.parseYangResources(BindingGeneratorImplTest.class,
+ "/uses-statement/test-uses-leaf-innertype2-base.yang", "/uses-statement/test-uses-leaf-innertype2.yang");
final List<Type> generateTypes = bg.generateTypes(context);
assertNotNull(generateTypes);
assertTrue(!generateTypes.isEmpty());
}
@Test
- public void generatedTypesUsesUnionLeafTest() throws Exception {
+ public void generatedTypesUsesUnionLeafTest() {
final BindingGenerator bg = new BindingGeneratorImpl(false);
- final List<String> sources = new ArrayList<>();
- sources.add("/uses-statement/test-uses-leaf-innertype2-base.yang");
- sources.add("/uses-statement/test-uses-leaf-innertype2.yang");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sources);
+ final SchemaContext context = YangParserTestUtils.parseYangResources(BindingGeneratorImplTest.class,
+ "/uses-statement/test-uses-leaf-innertype2-base.yang", "/uses-statement/test-uses-leaf-innertype2.yang");
final List<Type> generateTypes = bg.generateTypes(context);
assertNotNull(generateTypes);
assertTrue(!generateTypes.isEmpty());
}
@Test
- public void generatedTypesUsesLeafTest() throws Exception {
+ public void generatedTypesUsesLeafTest() {
final BindingGenerator bg = new BindingGeneratorImpl(false);
- final List<String> sources = new ArrayList<>();
- sources.add("/uses-statement/test-uses-leaf-innertype2-base.yang");
- sources.add("/uses-statement/test-uses-leaf-innertype2.yang");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sources);
+ final SchemaContext context = YangParserTestUtils.parseYangResources(BindingGeneratorImplTest.class,
+ "/uses-statement/test-uses-leaf-innertype2-base.yang", "/uses-statement/test-uses-leaf-innertype2.yang");
final List<Type> generateTypes = bg.generateTypes(context);
assertNotNull(generateTypes);
assertTrue(!generateTypes.isEmpty());
}
@Test
- public void generatedTypesUsesLeafInnertype3Test() throws Exception {
+ public void generatedTypesUsesLeafInnertype3Test() {
final BindingGenerator bg = new BindingGeneratorImpl(false);
- final List<String> sources = new ArrayList<>();
- sources.add("/uses-statement/test-uses-leaf-innertype3-base.yang");
- sources.add("/uses-statement/test-uses-leaf-innertype3.yang");
- final SchemaContext context = YangParserTestUtils.parseYangSources(sources);
+ final SchemaContext context = YangParserTestUtils.parseYangResources(BindingGeneratorImplTest.class,
+ "/uses-statement/test-uses-leaf-innertype3-base.yang",
+ "/uses-statement/test-uses-leaf-innertype3.yang");
final List<Type> generateTypes = bg.generateTypes(context);
assertNotNull(generateTypes);
assertTrue(!generateTypes.isEmpty());
}
@Test
- public void generatedTypesTest() throws Exception {
+ public void generatedTypesTest() {
final BindingGenerator bg = new BindingGeneratorImpl(false);
- final SchemaContext context = YangParserTestUtils.parseYangSource("/generator/test-list.yang");
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/generator/test-list.yang");
final List<Type> generateTypes = bg.generateTypes(context);
assertNotNull(generateTypes);
}
@Test
- public void generateTypesDescriptionsTest() throws Exception {
+ public void generateTypesDescriptionsTest() {
final BindingGenerator bg = new BindingGeneratorImpl(true);
- final SchemaContext context = YangParserTestUtils.parseYangSources("/base/with_import/");
+ final SchemaContext context = YangParserTestUtils.parseYangResourceDirectory("/base/with_import/");
assertNotNull(context);
final List<Type> generateTypes = bg.generateTypes(context, context.getModules());
@Test
public void generateTypesIdentityTest() throws Exception {
final BindingGenerator bg = new BindingGeneratorImpl(true);
- final SchemaContext context = YangParserTestUtils.parseYangSources("/identity/");
+ final SchemaContext context = YangParserTestUtils.parseYangResourceDirectory("/identity/");
assertNotNull(context);
final List<Type> generateTypes = bg.generateTypes(context, context.getModules());
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+import java.util.List;
import org.junit.Test;
import org.opendaylight.mdsal.binding.javav2.generator.api.BindingGenerator;
import org.opendaylight.mdsal.binding.javav2.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-import java.util.List;
public class Bug8542Test {
@Test
- public void Bug8542Test() throws Exception {
+ public void testBug8542() {
final BindingGenerator bg = new BindingGeneratorImpl(false);
- final SchemaContext context = YangParserTestUtils.parseYangSource("/bug-8542/recursive-uses-augment.yang");
+ final SchemaContext context = YangParserTestUtils.parseYangResource("/bug-8542/recursive-uses-augment.yang");
final List<Type> generateTypes = bg.generateTypes(context);
assertNotNull(generateTypes);
assertTrue(!generateTypes.isEmpty());
* 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.mdsal.binding.javav2.generator.impl;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import java.lang.reflect.Method;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.UsesNode;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-import java.io.File;
-import java.lang.reflect.Method;
-
public class Bug8575Test {
@Test
public void bug8575Test() throws Exception {
- final Class[] parameterTypes = { SchemaContext.class, SchemaPath.class, UsesNode.class };
+ final Class<?>[] parameterTypes = { SchemaContext.class, SchemaPath.class, UsesNode.class };
final Method generate =
AugmentToGenType.class.getDeclaredMethod("findOriginalTargetFromGrouping", parameterTypes);
assertNotNull(generate);
generate.setAccessible(true);
- File foo = new File(getClass().getResource(
- "/bug-8575/foo.yang").toURI());
-
- SchemaContext context = YangParserTestUtils.parseYangSources(foo);
+ SchemaContext context = YangParserTestUtils.parseYangResource("/bug-8575/foo.yang");
final QName groupingQname = QName.create("foo", "2017-05-15", "A");
final QName containerQname = QName.create("foo", "2017-05-15", "A1");
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.base.Optional;
import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
public class RpcActionGenHelperTest {
+ // Bridge for method references
+ @FunctionalInterface
+ private static interface GeneratorMethod {
+ Map<Module, ModuleContext> generate(Module module, Map<Module, ModuleContext> genCtx,
+ SchemaContext schemaContext, boolean verboseClassComments,
+ Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, TypeProvider typeProvider);
+ }
- @SuppressWarnings("unchecked")
@Test(expected = UnsupportedOperationException.class)
public void constructorTest() throws Throwable {
- final Constructor<RpcActionGenHelper> constructor =
- (Constructor<RpcActionGenHelper>) RpcActionGenHelper.class.getDeclaredConstructors()[0];
+ final Constructor<RpcActionGenHelper> constructor = RpcActionGenHelper.class.getDeclaredConstructor();
constructor.setAccessible(true);
- final Object[] objs = {};
try {
- constructor.newInstance(objs);
+ constructor.newInstance();
} catch (final Exception e) {
throw e.getCause();
}
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void getRoutingContextAbsentTest() throws Exception {
- final Class[] parameterTypes = { DataSchemaNode.class };
- final Method generate = RpcActionGenHelper.class.getDeclaredMethod("getRoutingContext", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
+ public void getRoutingContextAbsentTest() {
final DataSchemaNode dataSchemaNode = mock(DataSchemaNode.class);
final List<UnknownSchemaNode> unknownSchemaNodes = new ArrayList<>();
when(dataSchemaNode.getUnknownSchemaNodes()).thenReturn(unknownSchemaNodes);
- final Object[] args = { dataSchemaNode };
- final Optional<QName> result = (Optional<QName>) generate.invoke(RpcActionGenHelper.class, args);
+ final Optional<QName> result = RpcActionGenHelper.getRoutingContext(dataSchemaNode);
assertNotNull(result);
assertTrue(!result.isPresent());
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void getRoutingContextTest() throws Exception {
- final Class[] parameterTypes = { DataSchemaNode.class };
- final Method generate = RpcActionGenHelper.class.getDeclaredMethod("getRoutingContext", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void getRoutingContextTest() {
final DataSchemaNode dataSchemaNode = mock(DataSchemaNode.class);
final List<UnknownSchemaNode> unknownSchemaNodes = new ArrayList<>();
- final Field contextRef = RpcActionGenHelper.class.getDeclaredField("CONTEXT_REFERENCE");
- contextRef.setAccessible(true);
- final QName nodeType = (QName) contextRef.get(RpcActionGenHelper.class);
final UnknownSchemaNode unknownSchemaNode = mock(UnknownSchemaNode.class);
- when(unknownSchemaNode.getNodeType()).thenReturn(nodeType);
+ when(unknownSchemaNode.getNodeType()).thenReturn(RpcActionGenHelper.CONTEXT_REFERENCE);
final QName qname = QName.create("test", "2017-05-04", "unknown");
when(unknownSchemaNode.getQName()).thenReturn(qname);
unknownSchemaNodes.add(unknownSchemaNode);
when(dataSchemaNode.getUnknownSchemaNodes()).thenReturn(unknownSchemaNodes);
- final Object[] args = { dataSchemaNode };
- final Optional<QName> result = (Optional<QName>) generate.invoke(RpcActionGenHelper.class, args);
+ final Optional<QName> result = RpcActionGenHelper.getRoutingContext(dataSchemaNode);
assertNotNull(result);
assertTrue(result.isPresent());
assertEquals(qname, result.get());
@Ignore
@Test
- public void actionMethodsToGenTypeContainerAsParentTest() throws Exception {
+ public void actionMethodsToGenTypeContainerAsParentTest() {
actionMethodsToGenType(ContainerSchemaNode.class, false);
}
@Ignore
@Test
- public void actionMethodsToGenTypeListAsParentTest() throws Exception {
+ public void actionMethodsToGenTypeListAsParentTest() {
actionMethodsToGenType(ListSchemaNode.class, false);
}
- @SuppressWarnings("rawtypes")
- @Test
- public void rpcMethodsToGenTypeNullRpcsTest() throws Exception {
- final Class[] parameterTypes =
- { Module.class, Map.class, SchemaContext.class, boolean.class, Map.class, TypeProvider.class };
- final Method generate = RpcActionGenHelper.class.getDeclaredMethod("rpcMethodsToGenType", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ @Test(expected = IllegalStateException.class)
+ public void rpcMethodsToGenTypeNullRpcsTest() {
final QName rpcQName = QName.create("test.rpc", "2017-05-04", "rpc-test");
final Module module = mock(Module.class);
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
final TypeProvider typeProvider = mock(TypeProvider.class);
- final Object[] args = { module, genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider };
-
- try {
- generate.invoke(RpcActionGenHelper.class, args);
- fail();
- } catch (final Exception e) {
- assertNotNull(e);
- assertTrue(e instanceof InvocationTargetException);
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause instanceof IllegalStateException);
- }
+ RpcActionGenHelper.rpcMethodsToGenType(module, genCtx, schemaContext, verboseClassComments, genTypeBuilders,
+ typeProvider);
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void rpcMethodsToGenTypeEmptyRpcsTest() throws Exception {
- final Class[] parameterTypes =
- { Module.class, Map.class, SchemaContext.class, boolean.class, Map.class, TypeProvider.class };
- final Method generate = RpcActionGenHelper.class.getDeclaredMethod("rpcMethodsToGenType", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void rpcMethodsToGenTypeEmptyRpcsTest() {
final QName rpcQName = QName.create("test.rpc", "2017-05-04", "rpc-test");
final Module module = mock(Module.class);
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
final TypeProvider typeProvider = mock(TypeProvider.class);
- final Object[] args = { module, genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider };
- final Map<Module, ModuleContext> result =
- (Map<Module, ModuleContext>) generate.invoke(RpcActionGenHelper.class, args);
+ final Map<Module, ModuleContext> result = RpcActionGenHelper.rpcMethodsToGenType(module, genCtx, schemaContext,
+ verboseClassComments, genTypeBuilders, typeProvider);
assertNotNull(result);
}
@Test
- public void rpcMethodsToGenTypeRoutedRpcTest() throws Exception {
+ public void rpcMethodsToGenTypeRoutedRpcTest() {
actionMethodsToGenType(ContainerSchemaNode.class, true);
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void rpcMethodsToGenTypeRpcTest() throws Exception {
- final Class[] parameterTypes =
- { Module.class, Map.class, SchemaContext.class, boolean.class, Map.class, TypeProvider.class };
- final Method generate = RpcActionGenHelper.class.getDeclaredMethod("rpcMethodsToGenType", parameterTypes);
- assertNotNull(generate);
- generate.setAccessible(true);
-
+ public void rpcMethodsToGenTypeRpcTest() {
final QName rpcQName = QName.create("test.rpc", "2017-05-04", "rpc-test");
final ContainerSchemaNode rpcParent = mock(ContainerSchemaNode.class);
when(module.getName()).thenReturn("module-name");
when(module.getRevision()).thenReturn(rpcQName.getRevision());
when(module.getNamespace()).thenReturn(rpcQName.getNamespace());
+ when(module.getDescription()).thenReturn(java.util.Optional.empty());
+ when(module.getReference()).thenReturn(java.util.Optional.empty());
final Set<RpcDefinition> rpcs = new HashSet<>();
final RpcDefinition rpcDefinition = mock(RpcDefinition.class);
+ when(rpcDefinition.getDescription()).thenReturn(java.util.Optional.empty());
+ when(rpcDefinition.getReference()).thenReturn(java.util.Optional.empty());
final SchemaPath rpcPath = SchemaPath.create(true, rpcParentQName, rpcQName);
when(rpcDefinition.getPath()).thenReturn(rpcPath);
when(rpcDefinition.getQName()).thenReturn(rpcQName);
+
when(module.getDataChildByName(rpcParentQName)).thenReturn(rpcParent);
rpcs.add(rpcDefinition);
when(module.getRpcs()).thenReturn(rpcs);
final SchemaPath inputSchemaPath = SchemaPath.create(true, rpcQName, qnameInput);
when(input.getQName()).thenReturn(qnameInput);
when(input.getPath()).thenReturn(inputSchemaPath);
+ when(input.getDescription()).thenReturn(java.util.Optional.empty());
+ when(input.getReference()).thenReturn(java.util.Optional.empty());
+
when(rpcDefinition.getInput()).thenReturn(input);
final ContainerSchemaNode output = mock(ContainerSchemaNode.class);
final SchemaPath outputSchemaPath = SchemaPath.create(true, rpcQName, qnameOutput);
when(output.getQName()).thenReturn(qnameOutput);
when(output.getPath()).thenReturn(outputSchemaPath);
+ when(output.getDescription()).thenReturn(java.util.Optional.empty());
+ when(output.getReference()).thenReturn(java.util.Optional.empty());
when(rpcDefinition.getOutput()).thenReturn(output);
final Map<Module, ModuleContext> genCtx = new HashMap<>();
genCtx.put(module, moduleContext);
final SchemaContext schemaContext = mock(SchemaContext.class);
- when(schemaContext.findModuleByNamespaceAndRevision(rpcQName.getNamespace(), rpcQName.getRevision()))
- .thenReturn(module);
+ when(schemaContext.findModule(rpcQName.getModule())).thenReturn(java.util.Optional.of(module));
final boolean verboseClassComments = false;
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
final TypeProvider typeProvider = mock(TypeProvider.class);
- final Object[] args = { module, genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider };
- final Map<Module, ModuleContext> result =
- (Map<Module, ModuleContext>) generate.invoke(RpcActionGenHelper.class, args);
+ final Map<Module, ModuleContext> result = RpcActionGenHelper.rpcMethodsToGenType(module, genCtx, schemaContext,
+ verboseClassComments, genTypeBuilders, typeProvider);
assertNotNull(result);
}
- @SuppressWarnings({ "unchecked", "rawtypes" })
- private <T extends ActionNodeContainer> void actionMethodsToGenType(final Class<T> clazz,
- final boolean isRoutedRpc) throws Exception {
- final Class[] parameterTypes =
- { Module.class, Map.class, SchemaContext.class, boolean.class, Map.class, TypeProvider.class };
- Method generate;
+ private static <T extends ActionNodeContainer> void actionMethodsToGenType(final Class<T> clazz,
+ final boolean isRoutedRpc) {
+ final GeneratorMethod generate;
if (isRoutedRpc) {
- generate = RpcActionGenHelper.class.getDeclaredMethod("rpcMethodsToGenType", parameterTypes);
+ generate = RpcActionGenHelper::rpcMethodsToGenType;
} else {
- generate = RpcActionGenHelper.class.getDeclaredMethod("actionMethodsToGenType", parameterTypes);
+ generate = RpcActionGenHelper::actionMethodsToGenType;
}
- assertNotNull(generate);
- generate.setAccessible(true);
final QName actionQName = QName.create("test.action", "2017-05-04", "action-test");
when(module.getName()).thenReturn("module-name");
when(module.getRevision()).thenReturn(actionQName.getRevision());
when(module.getNamespace()).thenReturn(actionQName.getNamespace());
+ when(module.getDescription()).thenReturn(java.util.Optional.empty());
+ when(module.getReference()).thenReturn(java.util.Optional.empty());
final Collection<DataSchemaNode> childNodes = new ArrayList<>();
final T actionNodeContainer = mock(clazz);
when(actionDefinition.getQName()).thenReturn(actionQName);
final SchemaPath actionPath = SchemaPath.create(true, actionQName);
when(actionDefinition.getPath()).thenReturn(actionPath);
+ when(actionDefinition.getDescription()).thenReturn(java.util.Optional.empty());
+ when(actionDefinition.getReference()).thenReturn(java.util.Optional.empty());
final ContainerSchemaNode input = mock(ContainerSchemaNode.class);
final QName qnameInput = QName.create(actionQName, "action-input");
final SchemaPath inputSchemaPath = SchemaPath.create(true, actionQName, qnameInput);
when(input.getQName()).thenReturn(qnameInput);
when(input.getPath()).thenReturn(inputSchemaPath);
+ when(input.getDescription()).thenReturn(java.util.Optional.empty());
+ when(input.getReference()).thenReturn(java.util.Optional.empty());
when(actionDefinition.getInput()).thenReturn(input);
final ContainerSchemaNode output = mock(ContainerSchemaNode.class);
final SchemaPath outputSchemaPath = SchemaPath.create(true, actionQName, qnameOutput);
when(output.getQName()).thenReturn(qnameOutput);
when(output.getPath()).thenReturn(outputSchemaPath);
+ when(output.getDescription()).thenReturn(java.util.Optional.empty());
+ when(output.getReference()).thenReturn(java.util.Optional.empty());
when(actionDefinition.getOutput()).thenReturn(output);
actions.add(actionDefinition);
genCtx.put(module, moduleContext);
final SchemaContext schemaContext = mock(SchemaContext.class);
- when(schemaContext.findModuleByNamespaceAndRevision(actionQName.getNamespace(), actionQName.getRevision()))
- .thenReturn(module);
+ when(schemaContext.findModule(actionQName.getModule())).thenReturn(java.util.Optional.of(module));
final boolean verboseClassComments = false;
final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
final RpcDefinition rpcDef = mock(RpcDefinition.class);
when(rpcDef.getPath()).thenReturn(outputSchemaPath);
when(rpcDef.getQName()).thenReturn(qnameOutput);
+ when(rpcDef.getDescription()).thenReturn(java.util.Optional.empty());
+ when(rpcDef.getReference()).thenReturn(java.util.Optional.empty());
+
when(module.getDataChildByName(actionQName)).thenReturn((ContainerSchemaNode) actionNodeContainer);
final List<UnknownSchemaNode> unknownSchemaNodes = new ArrayList<>();
final UnknownSchemaNode unknownSchemaNode = mock(UnknownSchemaNode.class);
- final Field contextRef = RpcActionGenHelper.class.getDeclaredField("CONTEXT_REFERENCE");
- contextRef.setAccessible(true);
- final QName nodeType = (QName) contextRef.get(RpcActionGenHelper.class);
- when(unknownSchemaNode.getNodeType()).thenReturn(nodeType);
- when(unknownSchemaNode.getQName()).thenReturn(nodeType);
+ when(unknownSchemaNode.getNodeType()).thenReturn(RpcActionGenHelper.CONTEXT_REFERENCE);
+ when(unknownSchemaNode.getQName()).thenReturn(RpcActionGenHelper.CONTEXT_REFERENCE);
unknownSchemaNodes.add(unknownSchemaNode);
when(((DataSchemaNode) actionNodeContainer).getUnknownSchemaNodes()).thenReturn(unknownSchemaNodes);
when(rpcDef.getInput()).thenReturn(input);
when(module.getRpcs()).thenReturn(rpcs);
}
- final Object[] args = { module, genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider };
- final Map<Module, ModuleContext> result =
- (Map<Module, ModuleContext>) generate.invoke(RpcActionGenHelper.class, args);
+ final Map<Module, ModuleContext> result = generate.generate(module, genCtx, schemaContext, verboseClassComments,
+ genTypeBuilders, typeProvider);
assertNotNull(result);
}
}
import static org.junit.Assert.assertTrue;
import com.google.common.annotations.Beta;
-import java.io.FileNotFoundException;
-import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.Set;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.mdsal.binding.javav2.generator.impl.txt.yangTemplateForModule;
import org.opendaylight.mdsal.binding.javav2.generator.util.YangSnippetCleaner;
import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
@Beta
private Set<Module> modules;
@Before
- public void setup() throws URISyntaxException, ReactorException, FileNotFoundException {
- this.modules = YangParserTestUtils.parseYangSources("/yang-template").getModules();
+ public void setup() {
+ this.modules = YangParserTestUtils.parseYangResourceDirectory("/yang-template").getModules();
}
@Test
moduleBody = yangTemplateForModule.render(iterator.next()).body().trim();
cleanedModuleBody = YangSnippetCleaner.clean(moduleBody);
+ System.out.println(cleanedModuleBody);
assertTrue(cleanedModuleBody.contains("module yang-template-test {"));
- assertTrue(cleanedModuleBody
- .contains(" import yang-template-import { prefix \"yti\"; revision-date 2016-06-23; }"));
+ assertTrue(cleanedModuleBody.contains(" import yang-template-import {"));
+ assertTrue(cleanedModuleBody.contains(" prefix \"yti\";"));
+ assertTrue(cleanedModuleBody.contains(" revision-date 2016-06-23;"));
+ assertTrue(cleanedModuleBody.contains(" }"));
assertTrue(cleanedModuleBody.contains(" anydata simple-anydata;"));
assertTrue(cleanedModuleBody.contains(" container simple-container-with-action {"));
assertTrue(cleanedModuleBody.contains(" leaf-list simple-leaf-list {"));
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
+import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
+import java.util.Optional;
import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier;
import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions;
import org.opendaylight.mdsal.binding.javav2.model.api.Type;
import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.TypeMemberBuilder;
import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
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.api.type.RangeRestrictedTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
import org.opendaylight.yangtools.yang.model.util.type.DecimalTypeBuilder;
private static final Restrictions EMPTY_RESTRICTIONS = new Restrictions() {
@Override
- public List<LengthConstraint> getLengthConstraints() {
- return Collections.emptyList();
+ public Optional<LengthConstraint> getLengthConstraint() {
+ return Optional.empty();
}
@Override
}
@Override
- public List<RangeConstraint> getRangeConstraints() {
- return Collections.emptyList();
+ public Optional<RangeConstraint<?>> getRangeConstraint() {
+ return Optional.empty();
}
@Override
}
for (final MethodSignatureBuilder m : sortedCollection(SUID_MEMBER_COMPARATOR, to.getMethodDefinitions())) {
- if (!(m.getAccessModifier().equals(AccessModifier.PRIVATE))) {
+ if (!m.getAccessModifier().equals(AccessModifier.PRIVATE)) {
dout.writeUTF(m.getName());
dout.write(m.getAccessModifier().ordinal());
}
final byte[] hashBytes = SHA1_MD.get().digest(bout.toByteArray());
long hash = 0;
for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
- hash = (hash << 8) | (hashBytes[i] & 0xFF);
+ hash = hash << 8 | hashBytes[i] & 0xFF;
}
return hash;
}
}
public static Restrictions getRestrictions(final TypeDefinition<?> type) {
- if ((type == null) || (type.getBaseType() == null)) {
+ if (type == null || type.getBaseType() == null) {
if (type instanceof DecimalTypeDefinition) {
final DecimalTypeDefinition decimal = (DecimalTypeDefinition) type;
final DecimalTypeBuilder tmpBuilder = BaseTypes.decimalTypeBuilder(decimal.getPath());
tmpBuilder.setFractionDigits(decimal.getFractionDigits());
final DecimalTypeDefinition tmp = tmpBuilder.build();
- if (!tmp.getRangeConstraints().equals(decimal.getRangeConstraints())) {
+ if (!tmp.getRangeConstraint().equals(decimal.getRangeConstraint())) {
return new Restrictions() {
@Override
public boolean isEmpty() {
}
@Override
- public List<RangeConstraint> getRangeConstraints() {
- return decimal.getRangeConstraints();
+ public Optional<RangeConstraint<BigDecimal>> getRangeConstraint() {
+ return decimal.getRangeConstraint();
}
@Override
}
@Override
- public List<LengthConstraint> getLengthConstraints() {
- return ImmutableList.of();
+ public Optional<LengthConstraint> getLengthConstraint() {
+ return Optional.empty();
}
};
}
return EMPTY_RESTRICTIONS;
}
- final List<LengthConstraint> length;
+ final Optional<LengthConstraint> length;
final List<PatternConstraint> pattern;
- final List<RangeConstraint> range;
+ final Optional<? extends RangeConstraint<?>> range;
/*
* Take care of extended types.
if (type instanceof BinaryTypeDefinition) {
final BinaryTypeDefinition binary = (BinaryTypeDefinition)type;
final BinaryTypeDefinition base = binary.getBaseType();
- if ((base != null) && (base.getBaseType() != null)) {
- length = currentOrEmpty(binary.getLengthConstraints(), base.getLengthConstraints());
+ if (base != null && base.getBaseType() != null) {
+ length = currentOrEmpty(binary.getLengthConstraint(), base.getLengthConstraint());
} else {
- length = binary.getLengthConstraints();
+ length = binary.getLengthConstraint();
}
pattern = ImmutableList.of();
- range = ImmutableList.of();
+ range = Optional.empty();
} else if (type instanceof DecimalTypeDefinition) {
- length = ImmutableList.of();
+ length = Optional.empty();
pattern = ImmutableList.of();
final DecimalTypeDefinition decimal = (DecimalTypeDefinition)type;
final DecimalTypeDefinition base = decimal.getBaseType();
- if ((base != null) && (base.getBaseType() != null)) {
- range = currentOrEmpty(decimal.getRangeConstraints(), base.getRangeConstraints());
+ if (base != null && base.getBaseType() != null) {
+ range = currentOrEmpty(decimal.getRangeConstraint(), base.getRangeConstraint());
} else {
- range = decimal.getRangeConstraints();
+ range = decimal.getRangeConstraint();
}
- } else if (type instanceof IntegerTypeDefinition) {
- length = ImmutableList.of();
+ } else if (type instanceof RangeRestrictedTypeDefinition) {
+ // Integer-like types
+ length = Optional.empty();
pattern = ImmutableList.of();
-
- final IntegerTypeDefinition integer = (IntegerTypeDefinition)type;
- final IntegerTypeDefinition base = integer.getBaseType();
- if ((base != null) && (base.getBaseType() != null)) {
- range = currentOrEmpty(integer.getRangeConstraints(), base.getRangeConstraints());
- } else {
- range = integer.getRangeConstraints();
- }
+ range = extractRangeConstraint((RangeRestrictedTypeDefinition<?, ?>)type);
} else if (type instanceof StringTypeDefinition) {
final StringTypeDefinition string = (StringTypeDefinition)type;
final StringTypeDefinition base = string.getBaseType();
- if ((base != null) && (base.getBaseType() != null)) {
- length = currentOrEmpty(string.getLengthConstraints(), base.getLengthConstraints());
+ if (base != null && base.getBaseType() != null) {
+ length = currentOrEmpty(string.getLengthConstraint(), base.getLengthConstraint());
} else {
- length = string.getLengthConstraints();
+ length = string.getLengthConstraint();
}
pattern = uniquePatterns(string);
- range = ImmutableList.of();
- } else if (type instanceof UnsignedIntegerTypeDefinition) {
- length = ImmutableList.of();
- pattern = ImmutableList.of();
-
- final UnsignedIntegerTypeDefinition unsigned = (UnsignedIntegerTypeDefinition)type;
- final UnsignedIntegerTypeDefinition base = unsigned.getBaseType();
- if ((base != null) && (base.getBaseType() != null)) {
- range = currentOrEmpty(unsigned.getRangeConstraints(), base.getRangeConstraints());
- } else {
- range = unsigned.getRangeConstraints();
- }
+ range = Optional.empty();
} else {
- length = ImmutableList.of();
+ length = Optional.empty();
pattern = ImmutableList.of();
- range = ImmutableList.of();
+ range = Optional.empty();
}
// Now, this may have ended up being empty, too...
- if (length.isEmpty() && pattern.isEmpty() && range.isEmpty()) {
+ if (!length.isPresent() && pattern.isEmpty() && !range.isPresent()) {
return EMPTY_RESTRICTIONS;
}
// Nope, not empty allocate a holder
return new Restrictions() {
@Override
- public List<RangeConstraint> getRangeConstraints() {
+ public Optional<? extends RangeConstraint<?>> getRangeConstraint() {
return range;
}
@Override
return pattern;
}
@Override
- public List<LengthConstraint> getLengthConstraints() {
+ public Optional<LengthConstraint> getLengthConstraint() {
return length;
}
@Override
* @throws NullPointerException if any of the arguments are null
*/
public static String packageNameForAugmentedGeneratedType(final String parentAugmentPackageName,
- final AugmentationSchema augmentationSchema) {
+ final AugmentationSchemaNode augmentationSchema) {
final QName last = augmentationSchema.getTargetPath().getLastComponent();
return generateNormalizedPackageName(parentAugmentPackageName, last);
}
}
- private static <T> List<T> currentOrEmpty(final List<T> current, final List<T> base) {
- return current.equals(base) ? ImmutableList.of() : current;
+ private static <T extends Optional<?>> T currentOrEmpty(final T current, final T base) {
+ return current.equals(base) ? (T)Optional.empty() : current;
}
private static List<PatternConstraint> uniquePatterns(final StringTypeDefinition type) {
return false;
}
+
+ private static <T extends RangeRestrictedTypeDefinition<?, ?>> Optional<? extends RangeConstraint<?>>
+ extractRangeConstraint(final T def) {
+ final T base = (T) def.getBaseType();
+ if (base != null && base.getBaseType() != null) {
+ return currentOrEmpty(def.getRangeConstraint(), base.getRangeConstraint());
+ }
+
+ return def.getRangeConstraint();
+ }
+
}
import com.google.common.annotations.Beta;
import com.google.common.base.CharMatcher;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.Iterables;
-import java.util.Collections;
+import com.google.common.collect.Range;
+import com.google.common.collect.RangeSet;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
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.BaseConstraints;
import org.w3c.dom.Document;
@Beta
public static ConcreteType typeForClass(final Class<?> cls, final Restrictions restrictions) {
- if (restrictions != null) {
- if (restrictions instanceof DefaultRestrictions) {
- return new ConcreteTypeImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions);
- } else {
- return new BaseTypeWithRestrictionsImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions);
- }
- } else {
+ if (restrictions == null) {
return typeForClass(cls);
}
+ if (restrictions instanceof DefaultRestrictions) {
+ return new ConcreteTypeImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions);
+ } else {
+ return new BaseTypeWithRestrictionsImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions);
+ }
}
public static ConcreteType typeForClass(final Class<?> cls, final Restrictions restrictions,
final ModuleContext moduleContext) {
- if (restrictions != null) {
- if (restrictions instanceof DefaultRestrictions) {
- return new ConcreteTypeImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions);
- } else {
- return new BaseTypeWithRestrictionsImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions,
- moduleContext);
- }
- } else {
+ if (restrictions == null) {
return typeForClass(cls);
}
+ if (restrictions instanceof DefaultRestrictions) {
+ return new ConcreteTypeImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions);
+ } else {
+ return new BaseTypeWithRestrictionsImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions,
+ moduleContext);
+ }
}
/**
* <code>packageName</code> and <code>typeName</code>
*/
public static WildcardType wildcardTypeFor(final String packageName, final String typeName,
- final boolean isPkNameNormalized, final boolean isTypeNormalized, ModuleContext context) {
+ final boolean isPkNameNormalized, final boolean isTypeNormalized, final ModuleContext context) {
return new WildcardTypeImpl(packageName, typeName, isPkNameNormalized, isTypeNormalized, context);
}
@Nullable
public static String getOuterClassName(final Type valueType) {
final String pkgName = valueType.getPackageName();
- final int index = CharMatcher.JAVA_UPPER_CASE.indexIn(pkgName);
+ final int index = CharMatcher.javaUpperCase().indexIn(pkgName);
if (index >= 0) {
// It is inner class.
return Iterables.getFirst(DOT_SPLITTER.split(pkgName.substring(index)), null);
@Nullable
public static String getOuterClassPackageName(final Type valueType) {
final String pkgName = valueType.getPackageName();
- final int index = CharMatcher.JAVA_UPPER_CASE.indexIn(pkgName);
+ final int index = CharMatcher.javaUpperCase().indexIn(pkgName);
if (index >= 1) {
return pkgName.substring(0, index - 1);
}
* if the type name has been normalized
*/
public WildcardTypeImpl(final String packageName, final String typeName, final boolean isPkNameNormalized,
- final boolean isTypeNormalized, ModuleContext context) {
+ final boolean isTypeNormalized, final ModuleContext context) {
super(packageName, typeName, isPkNameNormalized, isTypeNormalized, context);
}
}
- public static <T extends Number> DefaultRestrictions<T> getDefaultRestrictions(final T min, final T max) {
+ public static <T extends Number & Comparable<T>> DefaultRestrictions<T> getDefaultRestrictions(final T min,
+ final T max) {
return new DefaultRestrictions<>(min, max);
}
- private static final class DefaultRestrictions<T extends Number> implements Restrictions {
- private final List<RangeConstraint> rangeConstraints;
+ private static final class DefaultRestrictions<T extends Number & Comparable<T>> implements Restrictions {
+ private final RangeConstraint<T> rangeConstraint;
private DefaultRestrictions(final T min, final T max) {
Preconditions.checkNotNull(min);
Preconditions.checkNotNull(max);
- this.rangeConstraints = Collections.singletonList(BaseConstraints.newRangeConstraint(min, max, Optional
- .absent(), Optional.absent()));
+ this.rangeConstraint = new RangeConstraint<T>() {
+
+ @Override
+ public Optional<String> getErrorAppTag() {
+ return Optional.empty();
+ }
+
+ @Override
+ public Optional<String> getErrorMessage() {
+ return Optional.empty();
+ }
+
+ @Override
+ public Optional<String> getDescription() {
+ return Optional.empty();
+ }
+
+ @Override
+ public Optional<String> getReference() {
+ return Optional.empty();
+ }
+
+ @Override
+ public RangeSet<T> getAllowedRanges() {
+ return ImmutableRangeSet.of(Range.closed(min, max));
+ }
+ };
}
@Override
}
@Override
- public List<RangeConstraint> getRangeConstraints() {
- return this.rangeConstraints;
+ public Optional<RangeConstraint<?>> getRangeConstraint() {
+ return Optional.ofNullable(rangeConstraint);
}
@Override
}
@Override
- public List<LengthConstraint> getLengthConstraints() {
- return ImmutableList.of();
+ public Optional<LengthConstraint> getLengthConstraint() {
+ return Optional.empty();
}
}
}
private String moduleName;
private List<QName> schemaPath;
- public EnumerationBuilderImpl(final String packageName, final String name, ModuleContext context) {
+ public EnumerationBuilderImpl(final String packageName, final String name, final ModuleContext context) {
super(packageName, name, context);
}
public EnumerationBuilderImpl(final String packageName, final String name, final boolean isPkNameNormalized,
- final boolean isTypeNormalized, ModuleContext context) {
+ final boolean isTypeNormalized, final ModuleContext context) {
super(packageName, name, isPkNameNormalized, isTypeNormalized, context);
}
final List<EnumPair> enums = enumTypeDef.getValues();
if (enums != null) {
enums.stream().filter(enumPair -> enumPair != null).forEach(enumPair -> this.addValue(enumPair.getName(),
- enumPair.getValue(), enumPair.getDescription(), enumPair.getReference(), enumPair.getStatus()));
+ enumPair.getValue(), enumPair.getDescription().orElse(null), enumPair.getReference().orElse(null),
+ enumPair.getStatus()));
}
}
@Nullable
@Override
- public String getDescription() {
- return this.description;
+ public Optional<String> getDescription() {
+ return Optional.ofNullable(this.description);
}
@Nullable
@Override
- public String getReference() {
- return this.reference;
+ public Optional<String> getReference() {
+ return Optional.ofNullable(this.reference);
}
@Nonnull
builder.append(" (");
builder.append(valPair.getValue());
- if (i == (this.values.size() - 1)) {
+ if (i == this.values.size() - 1) {
builder.append(" );");
} else {
builder.append(" ),");
package org.opendaylight.mdsal.binding.javav2.java.api.generator.rangeGenerators;
import com.google.common.collect.Range;
-import java.util.Collection;
+import java.util.Set;
import javax.annotation.Nonnull;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
}
@Override
- protected final String generateRangeCheckerImplementation(final String checkerName, @Nonnull final Collection<RangeConstraint> constraints) {
+ protected final String generateRangeCheckerImplementation(final String checkerName,
+ @Nonnull final RangeConstraint<?> constraint) {
+ final Set<? extends Range<? extends Number>> constraints = constraint.getAllowedRanges().asRanges();
final String fieldName = checkerName.toUpperCase() + "_RANGES";
final StringBuilder sb = new StringBuilder();
.append(") java.lang.reflect.Array.newInstance(").append(RANGE).append(".class, ").append(constraints.size()).append(");\n");
int i = 0;
- for (RangeConstraint r : constraints) {
- final String min = format(getValue(r.getMin()));
- final String max = format(getValue(r.getMax()));
+ for (Range<? extends Number> r : constraints) {
+ final String min = format(getValue(r.lowerEndpoint()));
+ final String max = format(getValue(r.upperEndpoint()));
sb.append(" a[").append(i++).append("] = ").append(RANGE).append(".closed(").append(min).append(", ").append(max).append(");\n");
}
import com.google.common.collect.Range;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.List;
+import java.util.Set;
import javax.annotation.Nonnull;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
import org.slf4j.Logger;
return minValue.compareTo(minToEnforce) < 0;
}
- private Collection<String> createExpressions(final Collection<RangeConstraint> constraints) {
+ private Collection<String> createExpressions(final RangeConstraint<?> constraint) {
+ final Set<? extends Range<? extends Number>> constraints = constraint.getAllowedRanges().asRanges();
final Collection<String> ret = new ArrayList<>(constraints.size());
- for (RangeConstraint r : constraints) {
- final T min = getValue(r.getMin());
+ for (Range<? extends Number> r : constraints) {
+ final T min = getValue(r.lowerEndpoint());
final boolean needMin = needsMinimumEnforcement(min);
- final T max = getValue(r.getMax());
+ final T max = getValue(r.upperEndpoint());
final boolean needMax = needsMaximumEnforcement(max);
if (!needMin && !needMax) {
return ret;
}
- private String createRangeString(final Collection<RangeConstraint> constraints) {
- final List<Range<T>> ranges = new ArrayList<>(constraints.size());
-
- for (RangeConstraint c : constraints) {
- ranges.add(Range.closed(getValue(c.getMin()), getValue(c.getMax())));
- }
-
- return ranges.toString();
+ private static String createRangeString(final RangeConstraint<?> constraints) {
+ return constraints.getAllowedRanges().toString();
}
@Override
- protected final String generateRangeCheckerImplementation(final String checkerName, final Collection<RangeConstraint> constraints) {
+ protected final String generateRangeCheckerImplementation(final String checkerName,
+ final RangeConstraint<?> constraint) {
final StringBuilder sb = new StringBuilder();
- final Collection<String> expressions = createExpressions(constraints);
+ final Collection<String> expressions = createExpressions(constraint);
sb.append("private static void ").append(checkerName).append("(final ").append(primitiveName).append(" value) {\n");
}
sb.append(" throw new IllegalArgumentException(String.format(\"Invalid range: %s, expected: ")
- .append(createRangeString(constraints)).append(".\", value));\n");
+ .append(createRangeString(constraint)).append(".\", value));\n");
}
sb.append("}\n");
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
-import java.util.Collection;
import java.util.Map;
import javax.annotation.Nonnull;
import org.opendaylight.mdsal.binding.javav2.model.api.ConcreteType;
/**
* Generate the checker method source code.
* @param checkerName Name of the checker method.
- * @param constraints Restrictions which need to be applied.
+ * @param constraint Restrictions which need to be applied.
* @return Method source code.
*/
- @Nonnull protected abstract String generateRangeCheckerImplementation(@Nonnull final String checkerName, @Nonnull final Collection<RangeConstraint> constraints);
+ @Nonnull protected abstract String generateRangeCheckerImplementation(@Nonnull final String checkerName,
+ @Nonnull final RangeConstraint<?> constraint);
private static String rangeCheckerName(final String member) {
return "check" + member + "Range";
}
- public String generateRangeChecker(@Nonnull final String member, @Nonnull final Collection<RangeConstraint>
- constraints) {
- Preconditions.checkArgument(!constraints.isEmpty(), "Restrictions may not be empty");
- return generateRangeCheckerImplementation(rangeCheckerName(member), constraints);
+ public String generateRangeChecker(@Nonnull final String member, @Nonnull final RangeConstraint<?> constraint) {
+ return generateRangeCheckerImplementation(rangeCheckerName(member), constraint);
}
public String generateRangeCheckerCall(@Nonnull final String member, @Nonnull final String valueReference) {
return rangeCheckerName(member) + '(' + valueReference + ");\n";
}
-}
\ No newline at end of file
+}
package org.opendaylight.mdsal.binding.javav2.java.api.generator.rangeGenerators;
import com.google.common.collect.Range;
-import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.List;
+import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.opendaylight.mdsal.binding.javav2.model.api.Type;
return "check" + member + "Length";
}
- private static Collection<String> createExpressions(final Collection<LengthConstraint> constraints) {
+ private static Collection<String> createExpressions(final LengthConstraint constraint) {
+ final Set<Range<Integer>> constraints = constraint.getAllowedRanges().asRanges();
final Collection<String> ret = new ArrayList<>(constraints.size());
- for (LengthConstraint l : constraints) {
+ for (Range<Integer> l : constraints) {
final StringBuilder sb = new StringBuilder("length >");
// We have to deal with restrictions being out of integer's range
- if (l.getMin().longValue() <= Integer.MAX_VALUE) {
+ if (l.lowerEndpoint() <= Integer.MAX_VALUE) {
sb.append('=');
}
- sb.append(' ').append(l.getMin().intValue());
+ sb.append(' ').append(l.lowerEndpoint());
- final int max = l.getMax().intValue();
+ final int max = l.upperEndpoint();
if (max < Integer.MAX_VALUE) {
sb.append(" && length <= ").append(max);
}
return ret;
}
- private static String createLengthString(final Collection<LengthConstraint> constraints) {
- final List<Range<BigInteger>> ranges = new ArrayList<>(constraints.size());
-
- for (LengthConstraint c : constraints) {
- ranges.add(Range.closed(new BigInteger(c.getMin().toString()), new BigInteger(c.getMax().toString())));
- }
-
- return ranges.toString();
+ private static String createLengthString(final LengthConstraint constraint) {
+ return new ArrayList<>(constraint.getAllowedRanges().asRanges()).toString();
}
- private static String generateArrayLengthChecker(final String member, final Collection<LengthConstraint> constraints) {
+ private static String generateArrayLengthChecker(final String member, final LengthConstraint constraint) {
final StringBuilder sb = new StringBuilder();
- final Collection<String> expressions = createExpressions(constraints);
+ final Collection<String> expressions = createExpressions(constraint);
sb.append("private static void ").append(lengthCheckerName(member)).append("(final byte[] value) {\n");
}
sb.append(" throw new IllegalArgumentException(String.format(\"Invalid length: %s, expected: ")
- .append(createLengthString(constraints)).append(".\", java.util.Arrays.toString(value)));\n");
+ .append(createLengthString(constraint)).append(".\", java.util.Arrays.toString(value)));\n");
}
sb.append("}\n");
return sb.toString();
}
- private static String generateStringLengthChecker(final String member, final Collection<LengthConstraint> constraints) {
+ private static String generateStringLengthChecker(final String member, final LengthConstraint constraint) {
final StringBuilder sb = new StringBuilder();
- final Collection<String> expressions = createExpressions(constraints);
+ final Collection<String> expressions = createExpressions(constraint);
sb.append("private static void ").append(lengthCheckerName(member)).append("(final String value) {\n");
}
sb.append(" throw new IllegalArgumentException(String.format(\"Invalid length: %s, expected: ")
- .append(createLengthString(constraints)).append(".\", value));\n");
+ .append(createLengthString(constraint)).append(".\", value));\n");
}
sb.append("}\n");
return sb.toString();
}
- public static String generateLengthChecker(final String member, final Type type, final Collection<LengthConstraint>
- constraints) {
+ public static String generateLengthChecker(final String member, final Type type,
+ final LengthConstraint constraint) {
if (TypeUtils.getBaseYangType(type).getName().contains("[")) {
- return generateArrayLengthChecker(member, constraints);
+ return generateArrayLengthChecker(member, constraint);
} else {
- return generateStringLengthChecker(member, constraints);
+ return generateStringLengthChecker(member, constraint);
}
}
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil;
import org.opendaylight.mdsal.binding.javav2.model.api.Type;
import org.opendaylight.mdsal.binding.javav2.model.api.WildcardType;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
public abstract class BaseRenderer {
private static final String COMMA = ",";
return type;
}
- protected String getFromImportMap(@NonNull String typeName) {
+ protected String getFromImportMap(@NonNull final String typeName) {
return importMap.get(typeName);
}
- protected void putToImportMap(@NonNull String typeName, String typePackageName) {
+ protected void putToImportMap(@NonNull final String typeName, final String typePackageName) {
importMap.put(typeName, typePackageName);
}
- protected void putAllToImportMap(@NonNull Map<String, String> imports) {
+ protected void putAllToImportMap(@NonNull final Map<String, String> imports) {
importMap.putAll(imports);
}
return sb;
}
- protected GeneratedProperty findProperty(final GeneratedTransferObject gto, String name) {
+ protected GeneratedProperty findProperty(final GeneratedTransferObject gto, final String name) {
for (GeneratedProperty prop : gto.getProperties()) {
if (name.equals(prop.getName())) {
return prop;
*/
protected String emitConstant(final Constant constant) {
final StringBuilder sb = new StringBuilder();
- final Object qname = constant.getValue();
+ final Object value = constant.getValue();
sb.append("public static final ")
.append(importedName(constant.getType()))
.append(' ')
.append(constant.getName())
.append(" = ");
- if (qname instanceof QName) {
- sb.append(QName.class.getName())
- .append(".create(\"")
- .append(((QName) qname).getNamespace().toString())
- .append("\", \"")
- .append(((QName) qname).getFormattedRevision())
- .append("\", \"")
- .append(((QName) qname).getLocalName())
- .append("\").intern()");
+ if (value instanceof QName) {
+ final QName qname = (QName) value;
+ sb.append(QName.class.getName()).append(".create(\"").append(qname.getNamespace()).append("\", ");
+ final Optional<Revision> rev = qname.getRevision();
+ if (rev.isPresent()) {
+ sb.append('"').append(rev.get()).append('"');
+ } else {
+ sb.append("null");
+ }
+ sb.append(", \"").append(qname.getLocalName()).append("\").intern()");
} else {
- sb.append(qname);
+ sb.append(value);
}
sb.append(";\n");
return sb.toString();
final Type t = pTypes[i];
String separator = COMMA;
- if (i == (pTypes.length - 1)) {
+ if (i == pTypes.length - 1) {
separator = "";
}
Collections.sort(sorted, function);
allProperties = ImmutableList.copyOf(sorted);
- if (restrictions != null && (restrictions.getRangeConstraints() != null && !restrictions.getRangeConstraints()
- .isEmpty())) {
+ if (restrictions != null && restrictions.getRangeConstraint().isPresent()) {
rangeGenerator = AbstractRangeGenerator.forType(findProperty(genType, "value").getReturnType());
Preconditions.checkNotNull(rangeGenerator);
} else {
final StringBuilder lengthRangeCheckerBuilder = new StringBuilder();
if (restrictions != null) {
- if (restrictions.getLengthConstraints() != null && !restrictions.getLengthConstraints().isEmpty()) {
+ if (restrictions.getLengthConstraint().isPresent()) {
lengthRangeCheckerBuilder.append(LengthGenerator.generateLengthChecker("_value", findProperty(genTO,
- "value").getReturnType(), restrictions.getLengthConstraints()))
+ "value").getReturnType(), restrictions.getLengthConstraint().get()))
.append("\n");
}
- if (restrictions.getRangeConstraints() != null && !restrictions.getRangeConstraints().isEmpty()) {
+ if (restrictions.getRangeConstraint().isPresent()) {
lengthRangeCheckerBuilder.append(rangeGenerator.generateRangeChecker("_value", restrictions
- .getRangeConstraints()))
+ .getRangeConstraint().get()))
.append("\n");
}
}
if (!enumeration.getValues().isEmpty()) {
for (Enumeration.Pair pair : enumeration.getValues()) {
final StringBuilder sb = new StringBuilder();
- sb.append(asJavadoc(encodeAngleBrackets(pair.getDescription())));
+ sb.append(asJavadoc(encodeAngleBrackets(pair.getDescription().orElse(null))));
sb.append("\n");
sb.append(pair.getMappedName());
sb.append('(');
generatedConstants, generatedInnerClasses).body();
}
- private boolean isAccessor (final MethodSignature maybeGetter) {
+ private static boolean isAccessor(final MethodSignature maybeGetter) {
return maybeGetter.getName().startsWith("is") || maybeGetter.getName().startsWith("get");
}
import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModelBindingProvider;
import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModuleInfo;
import org.opendaylight.yangtools.concepts.SemVer;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
}
public static Module getSortedQName(final Set<Module> modules, final String name) {
- final TreeMap<Date, Module> sorted = new TreeMap<>();
+ final TreeMap<java.util.Optional<Revision>, Module> sorted = new TreeMap<>(Revision::compare);
for (Module module : modules) {
if (name.equals(module.getName())) {
sorted.put(module.getRevision(), module);
@generateSetters() = {
@for(field <- properties) {
@if(!field.getReturnType.isInstanceOf[GeneratedType] && getRestrictions(field.getReturnType) != null) {
- @if(getRestrictions(field.getReturnType).getRangeConstraints != null && !getRestrictions(field.getReturnType).getRangeConstraints.isEmpty) {
+ @if(getRestrictions(field.getReturnType).getRangeConstraint.isPresent) {
@{AbstractRangeGenerator.forType(field.getReturnType).generateRangeChecker(toFirstUpper(field.getName),
- getRestrictions(field.getReturnType).getRangeConstraints)}
+ getRestrictions(field.getReturnType).getRangeConstraint.get)}
}
- @if(getRestrictions(field.getReturnType).getLengthConstraints != null && !getRestrictions(field.getReturnType).getLengthConstraints.isEmpty) {
+ @if(getRestrictions(field.getReturnType).getLengthConstraint.isPresent) {
@{LengthGenerator.generateLengthChecker(fieldName(field), field.getReturnType,
- getRestrictions(field.getReturnType).getLengthConstraints)}
+ getRestrictions(field.getReturnType).getLengthConstraint.get)}
}
}
public @{genType.getName}Builder set@{toFirstUpper(field.getName)}(final @{field.getReturnType.getFullyQualifiedName} value) {
@if(!field.getReturnType.isInstanceOf[GeneratedType] && getRestrictions(field.getReturnType) != null) {
if (value != null) {
- @if(getRestrictions(field.getReturnType).getRangeConstraints != null && !getRestrictions(field.getReturnType).getRangeConstraints.isEmpty) {
+ @if(getRestrictions(field.getReturnType).getRangeConstraint.isPresent) {
@if(field.getReturnType.isInstanceOf[ConcreteType]) {
@{AbstractRangeGenerator.forType(field.getReturnType).generateRangeCheckerCall(toFirstUpper(field.getName), "value")}
} else {
@{AbstractRangeGenerator.forType(field.getReturnType).generateRangeCheckerCall(toFirstUpper(field.getName), "value.getValue()")}
}
}
- @if(getRestrictions(field.getReturnType).getLengthConstraints != null && !getRestrictions(field.getReturnType).getLengthConstraints.isEmpty) {
+ @if(getRestrictions(field.getReturnType).getLengthConstraint.isPresent) {
@if(field.getReturnType.isInstanceOf[ConcreteType]) {
@{LengthGenerator.generateLengthCheckerCall(fieldName(field), "value")}
} else {
return true;
}
}
-}
\ No newline at end of file
+}
@(currentType: Type, paramName: String, returnType: Type, rangeGenerator: AbstractRangeGenerator[_])
@if(getRestrictions(currentType) != null) {
- @if(!getRestrictions(currentType).getLengthConstraints.isEmpty || !getRestrictions(currentType).getRangeConstraints.isEmpty) {
+ @if(getRestrictions(currentType).getLengthConstraint.isPresent || getRestrictions(currentType).getRangeConstraint.isPresent) {
if (@{paramName} != null) {
- @if(!getRestrictions(currentType).getLengthConstraints.isEmpty) {
+ @if(getRestrictions(currentType).getLengthConstraint.isPresent) {
@{LengthGenerator.generateLengthCheckerCall(paramName, paramValue(returnType, paramName))}
}
- @if(!getRestrictions(currentType).getRangeConstraints.isEmpty) {
+ @if(getRestrictions(currentType).getRangeConstraint.isPresent) {
@{rangeGenerator.generateRangeCheckerCall(paramName, paramValue(returnType, paramName))}
}
}
}
-}
\ No newline at end of file
+}
private final @{importedNames.get("string")} name = "@{module.getName}";
private final @{importedNames.get("string")} namespace = "@{module.getNamespace.toString}";
private final @{importedNames.get("string")} semanticVersion = "@{module.getSemanticVersion}";
- private final @{importedNames.get("string")} revision = "@{module.getQNameModule.getFormattedRevision}";
+ private final @{importedNames.get("string")} revision = @if(module.getRevision.isPresent) { "@{module.getRevision.get.toString}" } else { null };
private final @{importedNames.get("string")} resourcePath = "@{getSourcePath(module, moduleFilePathResolver)}";
private final @{importedNames.get("set")}<YangModuleInfo> importedModules;
private final @{importedNames.get("string")} name = "@{submodule.getName}";
private final @{importedNames.get("string")} semanticVersion = "@{submodule.getSemanticVersion}";
private final @{importedNames.get("string")} namespace = "@{submodule.getNamespace.toString}";
- private final @{importedNames.get("string")} revision = "@{submodule.getQNameModule.getFormattedRevision}";
+ private final @{importedNames.get("string")} revision = @if(module.getRevision.isPresent) { "@{module.getRevision.get.toString}" } else { null };
private final @{importedNames.get("string")} resourcePath = "@{getSourcePath(submodule, moduleFilePathResolver)}";
private final @{importedNames.get("set")}<YangModuleInfo> importedModules;
}
@if(!module.getImports.isEmpty) {
@for(moduleImport <- module.getImports) {
- @if(moduleImport.getRevision == null) {
- set.add(@{normalizeFullPackageName(getRootPackageName(getSortedQName(ctx.getModules, moduleImport
- .getModuleName)))}.@{MODULE_INFO_CLASS_NAME}.getInstance());
- } else {
- set.add(@{normalizeFullPackageName(getRootPackageName(ctx.findModuleByName(moduleImport
- .getModuleName, moduleImport.getRevision)))}.@{MODULE_INFO_CLASS_NAME}.getInstance());
- }
+ set.add(@{normalizeFullPackageName(getRootPackageName(ctx.findModule(moduleImport
+ .getModuleName, moduleImport.getRevision).get))}.@{MODULE_INFO_CLASS_NAME}.getInstance());
}
}
@if(!module.getSubmodules.isEmpty) {
@Test
public void generatedFilesTest() throws Exception {
- final SchemaContext context = YangParserTestUtils.parseYangSources("/base/with_import/");
+ final SchemaContext context = YangParserTestUtils.parseYangResourceDirectory("/base/with_import/");
final BindingGenerator bindingGenerator = new BindingGeneratorImpl(true);
final List<Type> types = bindingGenerator.generateTypes(context, context.getModules());
final BuildContext buildContext = new DefaultBuildContext();
this.projectBaseDir = project.getBasedir();
}
- @Override
- public Collection<File> generateSources(SchemaContext context, File outputBaseDir, Set<Module> currentModules) throws IOException {
- return generateSources(context, outputBaseDir, currentModules,
- m -> Optional.of("/" + m.getModuleSourcePath().replace(File.separator, "/")));
- }
-
private Collection<? extends File> generateModuleInfos(final File outputBaseDir, final Set<Module> yangModules,
final SchemaContext context, final Function<Module, Optional<String>> moduleResourcePathResolver) {
Builder<File> result = ImmutableSet.builder();
import java.util.Set;
import javax.annotation.Nullable;
import org.opendaylight.mdsal.binding.javav2.generator.api.ClassLoadingStrategy;
-import org.opendaylight.mdsal.binding.javav2.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext;
+import org.opendaylight.mdsal.binding.javav2.generator.impl.BindingGeneratorImpl;
import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier;
import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer;
import org.opendaylight.mdsal.binding.javav2.generator.util.ReferencedTypeImpl;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
private final ClassLoadingStrategy strategy;
private final SchemaContext schemaContext;
- private final Map<Type, AugmentationSchema> augmentationToSchema = new HashMap<>();
+ private final Map<Type, AugmentationSchemaNode> augmentationToSchema = new HashMap<>();
private final BiMap<Type, Object> typeToDefiningSchema = HashBiMap.create();
private final Multimap<Type, Type> choiceToCases = HashMultimap.create();
private final Map<QName, Type> identities = new HashMap<>();
* augmentations, which may be present in runtime for them, thus returned
* schema is unsuitable for use for validation of data.
* <p>
- * For retrieving {@link AugmentationSchema}, which will contains full model
+ * For retrieving {@link AugmentationSchemaNode}, which will contains full model
* for child nodes, you should use method
* {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)} which
* will return augmentation schema derived from supplied augmentation target
* @throws IllegalArgumentException
* - if supplied class is not an augmentation
*/
- public @Nullable AugmentationSchema getAugmentationDefinition(final Class<?> augClass) throws IllegalArgumentException {
+ public @Nullable AugmentationSchemaNode getAugmentationDefinition(final Class<?> augClass) {
Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass), "Class %s does not represent augmentation", augClass);
return this.augmentationToSchema.get(referencedType(augClass));
}
}
/**
- * Returns defining {@link AugmentationSchema} of target for supplied class.
+ * Returns defining {@link AugmentationSchemaNode} of target for supplied class.
*
* @param target
* - {@link DataNodeContainer}
* @param aug
* - supplied class
- * @return entry of {@link AugmentationSchema} according to its identifier
+ * @return entry of {@link AugmentationSchemaNode} according to its identifier
* {@link AugmentationIdentifier}
*/
- public Entry<AugmentationIdentifier, AugmentationSchema> getResolvedAugmentationSchema(final DataNodeContainer target,
- final Class<? extends Augmentation<?>> aug) {
- final AugmentationSchema origSchema = getAugmentationDefinition(aug);
+ public Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
+ final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
+ final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
Preconditions.checkArgument(origSchema != null, "Augmentation %s is not known in current schema context",aug);
/*
* FIXME: Validate augmentation schema lookup
}
final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
- final AugmentationSchema proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
+ final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
return new SimpleEntry<>(identifier, proxy);
}
* @throws IllegalArgumentException
* - if supplied class does not represent case
*/
- public Optional<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) throws IllegalArgumentException {
+ public Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) throws IllegalArgumentException {
final DataSchemaNode origSchema = getSchemaDefinition(childClass);
- Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "Supplied schema %s is not case.", origSchema);
+ Preconditions.checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
/*
* FIXME: Make sure that if there are multiple augmentations of same
* unaware that he is using incorrect case which was generated for
* choice inside grouping.
*/
- final Optional<ChoiceCaseNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
- (ChoiceCaseNode) origSchema);
+ final Optional<CaseSchemaNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
+ (CaseSchemaNode) origSchema);
return found;
}
}
/**
- * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition})
+ * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
* from which supplied class was generated. Returned schema may be augmented with
* additional information, which was not available at compile type
* (e.g. third party augmentations).
*
* @param type Binding Class for which schema should be retrieved.
* @return Instance of generated type (definition of Java API), along with
- * {@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition}
+ * {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
* which was used to generate supplied class.
*/
public Entry<GeneratedType, Object> getTypeWithSchema(final Class<?> type) {
public ImmutableMap<AugmentationIdentifier,Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
final Map<AugmentationIdentifier,Type> identifierToType = new HashMap<>();
if (container instanceof AugmentationTarget) {
- final Set<AugmentationSchema> augments = ((AugmentationTarget) container).getAvailableAugmentations();
- for (final AugmentationSchema augment : augments) {
+ for (final AugmentationSchemaNode augment : ((AugmentationTarget) container).getAvailableAugmentations()) {
// Augmentation must have child nodes if is to be used with Binding classes
- AugmentationSchema augOrig = augment;
+ AugmentationSchemaNode augOrig = augment;
while (augOrig.getOriginalDefinition().isPresent()) {
augOrig = augOrig.getOriginalDefinition().get();
}
return ImmutableMap.copyOf(identifierToType);
}
- private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchema augment) {
+ private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
final Set<QName> childNames = new HashSet<>();
for (final DataSchemaNode child : augment.getChildNodes()) {
childNames.add(child.getQName());
import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
import org.opendaylight.yangtools.concepts.ObjectRegistration;
import org.opendaylight.yangtools.util.ClassLoaderUtils;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
* @return optional of schema context
*/
public Optional<SchemaContext> tryToCreateSchemaContext() {
- return ctxResolver.getSchemaContext();
+ return Optional.fromJavaUtil(ctxResolver.getSchemaContext());
}
private boolean resolveModuleInfo(final Class<?> cls) {
}
private static SourceIdentifier sourceIdentifierFrom(final YangModuleInfo moduleInfo) {
- return RevisionSourceIdentifier.create(moduleInfo.getName(), Optional.of(moduleInfo.getRevision()));
+ return RevisionSourceIdentifier.create(moduleInfo.getName(), Revision.ofNullable(moduleInfo.getRevision()));
}
/**
import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode;
import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.common.Revision;
+import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
for (final DataSchemaNode child : ctx.getChildNodes()) {
if (child instanceof ChoiceSchemaNode) {
- final DataNodeContainer potential = findInCases(((ChoiceSchemaNode) child), targetQName);
+ final DataNodeContainer potential = findInCases((ChoiceSchemaNode) child, targetQName);
if (potential != null) {
return Optional.of(potential);
}
}
private static DataNodeContainer findInCases(final ChoiceSchemaNode choiceNode, final QName targetQName) {
- for (final ChoiceCaseNode caze : choiceNode.getCases()) {
+ for (final CaseSchemaNode caze : choiceNode.getCases().values()) {
final Optional<DataNodeContainer> potential = findDataNodeContainer(caze, targetQName);
if (potential.isPresent()) {
return potential.get();
final YangModuleInfo moduleInfo, final Class<? extends TreeNode> targetType) {
for (final OperationDefinition operation : operations) {
final String operationNamespace = operation.getQName().getNamespace().toString();
- final String operationRevision = operation.getQName().getFormattedRevision();
+ final String operationRevision = operation.getQName().getRevision().map(Revision::toString).orElse(null);
if (moduleInfo.getNamespace().equals(operationNamespace)
&& moduleInfo.getRevision().equals(operationRevision)) {
final Optional<DataNodeContainer> potential = findInputOutput(operation, targetType.getSimpleName());
* - choice case
* @return choice case node if exists, absent() otherwise
*/
- public static Optional<ChoiceCaseNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice, final ChoiceCaseNode originalDefinition) {
- ChoiceCaseNode potential = instantiatedChoice.getCaseNodeByName(originalDefinition.getQName());
- if(originalDefinition.equals(potential)) {
+ public static Optional<CaseSchemaNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice, final CaseSchemaNode originalDefinition) {
+ final QName qname = originalDefinition.getQName();
+ final CaseSchemaNode potential = instantiatedChoice.getCaseNodeByName(qname);
+ if (originalDefinition.equals(potential)) {
return Optional.of(potential);
}
if (potential != null) {
// different, but local names are still same.
//
// Still we need to check equality of definition, because local name is not
- // sufficient to uniquelly determine equality of cases
- //
- potential = instantiatedChoice.getCaseNodeByName(originalDefinition.getQName().getLocalName());
- if(potential != null && (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential)))) {
- return Optional.of(potential);
+ // sufficient to uniquely determine equality of cases
+ for (CaseSchemaNode found : instantiatedChoice.findCaseNodes(qname.getLocalName())) {
+ if (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(found))) {
+ return Optional.of(found);
+ }
}
return Optional.absent();
}
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
+
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import org.opendaylight.yangtools.util.ClassLoaderUtils;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* @return {@link QNameModule} from module info
*/
public static final QNameModule getQNameModule(final YangModuleInfo modInfo) {
- return QNameModule.create(URI.create(modInfo.getNamespace()), QName.parseRevision(modInfo.getRevision()));
+ return QNameModule.create(URI.create(modInfo.getNamespace()), Revision.ofNullable(modInfo.getRevision()));
}
/**
import static org.junit.Assert.assertNotNull;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.net.URISyntaxException;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class BindingRuntimeContextTest {
private DataNodeContainer myCont;
@Before
- public void setup() throws URISyntaxException, FileNotFoundException, ReactorException {
- schemaContext = YangParserTestUtils.parseYangSources(
- new File(getClass().getResource("/yang/test-runtime.yang").toURI()));
+ public void setup() {
+ schemaContext = YangParserTestUtils.parseYangResource("/yang/test-runtime.yang");
myCont = (DataNodeContainer) schemaContext.getChildNodes().iterator().next();
brc = BindingRuntimeContext.create(GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(), schemaContext);
}
import static org.junit.Assert.assertNotNull;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.net.URISyntaxException;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class BindingSchemaContextUtilsTest {
@Before
- public void setup() throws URISyntaxException, FileNotFoundException, ReactorException {
- schemaContext = YangParserTestUtils.parseYangSources(
- new File(getClass().getResource("/yang/test-runtime.yang").toURI()));
+ public void setup() {
+ schemaContext = YangParserTestUtils.parseYangResource("/yang/test-runtime.yang");
myCont = (DataNodeContainer) schemaContext.getChildNodes().iterator().next();
myChoice = (ChoiceSchemaNode) myCont.getChildNodes().iterator().next();
}
public void utilTest() {
assertNotNull(BindingSchemaContextUtils.findDataNodeContainer(schemaContext, MY_CONT_NODE_PATH));
assertNotNull(BindingSchemaContextUtils.findInstantiatedChoice(myCont, MyChoice.class));
- assertNotNull(BindingSchemaContextUtils.findInstantiatedCase(myChoice, myChoice.getCaseNodeByName("one")));
+ assertNotNull(BindingSchemaContextUtils.findInstantiatedCase(myChoice, myChoice.findCaseNodes("one")
+ .iterator().next()));
}
}
assertFalse(BindingReflections
.resolveOperationOutputClass(TestImplementation.class.getDeclaredMethod("rpcMethodTest2")).isPresent());
- assertTrue(BindingReflections.getQName(TestImplementation.class).toString().equals("test"));
+ assertTrue(BindingReflections.getQName(TestImplementation.class).toString().equals("()test"));
assertNotNull(BindingReflections.getQNameModule(TestImplementation.class));
}
private static final class TestImplementation extends BaseIdentity
implements Augmentation<TestImplementation>, Rpc {
- public static final QName QNAME = QName.create("test");
+ public static final QName QNAME = QName.create("", "test");
Future<List<Object>> rpcMethodTest() {
return null;
package org.opendaylight.mdsal.binding.javav2.util;
import static com.google.common.base.Preconditions.checkArgument;
+
import com.google.common.annotations.Beta;
import com.google.common.collect.ImmutableSet;
-import java.text.SimpleDateFormat;
+import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.Module;
/**
public static final String RPC_INPUT_SUFFIX = "Input";
public static final String RPC_OUTPUT_SUFFIX = "Output";
- private static final ThreadLocal<SimpleDateFormat> PACKAGE_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
-
- @Override
- protected SimpleDateFormat initialValue() {
- return new SimpleDateFormat("yyMMdd");
- }
-
- @Override
- public void set(final SimpleDateFormat value) {
- throw new UnsupportedOperationException();
- }
- };
-
private BindingMapping() {
throw new UnsupportedOperationException("Utility class");
}
// packageNameBuilder.append(PACKAGE_DATE_FORMAT.get().format(module.getRevision()));
// }
- packageNameBuilder.append("rev");
- packageNameBuilder.append(PACKAGE_DATE_FORMAT.get().format(module.getRevision()));
+ final Optional<Revision> optRev = module.getRevision();
+ if (optRev.isPresent()) {
+ // Revision is in format 2017-10-26, we want the output to be 171026, which is a matter of picking the
+ // right characters.
+ final String rev = optRev.get().toString();
+ checkArgument(rev.length() == 10, "Unsupported revision %s", rev);
+ packageNameBuilder.append("rev");
+ packageNameBuilder.append(rev.substring(2, 4)).append(rev.substring(5, 7)).append(rev.substring(8));
+ } else {
+ // No-revision packages are special
+ packageNameBuilder.append("norev");
+ }
return packageNameBuilder.toString();
}
*/
public abstract class AbstractDOMDataTreeServiceTestSuite {
protected static final QNameModule TEST_MODULE =
- QNameModule.create(URI.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:store"), null);
+ QNameModule.create(URI.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:store"));
protected static final YangInstanceIdentifier UNORDERED_CONTAINER_IID = YangInstanceIdentifier.create(
new NodeIdentifier(QName.create(TEST_MODULE, "lists")),
private static final String COMPARE_FIRST_LISTS = "A-test-lists";
private static final String COMPARE_SECOND_LISTS = "B-test-lists";
private static final QNameModule TEST_MODULE = QNameModule.create(URI.create(
- "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:store"), null);
+ "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:store"));
private static final YangInstanceIdentifier REF_YII_IID = YangInstanceIdentifier.create(
new YangInstanceIdentifier.NodeIdentifier(QName.create(TEST_MODULE, REF_LISTS)));
private static final YangInstanceIdentifier TEST_YII_IID = YangInstanceIdentifier.create(
private static final String TEST_MESSAGE = "TestMessage";
private static final String TEST_LISTS = "test-lists";
private static final QNameModule TEST_MODULE = QNameModule.create(URI.create(
- "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:store"), null);
+ "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:store"));
private static final YangInstanceIdentifier TEST_YI_ID = YangInstanceIdentifier.create(
new YangInstanceIdentifier.NodeIdentifier(QName.create(TEST_MODULE, TEST_LISTS)));
private static final DOMDataTreeIdentifier TEST_TREE = new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL,
public class DOMRpcIdentifierTest {
private static final String LOCAL_IDENT = "local";
private static final QNameModule TEST_MODULE = QNameModule.create(URI.create(
- "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:store"), null);
+ "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:store"));
private static final DOMRpcIdentifier GLOBAL = DOMRpcIdentifier.create(SchemaPath.SAME, null);
private static final DOMRpcIdentifier LOCAL = DOMRpcIdentifier.create(SchemaPath.ROOT,YangInstanceIdentifier.create(
new NodeIdentifier(QName.create(TEST_MODULE, LOCAL_IDENT))));
private static RpcDefinition findRpcDefinition(final SchemaContext context, final SchemaPath schemaPath) {
if (context != null) {
final QName qname = schemaPath.getPathFromRoot().iterator().next();
- final Module module = context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
+ final Module module = context.findModule(qname.getModule()).orElse(null);
if (module != null && module.getRpcs() != null) {
for (RpcDefinition rpc : module.getRpcs()) {
if (qname.equals(rpc.getQName())) {
*/
package org.opendaylight.mdsal.dom.broker;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import org.opendaylight.mdsal.dom.api.DOMRpcException;
import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
package org.opendaylight.mdsal.dom.broker.schema;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
-import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.ListenableFuture;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.mdsal.dom.api.DOMSchemaService;
import org.opendaylight.mdsal.dom.api.DOMSchemaServiceExtension;
final Optional<SchemaContext> schema = contextResolver.getSchemaContext();
if (schema.isPresent()) {
if (LOG.isDebugEnabled()) {
- LOG.debug("Got new SchemaContext: # of modules {}", schema.get().getAllModuleIdentifiers().size());
+ LOG.debug("Got new SchemaContext: # of modules {}", schema.get().getModules().size());
}
notifyListeners(schema.get());
}
@Override
public SchemaContext getGlobalContext() {
- return contextResolver.getSchemaContext().orNull();
+ return contextResolver.getSchemaContext().orElse(null);
}
@Override
}
@Override
- public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException>
- getSource(final SourceIdentifier sourceIdentifier) {
+ public ListenableFuture<? extends YangTextSchemaSource> getSource(final SourceIdentifier sourceIdentifier) {
return contextResolver.getSource(sourceIdentifier);
}
private CommitExecutorService commitExecutor;
@Before
- public void setupStore() throws Exception {
+ public void setupStore() {
final InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER",
MoreExecutors.newDirectExecutorService());
final InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG",
.build();
commitExecutor = new CommitExecutorService(Executors.newSingleThreadExecutor());
- futureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(1, 5, "FCB");
+ futureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(1, 5, "FCB", DOMBrokerTest.class);
executor = new DeadlockDetectingListeningExecutorService(commitExecutor,
TransactionCommitDeadlockException.DEADLOCK_EXCEPTION_SUPPLIER, futureExecutor);
domBroker = new SerializedDOMDataBroker(stores, executor);
LogicalDatastoreType.CONFIGURATION, TestModel.OUTER_LIST_PATH);
@Before
- public void setupStore() throws Exception {
+ public void setupStore() {
final InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER",
MoreExecutors.newDirectExecutorService());
final InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG",
.build();
commitExecutor = new CommitExecutorService(Executors.newSingleThreadExecutor());
- futureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(1, 5, "FCB");
+ futureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(1, 5, "FCB",
+ DOMDataTreeListenerTest.class);
executor = new DeadlockDetectingListeningExecutorService(commitExecutor,
TransactionCommitDeadlockException.DEADLOCK_EXCEPTION_SUPPLIER, futureExecutor);
domBroker = new SerializedDOMDataBroker(stores, executor);
public class DOMRpcRouterTest extends TestUtils {
@Test
- public void registerRpcImplementation() throws Exception {
+ public void registerRpcImplementation() {
try (DOMRpcRouter rpcRouter = new DOMRpcRouter()) {
DOMRpcRoutingTable routingTable = rpcRouter.routingTable();
assertFalse(routingTable.getRpcs().containsKey(SchemaPath.ROOT));
}
@Test
- public void invokeRpc() throws Exception {
+ public void invokeRpc() {
try (DOMRpcRouter rpcRouter = new DOMRpcRouter()) {
assertNotNull(rpcRouter.invokeRpc(SchemaPath.create(false, TestModel.TEST_QNAME), null));
}
}
@Test
- public void registerRpcListener() throws Exception {
+ public void registerRpcListener() {
try (DOMRpcRouter rpcRouter = new DOMRpcRouter()) {
final DOMRpcAvailabilityListener listener = mock(DOMRpcAvailabilityListener.class);
}
@Test
- public void onGlobalContextUpdated() throws Exception {
+ public void onGlobalContextUpdated() {
try (DOMRpcRouter rpcRouter = new DOMRpcRouter()) {
final DOMRpcRoutingTable routingTableOriginal = rpcRouter.routingTable();
}
@Test(expected = RejectedExecutionException.class)
- public void close() throws Exception {
+ public void close() {
final DOMRpcRouter rpcRouter = new DOMRpcRouter();
rpcRouter.close();
rpcRouter.registerRpcImplementation(getTestRpcImplementation(), DOMRpcIdentifier.create(SchemaPath.ROOT, null));
private AbstractDOMDataBroker domBroker;
@Before
- public void setupStore() throws Exception {
+ public void setupStore() {
final InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER",
MoreExecutors.newDirectExecutorService());
final InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG",
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
public class ShardedDOMDataTreeProducerMultiShardTest {
- private static final Logger LOG = LoggerFactory.getLogger(ShardedDOMDataTreeProducerMultiShardTest.class);
-
- private static SchemaContext schemaContext = null;
-
- static {
- try {
- schemaContext = TestModel.createTestContext();
- } catch (final ReactorException e) {
- LOG.error("Unable to create schema context for TestModel", e);
- }
- }
+ private static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
private static final DOMDataTreeIdentifier ROOT_ID =
new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.EMPTY);
MockitoAnnotations.initMocks(this);
rootShard = InMemoryDOMDataTreeShard.create(ROOT_ID, executor, 1);
- rootShard.onGlobalContextUpdated(schemaContext);
+ rootShard.onGlobalContextUpdated(SCHEMA_CONTEXT);
final ShardedDOMDataTree dataTree = new ShardedDOMDataTree();
final DOMDataTreeProducer shardRegProducer = dataTree.createProducer(Collections.singletonList(ROOT_ID));
doNothing().when(mockedDataTreeListener).onDataTreeChanged(anyCollection(), anyMap());
final InMemoryDOMDataTreeShard innerShard = InMemoryDOMDataTreeShard.create(INNER_CONTAINER_ID, executor, 1);
- innerShard.onGlobalContextUpdated(schemaContext);
+ innerShard.onGlobalContextUpdated(SCHEMA_CONTEXT);
final DOMDataTreeProducer shardRegProducer =
dataTreeService.createProducer(Collections.singletonList(INNER_CONTAINER_ID));
innerShardReg = dataTreeService.registerDataTreeShard(INNER_CONTAINER_ID, innerShard, shardRegProducer);
final ContainerNode lowerShardContainer = ImmutableContainerNodeBuilder.create()
.withNodeIdentifier(new NodeIdentifier(TestModel.ANOTHER_SHARD_CONTAINER))
.withChild(ImmutableLeafNodeBuilder.create().withNodeIdentifier(
- new NodeIdentifier(TestModel.ANOTHER_SHARD_VALUE)).build())
+ new NodeIdentifier(TestModel.ANOTHER_SHARD_VALUE)).withValue("").build())
.build();
cursor.write(TestModel.ANOTHER_SHARD_PATH.getLastPathArgument(), lowerShardContainer);
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
public class ShardedDOMDataTreeTest {
- private static final Logger LOG = LoggerFactory.getLogger(ShardedDOMDataTreeProducerMultiShardTest.class);
-
- private static SchemaContext schemaContext = null;
-
- static {
- try {
- schemaContext = TestModel.createTestContext();
- } catch (final ReactorException e) {
- LOG.error("Unable to create schema context for TestModel", e);
- }
- }
+ private static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
private static final DOMDataTreeIdentifier ROOT_ID =
new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY);
MockitoAnnotations.initMocks(this);
rootShard = InMemoryDOMDataTreeShard.create(ROOT_ID, executor, 1);
- rootShard.onGlobalContextUpdated(schemaContext);
+ rootShard.onGlobalContextUpdated(SCHEMA_CONTEXT);
final ShardedDOMDataTree dataTree = new ShardedDOMDataTree();
final DOMDataTreeProducer shardRegProducer = dataTree.createProducer(Collections.singletonList(ROOT_ID));
rootShardReg.close();
final InMemoryDOMDataTreeShard newRootShard = InMemoryDOMDataTreeShard.create(ROOT_ID, executor, 1);
- newRootShard.onGlobalContextUpdated(schemaContext);
+ newRootShard.onGlobalContextUpdated(SCHEMA_CONTEXT);
final DOMDataTreeProducer shardRegProducer = dataTreeService.createProducer(Collections.singletonList(ROOT_ID));
final ListenerRegistration<InMemoryDOMDataTreeShard> newRootShardReg =
shardRegProducer.close();
final InMemoryDOMDataTreeShard innerShard = InMemoryDOMDataTreeShard.create(INNER_CONTAINER_ID, executor, 1);
- innerShard.onGlobalContextUpdated(schemaContext);
+ innerShard.onGlobalContextUpdated(SCHEMA_CONTEXT);
final DOMDataTreeProducer shardRegProducer2 =
dataTreeService.createProducer(Collections.singletonList(INNER_CONTAINER_ID));
ListenerRegistration<InMemoryDOMDataTreeShard> innerShardReg =
doNothing().when(mockedDataTreeListener).onDataTreeChanged(anyCollection(), anyMap());
InMemoryDOMDataTreeShard testShard = InMemoryDOMDataTreeShard.create(TEST_ID, executor, 1);
- testShard.onGlobalContextUpdated(schemaContext);
+ testShard.onGlobalContextUpdated(SCHEMA_CONTEXT);
final DOMDataTreeProducer regProducer = dataTreeService.createProducer(Collections.singleton(TEST_ID));
dataTreeService.registerDataTreeShard(TEST_ID, testShard, regProducer);
final DOMDataTreeProducer shardProducer = dataTreeService.createProducer(
Collections.singletonList(outerListPath));
final InMemoryDOMDataTreeShard outerListShard = InMemoryDOMDataTreeShard.create(outerListPath, executor, 1000);
- outerListShard.onGlobalContextUpdated(schemaContext);
+ outerListShard.onGlobalContextUpdated(SCHEMA_CONTEXT);
final ListenerRegistration<InMemoryDOMDataTreeShard> oid1ShardRegistration =
dataTreeService.registerDataTreeShard(outerListPath, outerListShard, shardProducer);
public void testLargerSubshardSpace() throws Exception {
final InMemoryDOMDataTreeShard outerListShard = InMemoryDOMDataTreeShard.create(OUTER_LIST_ID, executor, 1, 1);
- outerListShard.onGlobalContextUpdated(schemaContext);
+ outerListShard.onGlobalContextUpdated(SCHEMA_CONTEXT);
try (DOMDataTreeProducer producer =
dataTreeService.createProducer(Collections.singletonList(OUTER_LIST_ID))) {
Collections.singletonList(ROOT_ID));
shardedDOMDataTree.registerDataTreeShard(ROOT_ID, rootShard, shardRegProducer);
shardRegProducer.close();
- final YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.of(QName.create("test"));
+ final YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.of(QName.create("", "test"));
final DOMDataTreeProducer producer = shardedDOMDataTree.createProducer(Collections.singletonList(ROOT_ID));
final DOMDataTreeCursorAwareTransaction transaction = producer.createTransaction(false);
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import com.google.common.util.concurrent.CheckedFuture;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import org.mockito.internal.util.io.IOUtil;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.concepts.Registration;
+import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
assertFalse(schemaService.hasListeners());
final SchemaContextHolder actualSchemaCtx = new SchemaContextHolder();
- final SchemaContextListener listener = prepareSchemaCtxListener(actualSchemaCtx);
+ final SchemaContextListener listener = actualSchemaCtx::setSchemaContext;
final ListenerRegistration<SchemaContextListener> registerSchemaContextListener =
schemaService.registerSchemaContextListener(listener);
assertEquals(registerSchemaContextListener.getInstance(), listener);
final SchemaContextHolder actualSchemaCtx = new SchemaContextHolder();
- final SchemaContextListener schemaCtxListener = prepareSchemaCtxListener(actualSchemaCtx);
+ final SchemaContextListener schemaCtxListener = actualSchemaCtx::setSchemaContext;
final ListenerRegistration<SchemaContextListener> registerSchemaContextListener =
schemaService.registerSchemaContextListener(schemaCtxListener);
assertEquals(registerSchemaContextListener.getInstance(), schemaCtxListener);
assertTrue(baseSchemaContext.getModules().size() == 1);
final SchemaContextHolder actualSchemaCtx = new SchemaContextHolder();
- final SchemaContextListener schemaCtxListener = prepareSchemaCtxListener(actualSchemaCtx);
-
- schemaService.registerSchemaContextListener(schemaCtxListener);
+ schemaService.registerSchemaContextListener(actualSchemaCtx::setSchemaContext);
assertEquals(baseSchemaContext, actualSchemaCtx.getSchemaContext());
assertEquals(nextSchemaContext, actualSchemaCtx.getSchemaContext());
}
- @SuppressWarnings("deprecation")
@Test
public void getSourceTest() throws Exception {
- final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("odl-datastore-test", "2014-03-13");
- final CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> source =
- schemaService.getSource(sourceIdentifier);
- final YangTextSchemaSource yangTextSchemaSource = source.checkedGet();
+ final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("odl-datastore-test",
+ Revision.of("2014-03-13"));
+ final YangTextSchemaSource yangTextSchemaSource = schemaService.getSource(sourceIdentifier).get();
final Collection<String> lines = IOUtil.readLines(yangTextSchemaSource.openStream());
assertEquals("module odl-datastore-test {", lines.iterator().next());
}
assertTrue(!registerAvailableYangs.isEmpty());
}
- private SchemaContextListener prepareSchemaCtxListener(final SchemaContextHolder actualSchemaCtx) {
- return new SchemaContextListener() {
-
- @Override
- public void onGlobalContextUpdated(final SchemaContext context) {
- actualSchemaCtx.setSchemaContext(context);
- }
- };
- }
-
private class SchemaContextHolder {
private SchemaContext schemaCtx;
*/
package org.opendaylight.mdsal.dom.broker.util;
-import java.io.InputStream;
-import java.util.Collections;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public final class TestModel {
YangInstanceIdentifier.builder(INNER_CONTAINER_PATH).node(ANOTHER_SHARD_CONTAINER).build();
public static final YangInstanceIdentifier NEW_SHARD_LIST_PATH =
YangInstanceIdentifier.builder(ANOTHER_SHARD_PATH).node(NEW_SHARD_LIST).build();
- private static final String DATASTORE_TEST_YANG = "/odl-datastore-test.yang";
private TestModel() {
throw new UnsupportedOperationException();
}
- public static SchemaContext createTestContext() throws ReactorException {
- return YangParserTestUtils.parseYangStreams(Collections.singletonList(getInputStream()));
- }
-
- private static InputStream getInputStream() {
- return TestModel.class.getResourceAsStream(DATASTORE_TEST_YANG);
+ public static SchemaContext createTestContext() {
+ return YangParserTestUtils.parseYangResource("/odl-datastore-test.yang");
}
}
package org.opendaylight.mdsal.dom.store.inmemory;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
}
public Optional<NormalizedNode<?, ?>> readNode(final PathArgument child) {
- return delegate.readNode(child);
+ return Optional.fromJavaUtil(delegate.readNode(child));
}
@Override
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
Identifiable<String>, SchemaContextListener, AutoCloseable, DOMStoreTreeChangePublisher {
private static final Logger LOG = LoggerFactory.getLogger(InMemoryDOMDataStore.class);
- private final DataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
+ private final DataTree dataTree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_OPERATIONAL);
private final AtomicLong txCounter = new AtomicLong(0);
private final InMemoryDOMStoreTreeChangePublisher changePublisher;
int dclExecutorMaxPoolSize = actualProperties.getMaxDataChangeExecutorPoolSize();
ExecutorService dataChangeListenerExecutor = SpecialExecutors.newBlockingBoundedFastThreadPool(
- dclExecutorMaxPoolSize, dclExecutorMaxQueueSize, name + "-DCL");
+ dclExecutorMaxPoolSize, dclExecutorMaxQueueSize, name + "-DCL", InMemoryDOMDataStore.class);
final InMemoryDOMDataStore dataStore = new InMemoryDOMDataStore(name, dataChangeListenerExecutor,
actualProperties.getMaxDataChangeListenerQueueSize(), debugTransactions);
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.tree.CursorAwareDataTreeSnapshot;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
final int maxDataChangeListenerQueueSize, final int submitQueueSize) {
this.prefix = Preconditions.checkNotNull(prefix);
- final TreeType treeType = treeTypeFor(prefix.getDatastoreType());
- this.dataTree = InMemoryDataTreeFactory.getInstance().create(treeType, prefix.getRootIdentifier());
+ final DataTreeConfiguration treeBaseConfig = treeTypeFor(prefix.getDatastoreType());
+ final DataTreeConfiguration treeConfig = new DataTreeConfiguration.Builder(treeBaseConfig.getTreeType())
+ .setMandatoryNodesValidation(treeBaseConfig.isMandatoryNodesValidationEnabled())
+ .setUniqueIndexes(treeBaseConfig.isUniqueIndexEnabled())
+ .setRootPath(prefix.getRootIdentifier())
+ .build();
+
+ this.dataTree = new InMemoryDataTreeFactory().create(treeConfig);
this.shardChangePublisher = new InMemoryDOMDataTreeShardChangePublisher(dataTreeChangeExecutor,
maxDataChangeListenerQueueSize, dataTree, prefix.getRootIdentifier(), childShards);
return new ChildShardContext(prefix, (WriteableDOMDataTreeShard) child);
}
- private static TreeType treeTypeFor(final LogicalDatastoreType dsType) {
+ private static DataTreeConfiguration treeTypeFor(final LogicalDatastoreType dsType) {
switch (dsType) {
case CONFIGURATION:
- return TreeType.CONFIGURATION;
+ return DataTreeConfiguration.DEFAULT_CONFIGURATION;
case OPERATIONAL:
- return TreeType.OPERATIONAL;
+ return DataTreeConfiguration.DEFAULT_OPERATIONAL;
default:
throw new IllegalArgumentException("Unsupported Data Store type:" + dsType);
}
*/
package org.opendaylight.mdsal.dom.store.inmemory;
-import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import java.util.Collection;
+import java.util.Optional;
import java.util.concurrent.ExecutorService;
import javax.annotation.Nonnull;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
}
@Override
- protected void notifyListener(AbstractDOMDataTreeChangeListenerRegistration<?> registration,
- Collection<DataTreeCandidate> changes) {
+ protected void notifyListener(final AbstractDOMDataTreeChangeListenerRegistration<?> registration,
+ final Collection<DataTreeCandidate> changes) {
LOG.debug("Enqueueing candidates {} for registration {}", changes, registration);
notificationManager.submitNotifications(registration, changes);
}
package org.opendaylight.mdsal.dom.store.inmemory;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map.Entry;
+import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import org.opendaylight.mdsal.common.api.ReadFailedException;
import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
-import java.io.IOException;
import java.util.concurrent.ExecutionException;
import org.junit.Before;
import org.junit.Ignore;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
public class InMemoryDataStoreTest {
private InMemoryDOMDataStore domStore;
@Before
- public void setupStore() throws IOException, YangSyntaxErrorException, ReactorException {
+ public void setupStore() {
domStore = new InMemoryDOMDataStore("TEST", MoreExecutors.newDirectExecutorService());
schemaContext = TestModel.createTestContext();
domStore.onGlobalContextUpdated(schemaContext);
*/
package org.opendaylight.controller.md.sal.dom.store.impl;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collections;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public final class TestModel {
public static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier.of(TEST_QNAME);
public static final YangInstanceIdentifier OUTER_LIST_PATH =
YangInstanceIdentifier.builder(TEST_PATH).node(OUTER_LIST_QNAME).build();
- private static final String DATASTORE_TEST_YANG = "/odl-datastore-test.yang";
private TestModel() {
throw new UnsupportedOperationException();
}
- public static SchemaContext createTestContext() throws IOException, YangSyntaxErrorException, ReactorException {
- return YangParserTestUtils.parseYangStreams(Collections.singletonList(getInputStream()));
- }
-
- private static InputStream getInputStream() {
- return TestModel.class.getResourceAsStream(DATASTORE_TEST_YANG);
+ public static SchemaContext createTestContext() {
+ return YangParserTestUtils.parseYangResource("/odl-datastore-test.yang");
}
}
import static org.opendaylight.mdsal.dom.store.inmemory.TestUtils.DATA_TREE;
import static org.opendaylight.mdsal.dom.store.inmemory.TestUtils.resetMocks;
-import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import java.util.Collection;
import java.util.Map;
+import java.util.Optional;
import javax.annotation.Nonnull;
import org.junit.After;
import org.junit.Before;
public class AbstractDOMShardTreeChangePublisherTest extends AbstractDOMShardTreeChangePublisher {
private static final YangInstanceIdentifier YANG_INSTANCE_IDENTIFIER =
- YangInstanceIdentifier.of(QName.create("test"));
+ YangInstanceIdentifier.of(QName.create("", "test"));
private static final DOMDataTreeIdentifier DOM_DATA_TREE_IDENTIFIER =
new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, YANG_INSTANCE_IDENTIFIER);
@Test
public void registerTreeChangeListenerTest() throws Exception {
final DOMDataTreeChangeListener domDataTreeChangeListener = mock(DOMDataTreeChangeListener.class);
- final ListenerRegistration listenerRegistration = mock(ListenerRegistration.class);
+ final ListenerRegistration<?> listenerRegistration = mock(ListenerRegistration.class);
final DataTreeSnapshot initialSnapshot = mock(DataTreeSnapshot.class);
- final DataContainerNode initialData =
+ final DataContainerNode<?> initialData =
ImmutableContainerNodeBuilder.create()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("test")))
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "test")))
.build();
doReturn(initialSnapshot).when(DATA_TREE).takeSnapshot();
doReturn(Optional.of(initialData)).when(initialSnapshot).readNode(any());
@Test(expected = UnsupportedOperationException.class)
public void registerTreeChangeListenerTestWithException() throws Exception {
final DOMDataTreeChangeListener domDataTreeChangeListener = mock(DOMDataTreeChangeListener.class);
- final ListenerRegistration listenerRegistration = mock(ListenerRegistration.class);
+ final ListenerRegistration<?> listenerRegistration = mock(ListenerRegistration.class);
doReturn(listenerRegistration)
.when(READABLE_WRITEABLE_DOM_DATA_TREE_SHARD).registerTreeChangeListener(any(), any());
final DOMDataTreeIdentifier domDataTreeIdentifier =
}
@Override
- protected void notifyListener(AbstractDOMDataTreeChangeListenerRegistration<?> registration,
- Collection<DataTreeCandidate> changes) {
+ protected void notifyListener(final AbstractDOMDataTreeChangeListenerRegistration<?> registration,
+ final Collection<DataTreeCandidate> changes) {
// NOOP
}
public class InMemoryDOMDataTreeShardTest {
@Test
- public void basicTest() throws Exception {
+ public void basicTest() {
final InMemoryDOMDataTreeShard inMemoryDOMDataTreeShard =
InMemoryDOMDataTreeShard.create(DOM_DATA_TREE_IDENTIFIER,
MoreExecutors.directExecutor(), 1);
final DOMDataTreeIdentifier domDataTreeIdentifier =
new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION,
- YangInstanceIdentifier.of(QName.create("Test")));
+ YangInstanceIdentifier.of(QName.create("", "Test")));
final ReadableWriteableDOMDataTreeShard domDataTreeShard = mock(ReadableWriteableDOMDataTreeShard.class);
doReturn("testReadableWriteableDOMDataTreeShard").when(domDataTreeShard).toString();
}
@Test
- public void createTransactionWithException() throws Exception {
+ public void createTransactionWithException() {
final DOMDataTreeIdentifier domDataTreeIdentifier =
new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY);
import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
public class InMemoryDOMDataTreeShardThreePhaseCommitCohortTest {
- private static final DataTreeCandidate DATA_TREE_CANDIDATE = mock(DataTreeCandidate.class);
+ private static final DataTreeCandidateTip DATA_TREE_CANDIDATE = mock(DataTreeCandidateTip.class);
private static final DataTreeCandidateNode DATA_TREE_CANDIDATE_NODE = mock(DataTreeCandidateNode.class);
private static final DataTreeModification DATA_TREE_MODIFICATION = mock(DataTreeModification.class);
private static final InMemoryDOMDataTreeShardChangePublisher IN_MEMORY_DOM_DATA_TREE_SHARD_CHANGE_PUBLISHER =
new InMemoryDOMDataTreeShardChangePublisher(MoreExecutors.directExecutor(), 1, DATA_TREE,
- YangInstanceIdentifier.of(QName.create("test")), ImmutableMap.of());
+ YangInstanceIdentifier.of(QName.create("", "test")), ImmutableMap.of());
private static final InMemoryDOMDataTreeShardThreePhaseCommitCohort
IN_MEMORY_DOM_DATA_TREE_SHARD_THREE_PHASE_COMMIT_COHORT =
new InMemoryDOMDataTreeShardThreePhaseCommitCohort(DATA_TREE, DATA_TREE_MODIFICATION,
import org.opendaylight.mdsal.dom.spi.shard.ReadableWriteableDOMDataTreeShard;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModificationCursor;
import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
private static final ShardRootModificationContext SHARD_ROOT_MODIFICATION_CONTEXT =
mock(ShardRootModificationContext.class);
private static final YangInstanceIdentifier YANG_INSTANCE_IDENTIFIER =
- YangInstanceIdentifier.of(QName.create("test"));
+ YangInstanceIdentifier.of(QName.create("", "test"));
private static final DOMDataTreeIdentifier DOM_DATA_TREE_IDENTIFIER =
new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, YANG_INSTANCE_IDENTIFIER);
private static final ForeignShardModificationContext FOREIGN_SHARD_MODIFICATION_CONTEXT =
doReturn(DataTreeModificationCursorAdaptor.of(dataTreeModificationCursor))
.when(SHARD_ROOT_MODIFICATION_CONTEXT).cursor();
doNothing().when(SHARD_ROOT_MODIFICATION_CONTEXT).closeCursor();
- final DataTreeCandidate dataTreeCandidate = mock(DataTreeCandidate.class);
+ final DataTreeCandidateTip dataTreeCandidate = mock(DataTreeCandidateTip.class);
final DataTreeCandidateNode dataTreeCandidateNode = mock(DataTreeCandidateNode.class);
doReturn(dataTreeCandidateNode).when(dataTreeCandidate).getRootNode();
doReturn(ModificationType.WRITE).when(dataTreeCandidateNode).getModificationType();
public void setUp() throws Exception {
doReturn(DOM_DATA_TREE_IDENTIFIER).when(SHARD_ROOT_MODIFICATION_CONTEXT).getIdentifier();
shardDataModification = TestUtils.createModification(SHARD_ROOT_MODIFICATION_CONTEXT,
- ImmutableMap.of(YangInstanceIdentifier.of(QName.create("test")), FOREIGN_SHARD_MODIFICATION_CONTEXT));
+ ImmutableMap.of(YangInstanceIdentifier.of(QName.create("", "test")),
+ FOREIGN_SHARD_MODIFICATION_CONTEXT));
final Map<DOMDataTreeIdentifier, ForeignShardModificationContext> children =
ImmutableMap.of(DOM_DATA_TREE_IDENTIFIER, FOREIGN_SHARD_MODIFICATION_CONTEXT);
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
+import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
public class OsgiBundleScanningSchemaServiceTest {
private final BundleContext bundleContext = mock(BundleContext.class, "bundleContext");
@Before
- public void setUp() throws Exception {
+ public void setUp() throws InvalidSyntaxException {
destroyInstance();
doReturn(mock(Filter.class)).when(bundleContext).createFilter(any());
doNothing().when(bundleContext).addBundleListener(any());
@SuppressWarnings("checkstyle:IllegalCatch")
@After
- public void destroyInstance() throws Exception {
+ public void destroyInstance() {
try {
OsgiBundleScanningSchemaService.getInstance();
OsgiBundleScanningSchemaService.destroyInstance();
}
@Test
- public void basicTest() throws Exception {
+ public void basicTest() {
assertTrue(osgiService instanceof DOMSchemaService);
final SchemaContext schemaContext = TestModel.createTestContext();
}
@Test(expected = UnsupportedOperationException.class)
- public void sessionContextTest() throws Exception {
+ public void sessionContextTest() {
osgiService.getSessionContext();
}
}
*/
package org.opendaylight.mdsal.dom.schema.service.osgi.util;
-import java.io.InputStream;
-import java.util.Collections;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class TestModel {
YangInstanceIdentifier.builder(INNER_CONTAINER_PATH).node(ANOTHER_SHARD_CONTAINER).build();
public static final YangInstanceIdentifier NEW_SHARD_LIST_PATH =
YangInstanceIdentifier.builder(ANOTHER_SHARD_PATH).node(NEW_SHARD_LIST).build();
- private static final String DATASTORE_TEST_YANG = "/odl-datastore-test.yang";
- public static SchemaContext createTestContext() throws ReactorException {
- return YangParserTestUtils.parseYangStreams(Collections.singletonList(getInputStream()));
- }
-
- private static InputStream getInputStream() {
- return TestModel.class.getResourceAsStream(DATASTORE_TEST_YANG);
+ public static SchemaContext createTestContext() {
+ return YangParserTestUtils.parseYangResource("/odl-datastore-test.yang");
}
}
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
-import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Optional;
import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
import org.opendaylight.mdsal.dom.api.DOMDataTreeListener;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
*/
package org.opendaylight.mdsal.dom.spi.shard;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
@Override
public Optional<NormalizedNode<?, ?>> readNode(final PathArgument arg) {
- return delegate().readNode(arg);
+ return Optional.fromJavaUtil(delegate().readNode(arg));
}
@Override
package org.opendaylight.mdsal.dom.spi.shard;
import com.google.common.annotations.Beta;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
+import java.util.Optional;
import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
}
try {
- return Futures.immediateCheckedFuture(snapshot.readNode(path));
+ return Futures.immediateCheckedFuture(Optional.fromJavaUtil(snapshot.readNode(path)));
} catch (Exception e) {
LOG.error("Tx: {} Failed Read of {}", getIdentifier(), path, e);
return Futures.immediateFailedCheckedFuture(new ReadFailedException("Read failed", e));
final Optional<NormalizedNode<?, ?>> result;
try {
- result = readSnapshotNode(path);
+ result = Optional.fromJavaUtil(readSnapshotNode(path));
} catch (Exception e) {
LOG.error("Tx: {} Failed Read of {}", getIdentifier(), path, e);
return Futures.immediateFailedCheckedFuture(new ReadFailedException("Read failed", e));
import com.google.common.annotations.Beta;
import com.google.common.base.MoreObjects.ToStringHelper;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
+import java.util.Optional;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
final DOMDataTreePrefixTableEntry<Object> domDataTreePrefixTableEntry = new DOMDataTreePrefixTableEntry<>();
final PathArgument pathArgument = mock(PathArgument.class);
final Object testObject = new Object();
- final YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.of(QName.create("test"));
+ final YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.of(QName.create("", "test"));
assertEquals(pathArgument, new DOMDataTreePrefixTableEntry<>(pathArgument).getIdentifier());
domDataTreePrefixTableEntry.store(yangInstanceIdentifier, testObject);
- assertEquals(QName.create("test"),
+ assertEquals(QName.create("", "test"),
domDataTreePrefixTableEntry.lookup(yangInstanceIdentifier).getIdentifier().getNodeType());
domDataTreePrefixTableEntry.remove(yangInstanceIdentifier);
domDataTreePrefixTableEntry.remove(yangInstanceIdentifier);
public void basicTest() throws Exception {
final DOMDataTreePrefixTable<Object> domDataTreePrefixTable = DOMDataTreePrefixTable.create();
final Object testObject = new Object();
- final YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.of(QName.create("test"));
+ final YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.of(QName.create("", "test"));
final DOMDataTreeIdentifier domDataTreeIdentifier =
new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, yangInstanceIdentifier);
domDataTreePrefixTable.store(domDataTreeIdentifier, testObject);
- assertEquals(QName.create("test"),
+ assertEquals(QName.create("", "test"),
domDataTreePrefixTable.lookup(domDataTreeIdentifier).getIdentifier().getNodeType());
domDataTreePrefixTable.remove(domDataTreeIdentifier);
assertNull(domDataTreePrefixTable.lookup(domDataTreeIdentifier).getIdentifier());
assertNotNull(registrationTreeNode.ensureChild(pathArgument));
assertNotNull(registrationTreeNode.getExactChild(pathArgument));
- final NodeWithValue<?> nodeWithValue = new NodeWithValue<>(QName.create("testNode"), new Object());
+ final NodeWithValue<?> nodeWithValue = new NodeWithValue<>(QName.create("", "testNode"), new Object());
assertEquals(Collections.EMPTY_LIST, registrationTreeNode.getInexactChildren(nodeWithValue));
assertEquals(Collections.EMPTY_LIST, registrationTreeNode.getInexactChildren(pathArgument));
- final NodeIdentifier nodeWithoutValue = new NodeIdentifier(QName.create("testNode"));
+ final NodeIdentifier nodeWithoutValue = new NodeIdentifier(QName.create("", "testNode"));
assertNotNull(registrationTreeNode.ensureChild(nodeWithoutValue));
assertFalse(registrationTreeNode.getInexactChildren(nodeWithValue).isEmpty());
public class RpcRoutingStrategyTest {
private static RpcRoutingStrategy rpcRoutingStrategy;
- private static final QName Q_NAME = QName.create("testQname");
+ private static final QName Q_NAME = QName.create("", "testQname");
private static final RpcDefinition RPC_DEFINITION = mock(RpcDefinition.class);
private static final DataSchemaNode DATA_SCHEMA_NODE = mock(DataSchemaNode.class);
private static final UnknownSchemaNode UNKNOWN_SCHEMA_NODE = mock(UnknownSchemaNode.class);
doReturn(containerSchemaNode).when(RPC_DEFINITION).getInput();
doReturn(ImmutableSet.of(DATA_SCHEMA_NODE)).when(containerSchemaNode).getChildNodes();
doReturn(ImmutableList.of(UNKNOWN_SCHEMA_NODE)).when(DATA_SCHEMA_NODE).getUnknownSchemaNodes();
- doReturn(QName.create("testNode")).when(UNKNOWN_SCHEMA_NODE).getNodeType();
+ doReturn(QName.create("", "testNode")).when(UNKNOWN_SCHEMA_NODE).getNodeType();
doReturn(Q_NAME).when(RPC_DEFINITION).getQName();
rpcRoutingStrategy = RpcRoutingStrategy.from(RPC_DEFINITION);
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
-import com.google.common.base.Optional;
+import java.util.Optional;
import org.junit.After;
import org.junit.Test;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
@Test
public void basicTest() throws Exception {
- final Optional<NormalizedNode<?, ?>> nodeOptional = Optional.absent();
+ final Optional<NormalizedNode<?, ?>> nodeOptional = Optional.empty();
doReturn(nodeOptional).when(MOCK_CURSOR_SNAPSHOT).readNode(TestUtils.PATH_ARGUMENT);
doNothing().when(MOCK_CURSOR_SNAPSHOT).exit();
doNothing().when(MOCK_CURSOR_SNAPSHOT).enter(TestUtils.PATH_ARGUMENT);
static final PathArgument PATH_ARGUMENT = mock(PathArgument.class);
- static final NodeIdentifier NODE_IDENTIFIER = NodeIdentifier.create(QName.create("test"));
+ static final NodeIdentifier NODE_IDENTIFIER = NodeIdentifier.create(QName.create("", "test"));
static final NormalizedNode<?, ?> NORMALIZED_NODE = mock(NormalizedNode.class);
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
-import com.google.common.base.Optional;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
+import java.util.Optional;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
final DataTreeCandidate dataTreeCandidate = mock(DataTreeCandidate.class);
final DataTreeCandidateNode dataTreeCandidateNode = mock(DataTreeCandidateNode.class, "dataTreeCandidateNode");
final YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.builder()
- .node(QName.create("node1")).node(QName.create("node2")).build();
+ .node(QName.create("", "node1")).node(QName.create("", "node2")).build();
doReturn(dataTreeCandidateNode).when(dataTreeCandidate).getRootNode();
doReturn(ModificationType.WRITE).when(dataTreeCandidateNode).getModificationType();
final NormalizedNode<?, ?> testNode = mock(NormalizedNode.class);
final Optional<NormalizedNode<?, ?>> optional = Optional.of(testNode);
doReturn("testNode").when(testNode).toString();
- doReturn(optional).when(DATA_TREE_SNAPSHOT).readNode(YangInstanceIdentifier.EMPTY);
+ doReturn(java.util.Optional.of(testNode)).when(DATA_TREE_SNAPSHOT).readNode(YangInstanceIdentifier.EMPTY);
assertTrue(snapshotBackedReadTransaction.exists(YangInstanceIdentifier.EMPTY).get());
assertEquals(optional, snapshotBackedReadTransaction.read(YangInstanceIdentifier.EMPTY).get());
final NormalizedNode<?, ?> testNode = mock(NormalizedNode.class);
final Optional<NormalizedNode<?, ?>> optional = Optional.of(testNode);
doReturn("testNode").when(testNode).toString();
- doReturn(optional).when(DATA_TREE_MODIFICATION).readNode(YangInstanceIdentifier.EMPTY);
+ doReturn(java.util.Optional.of(testNode)).when(DATA_TREE_MODIFICATION).readNode(YangInstanceIdentifier.EMPTY);
assertTrue(snapshotBackedReadWriteTransaction.exists(YangInstanceIdentifier.EMPTY).get());
assertEquals(optional, snapshotBackedReadWriteTransaction.read(YangInstanceIdentifier.EMPTY).get());
}
import static org.mockito.Mockito.verify;
import com.google.common.base.MoreObjects;
-import com.google.common.base.Optional;
+import java.util.Optional;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class DOMEntityOwnershipChangeTest {
private static final String ENTITY_TYPE = "type";
- private static final YangInstanceIdentifier ID = YangInstanceIdentifier.of(QName.create("test"));
+ private static final YangInstanceIdentifier ID = YangInstanceIdentifier.of(QName.create("", "test"));
private static final DOMEntity ENTITY = new DOMEntity(ENTITY_TYPE, ID);
@Test