2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.yang.parser.builder.impl;
10 import com.google.common.base.Function;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Splitter;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Iterables;
16 import com.google.common.io.ByteSource;
17 import com.google.common.io.ByteStreams;
19 import java.io.FileNotFoundException;
20 import java.io.IOException;
21 import java.io.InputStream;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.LinkedHashSet;
30 import java.util.List;
33 import java.util.TreeMap;
34 import org.antlr.v4.runtime.tree.ParseTree;
35 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Belongs_to_stmtContext;
36 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_header_stmtsContext;
37 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_stmtContext;
38 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Namespace_stmtContext;
39 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Revision_stmtsContext;
40 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Submodule_header_stmtsContext;
41 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Submodule_stmtContext;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
45 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
48 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
50 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.Module;
54 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
57 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
59 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
60 import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
61 import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationTargetBuilder;
62 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
63 import org.opendaylight.yangtools.yang.parser.builder.api.DataNodeContainerBuilder;
64 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
65 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
66 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingMember;
67 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
68 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
69 import org.opendaylight.yangtools.yang.parser.builder.api.UnknownSchemaNodeBuilder;
70 import org.opendaylight.yangtools.yang.parser.builder.api.UsesNodeBuilder;
71 import org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils;
72 import org.opendaylight.yangtools.yang.parser.impl.util.YangModelDependencyInfo;
73 import org.opendaylight.yangtools.yang.parser.util.NamedByteArrayInputStream;
74 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
75 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
79 public final class BuilderUtils {
81 private static final Logger LOG = LoggerFactory.getLogger(BuilderUtils.class);
82 private static final Splitter COLON_SPLITTER = Splitter.on(':');
83 private static final Date NULL_DATE = new Date(0L);
84 private static final String INPUT = "input";
85 private static final String OUTPUT = "output";
87 private BuilderUtils() {
90 public static Collection<ByteSource> streamsToByteSources(final Collection<InputStream> streams) throws IOException {
91 Collection<ByteSource> result = new HashSet<>();
92 for (InputStream stream : streams) {
93 result.add(new ByteSourceImpl(stream));
98 public static ByteSource fileToByteSource(final File file) {
99 return new ByteSource() {
101 public InputStream openStream() throws IOException {
102 return new NamedFileInputStream(file, file.getAbsolutePath());
107 public static Collection<ByteSource> filesToByteSources(final Collection<File> streams)
108 throws FileNotFoundException {
109 return Collections2.transform(streams, new Function<File, ByteSource>() {
111 public ByteSource apply(final File input) {
112 return new ByteSource() {
114 public InputStream openStream() throws IOException {
115 return new NamedFileInputStream(input, input.getAbsolutePath());
123 * Create new SchemaPath from given path and qname.
128 * one or more qnames added to base path
129 * @return new SchemaPath from given path and qname
131 * @deprecated Use {@link SchemaPath#createChild(QName...)} instead.
134 public static SchemaPath createSchemaPath(final SchemaPath schemaPath, final QName... qname) {
135 return schemaPath.createChild(qname);
139 * Find dependent module based on given prefix
142 * all available modules
146 * target module prefix
148 * current line in yang model
149 * @return module builder if found, null otherwise
151 public static ModuleBuilder findModuleFromBuilders(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
152 final ModuleBuilder module, final String prefix, final int line) {
153 ModuleBuilder dependentModule;
154 Date dependentModuleRevision;
156 if (prefix == null) {
157 dependentModule = module;
158 } else if (prefix.equals(module.getPrefix())) {
159 dependentModule = module;
161 ModuleImport dependentModuleImport = module.getImport(prefix);
162 if (dependentModuleImport == null) {
163 throw new YangParseException(module.getName(), line, "No import found with prefix '" + prefix + "'.");
165 String dependentModuleName = dependentModuleImport.getModuleName();
166 dependentModuleRevision = dependentModuleImport.getRevision();
168 TreeMap<Date, ModuleBuilder> moduleBuildersByRevision = modules.get(dependentModuleName);
169 if (moduleBuildersByRevision == null) {
172 if (dependentModuleRevision == null) {
173 dependentModule = moduleBuildersByRevision.lastEntry().getValue();
175 dependentModule = moduleBuildersByRevision.get(dependentModuleRevision);
178 return dependentModule;
181 public static ModuleBuilder findModuleFromBuilders(ModuleImport imp, Iterable<ModuleBuilder> modules) {
182 String name = imp.getModuleName();
183 Date revision = imp.getRevision();
184 TreeMap<Date, ModuleBuilder> map = new TreeMap<>();
185 for (ModuleBuilder module : modules) {
186 if (module != null) {
187 if (module.getName().equals(name)) {
188 map.put(module.getRevision(), module);
195 if (revision == null) {
196 return map.lastEntry().getValue();
198 return map.get(revision);
202 * Find module from context based on prefix.
206 * @param currentModule
209 * prefix used to reference dependent module
211 * current line in yang model
212 * @return module based on import with given prefix if found in context,
214 * @throws YangParseException
215 * if no import found with given prefix
217 public static Module findModuleFromContext(final SchemaContext context, final ModuleBuilder currentModule,
218 final String prefix, final int line) {
219 TreeMap<Date, Module> modulesByRevision = new TreeMap<>();
221 ModuleImport dependentModuleImport = currentModule.getImport(prefix);
222 if (dependentModuleImport == null) {
223 throw new YangParseException(currentModule.getName(), line, "No import found with prefix '" + prefix + "'.");
225 String dependentModuleName = dependentModuleImport.getModuleName();
226 Date dependentModuleRevision = dependentModuleImport.getRevision();
228 for (Module contextModule : context.getModules()) {
229 if (contextModule.getName().equals(dependentModuleName)) {
230 Date revision = contextModule.getRevision();
231 if (revision == null) {
232 revision = NULL_DATE;
234 modulesByRevision.put(revision, contextModule);
239 if (dependentModuleRevision == null) {
240 result = modulesByRevision.get(modulesByRevision.firstKey());
242 result = modulesByRevision.get(dependentModuleRevision);
244 if (result == null) {
245 throw new YangParseException(currentModule.getName(), line, "Module not found for prefix " + prefix);
252 * Add all augment's child nodes to given target.
255 * builder of augment statement
257 * augmentation target node
259 public static void fillAugmentTarget(final AugmentationSchemaBuilder augment, final Builder target) {
260 if (target instanceof DataNodeContainerBuilder) {
261 fillAugmentTarget(augment, (DataNodeContainerBuilder) target);
262 } else if (target instanceof ChoiceBuilder) {
263 fillAugmentTarget(augment, (ChoiceBuilder) target);
265 throw new YangParseException(
266 augment.getModuleName(),
268 "Error in augment parsing: The target node MUST be either a container, list, choice, case, input, output, or notification node.");
273 * Add all augment's child nodes to given target.
276 * builder of augment statement
278 * augmentation target node
280 private static void fillAugmentTarget(final AugmentationSchemaBuilder augment, final DataNodeContainerBuilder target) {
281 for (DataSchemaNodeBuilder child : augment.getChildNodeBuilders()) {
282 DataSchemaNodeBuilder childCopy = CopyUtils.copy(child, target, false);
283 if (augment.getParent() instanceof UsesNodeBuilder) {
284 setNodeAddedByUses(childCopy);
286 setNodeAugmenting(childCopy);
288 target.addChildNode(childCopy);
289 } catch (YangParseException e) {
291 // more descriptive message
292 throw new YangParseException(augment.getModuleName(), augment.getLine(),
293 "Failed to perform augmentation: " + e.getMessage());
299 * Add all augment's child nodes to given target.
302 * builder of augment statement
304 * augmentation target choice node
306 private static void fillAugmentTarget(final AugmentationSchemaBuilder augment, final ChoiceBuilder target) {
307 for (DataSchemaNodeBuilder builder : augment.getChildNodeBuilders()) {
308 DataSchemaNodeBuilder childCopy = CopyUtils.copy(builder, target, false);
309 if (augment.getParent() instanceof UsesNodeBuilder) {
310 setNodeAddedByUses(childCopy);
312 setNodeAugmenting(childCopy);
313 target.addCase(childCopy);
315 for (UsesNodeBuilder usesNode : augment.getUsesNodeBuilders()) {
316 if (usesNode != null) {
317 throw new YangParseException(augment.getModuleName(), augment.getLine(),
318 "Error in augment parsing: cannot augment choice with nodes from grouping");
324 * Set augmenting flag to true for node and all its child nodes.
328 private static void setNodeAugmenting(final DataSchemaNodeBuilder node) {
329 node.setAugmenting(true);
330 if (node instanceof DataNodeContainerBuilder) {
331 DataNodeContainerBuilder dataNodeChild = (DataNodeContainerBuilder) node;
332 for (DataSchemaNodeBuilder inner : dataNodeChild.getChildNodeBuilders()) {
333 setNodeAugmenting(inner);
335 } else if (node instanceof ChoiceBuilder) {
336 ChoiceBuilder choiceChild = (ChoiceBuilder) node;
337 for (ChoiceCaseBuilder inner : choiceChild.getCases()) {
338 setNodeAugmenting(inner);
344 * Set addedByUses flag to true for node and all its child nodes.
348 public static void setNodeAddedByUses(final GroupingMember node) {
349 node.setAddedByUses(true);
350 if (node instanceof DataNodeContainerBuilder) {
351 DataNodeContainerBuilder dataNodeChild = (DataNodeContainerBuilder) node;
352 for (DataSchemaNodeBuilder inner : dataNodeChild.getChildNodeBuilders()) {
353 setNodeAddedByUses(inner);
355 } else if (node instanceof ChoiceBuilder) {
356 ChoiceBuilder choiceChild = (ChoiceBuilder) node;
357 for (ChoiceCaseBuilder inner : choiceChild.getCases()) {
358 setNodeAddedByUses(inner);
363 public static SchemaNodeBuilder findSchemaNode(final Iterable<QName> path, final SchemaNodeBuilder parentNode) {
364 SchemaNodeBuilder node = null;
365 SchemaNodeBuilder parent = parentNode;
366 int size = Iterables.size(path);
368 for (QName qname : path) {
369 String name = qname.getLocalName();
370 if (parent instanceof DataNodeContainerBuilder) {
371 node = ((DataNodeContainerBuilder) parent).getDataChildByName(name);
373 node = findUnknownNode(name, parent);
375 } else if (parent instanceof ChoiceBuilder) {
376 node = ((ChoiceBuilder) parent).getCaseNodeByName(name);
378 node = findUnknownNode(name, parent);
380 } else if (parent instanceof RpcDefinitionBuilder) {
381 if ("input".equals(name)) {
382 node = ((RpcDefinitionBuilder) parent).getInput();
383 } else if ("output".equals(name)) {
384 node = ((RpcDefinitionBuilder) parent).getOutput();
387 node = findUnknownNode(name, parent);
391 node = findUnknownNode(name, parent);
403 private static UnknownSchemaNodeBuilder findUnknownNode(final String name, final Builder parent) {
404 for (UnknownSchemaNodeBuilder un : parent.getUnknownNodes()) {
405 if (un.getQName().getLocalName().equals(name)) {
414 * Find a builder for node in data namespace of YANG module.
416 * Search is performed on full QName equals, this means builders and schema
417 * path MUST be resolved against imports and their namespaces.
419 * Search is done in data namespace, this means notification, rpc
420 * definitions and top level data definitions are considered as top-level
421 * items, from which it is possible to traverse.
425 * Schema Path to node
427 * ModuleBuilder to start lookup in
428 * @return Node Builder if found, {@link Optional#absent()} otherwise.
430 public static Optional<SchemaNodeBuilder> findSchemaNodeInModule(final SchemaPath schemaPath,
431 final ModuleBuilder module) {
432 Iterator<QName> path = schemaPath.getPathFromRoot().iterator();
433 Preconditions.checkArgument(path.hasNext(), "Schema Path must contain at least one element.");
434 QName first = path.next();
435 Optional<SchemaNodeBuilder> currentNode = getDataNamespaceChild(module, first);
437 while (currentNode.isPresent() && path.hasNext()) {
438 SchemaNodeBuilder currentParent = currentNode.get();
439 QName currentPath = path.next();
440 currentNode = findDataChild(currentParent, currentPath);
441 if (!currentNode.isPresent()) {
442 for (SchemaNodeBuilder un : currentParent.getUnknownNodes()) {
443 if (un.getQName().equals(currentPath)) {
444 currentNode = Optional.of(un);
452 private static Optional<SchemaNodeBuilder> findDataChild(final SchemaNodeBuilder parent, final QName child) {
453 if (parent instanceof DataNodeContainerBuilder) {
454 return castOptional(SchemaNodeBuilder.class,
455 findDataChildInDataNodeContainer((DataNodeContainerBuilder) parent, child));
456 } else if (parent instanceof ChoiceBuilder) {
457 return castOptional(SchemaNodeBuilder.class, findCaseInChoice((ChoiceBuilder) parent, child));
458 } else if (parent instanceof RpcDefinitionBuilder) {
459 return castOptional(SchemaNodeBuilder.class, findContainerInRpc((RpcDefinitionBuilder) parent, child));
462 LOG.trace("Child {} not found in node {}", child, parent);
463 return Optional.absent();
468 * Casts optional from one argument to other.
471 * Class to be checked
474 * @return Optional object with type argument casted as cls
476 private static <T> Optional<T> castOptional(final Class<T> cls, final Optional<?> optional) {
477 if (optional.isPresent()) {
478 Object value = optional.get();
479 if (cls.isInstance(value)) {
480 @SuppressWarnings("unchecked")
481 // Actually checked by outer if
482 T casted = (T) value;
483 return Optional.of(casted);
486 return Optional.absent();
489 // FIXME: if rpc does not define input or output, this method creates it
492 * Gets input / output container from {@link RpcDefinitionBuilder} if QName
497 * RPC Definition builder
500 * @return Optional of input/output if defined and QName is input/output.
501 * Otherwise {@link Optional#absent()}.
503 private static Optional<ContainerSchemaNodeBuilder> findContainerInRpc(final RpcDefinitionBuilder parent,
505 if (INPUT.equals(child.getLocalName())) {
506 if (parent.getInput() == null) {
507 QName qname = QName.create(parent.getQName().getModule(), "input");
508 final ContainerSchemaNodeBuilder inputBuilder = new ContainerSchemaNodeBuilder(parent.getModuleName(),
509 parent.getLine(), qname, parent.getPath().createChild(qname));
510 inputBuilder.setParent(parent);
511 parent.setInput(inputBuilder);
512 return Optional.of(inputBuilder);
514 return Optional.of(parent.getInput());
515 } else if (OUTPUT.equals(child.getLocalName())) {
516 if (parent.getOutput() == null) {
517 QName qname = QName.create(parent.getQName().getModule(), "output");
518 final ContainerSchemaNodeBuilder outputBuilder = new ContainerSchemaNodeBuilder(parent.getModuleName(),
519 parent.getLine(), qname, parent.getPath().createChild(qname));
520 outputBuilder.setParent(parent);
521 parent.setOutput(outputBuilder);
522 return Optional.of(outputBuilder);
524 return Optional.of(parent.getOutput());
526 LOG.trace("Child {} not found in node {}", child, parent);
527 return Optional.absent();
531 * Finds case by QName in {@link ChoiceBuilder}
535 * DataNodeContainer in which lookup should be performed
538 * @return Optional of child if found.
541 private static Optional<ChoiceCaseBuilder> findCaseInChoice(final ChoiceBuilder parent, final QName child) {
542 for (ChoiceCaseBuilder caze : parent.getCases()) {
543 if (caze.getQName().equals(child)) {
544 return Optional.of(caze);
547 LOG.trace("Child {} not found in node {}", child, parent);
548 return Optional.absent();
552 * Finds direct child by QName in {@link DataNodeContainerBuilder}
556 * DataNodeContainer in which lookup should be performed
559 * @return Optional of child if found.
561 private static Optional<DataSchemaNodeBuilder> findDataChildInDataNodeContainer(final DataNodeContainerBuilder parent,
563 for (DataSchemaNodeBuilder childNode : parent.getChildNodeBuilders()) {
564 if (childNode.getQName().equals(child)) {
565 return Optional.of(childNode);
568 LOG.trace("Child {} not found in node {}", child, parent);
569 return Optional.absent();
574 * Find a child builder for node in data namespace of YANG module.
576 * Search is performed on full QName equals, this means builders and schema
577 * path MUST be resolved against imports and their namespaces.
579 * Search is done in data namespace, this means notification, rpc
580 * definitions and top level data definitions are considered as top-level
581 * items, from which it is possible to traverse.
587 * ModuleBuilder to start lookup in
588 * @return Node Builder if found, {@link Optional#absent()} otherwise.
590 private static Optional<SchemaNodeBuilder> getDataNamespaceChild(final ModuleBuilder module, final QName child) {
592 * First we do lookup in data tree, if node is found we return it.
594 final Optional<SchemaNodeBuilder> dataTreeNode = getDataChildByQName(module, child);
595 if (dataTreeNode.isPresent()) {
600 * We lookup in notifications
602 Set<NotificationBuilder> notifications = module.getAddedNotifications();
603 for (NotificationBuilder notification : notifications) {
604 if (notification.getQName().equals(child)) {
605 return Optional.<SchemaNodeBuilder> of(notification);
612 Set<RpcDefinitionBuilder> rpcs = module.getAddedRpcs();
613 for (RpcDefinitionBuilder rpc : rpcs) {
614 if (rpc.getQName().equals(child)) {
615 return Optional.<SchemaNodeBuilder> of(rpc);
618 LOG.trace("Child {} not found in data namespace of module {}", child, module);
619 return Optional.absent();
622 private static Optional<SchemaNodeBuilder> getDataChildByQName(final DataNodeContainerBuilder builder, final QName child) {
623 for (DataSchemaNodeBuilder childNode : builder.getChildNodeBuilders()) {
624 if (childNode.getQName().equals(child)) {
625 return Optional.<SchemaNodeBuilder> of(childNode);
628 LOG.trace("Child {} not found in node {}", child, builder);
629 return Optional.absent();
633 * Find augment target node and perform augmentation.
636 * augment builder to process
637 * @param firstNodeParent
638 * parent of first node in path
639 * @return true if augmentation process succeed, false otherwise
641 public static boolean processAugmentation(final AugmentationSchemaBuilder augment,
642 final ModuleBuilder firstNodeParent) {
643 Optional<SchemaNodeBuilder> potentialTargetNode = findSchemaNodeInModule(augment.getTargetPath(),
645 if (!potentialTargetNode.isPresent()) {
647 } else if (potentialTargetNode.get() instanceof UnknownSchemaNodeBuilder) {
648 LOG.warn("Error in augment parsing: unsupported augment target: {}", potentialTargetNode.get());
651 SchemaNodeBuilder targetNode = potentialTargetNode.get();
652 fillAugmentTarget(augment, targetNode);
653 Preconditions.checkState(targetNode instanceof AugmentationTargetBuilder,
654 "Node refered by augmentation must be valid augmentation target");
655 ((AugmentationTargetBuilder) targetNode).addAugmentation(augment);
656 augment.setResolved(true);
660 public static IdentitySchemaNodeBuilder findBaseIdentity(final ModuleBuilder module, final String baseString,
663 // FIXME: optimize indexOf() away?
664 if (baseString.indexOf(':') != -1) {
665 final Iterator<String> it = COLON_SPLITTER.split(baseString).iterator();
666 final String prefix = it.next();
667 final String name = it.next();
670 throw new YangParseException(module.getName(), line, "Failed to parse identityref base: " + baseString);
673 ModuleBuilder dependentModule = getModuleByPrefix(module, prefix);
674 if (dependentModule == null) {
678 return findIdentity(dependentModule.getAddedIdentities(), name);
680 return findIdentity(module.getAddedIdentities(), baseString);
684 public static IdentitySchemaNodeBuilder findIdentity(final Set<IdentitySchemaNodeBuilder> identities,
686 for (IdentitySchemaNodeBuilder identity : identities) {
687 if (identity.getQName().getLocalName().equals(name)) {
695 * Get module in which this node is defined.
698 * @return builder of module where this node is defined
700 public static ModuleBuilder getParentModule(final Builder node) {
701 if (node instanceof ModuleBuilder) {
702 return (ModuleBuilder) node;
704 Builder parent = node.getParent();
705 while (!(parent instanceof ModuleBuilder)) {
706 parent = parent.getParent();
708 ModuleBuilder parentModule = (ModuleBuilder) parent;
709 if (parentModule.isSubmodule()) {
710 parentModule = parentModule.getParent();
715 public static Set<DataSchemaNodeBuilder> wrapChildNodes(final String moduleName, final int line,
716 final Collection<DataSchemaNode> nodes, final SchemaPath parentPath, final QName parentQName) {
717 Set<DataSchemaNodeBuilder> result = new LinkedHashSet<>(nodes.size());
719 for (DataSchemaNode node : nodes) {
720 QName qname = QName.create(parentQName, node.getQName().getLocalName());
721 DataSchemaNodeBuilder wrapped = wrapChildNode(moduleName, line, node, parentPath, qname);
727 public static DataSchemaNodeBuilder wrapChildNode(final String moduleName, final int line,
728 final DataSchemaNode node, final SchemaPath parentPath, final QName qname) {
730 final SchemaPath schemaPath = parentPath.createChild(qname);
732 if (node instanceof AnyXmlSchemaNode) {
733 return new AnyXmlBuilder(moduleName, line, qname, schemaPath, ((AnyXmlSchemaNode) node));
734 } else if (node instanceof ChoiceSchemaNode) {
735 return new ChoiceBuilder(moduleName, line, qname, schemaPath, ((ChoiceSchemaNode) node));
736 } else if (node instanceof ContainerSchemaNode) {
737 return new ContainerSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((ContainerSchemaNode) node));
738 } else if (node instanceof LeafSchemaNode) {
739 return new LeafSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((LeafSchemaNode) node));
740 } else if (node instanceof LeafListSchemaNode) {
741 return new LeafListSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((LeafListSchemaNode) node));
742 } else if (node instanceof ListSchemaNode) {
743 return new ListSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((ListSchemaNode) node));
744 } else if (node instanceof ChoiceCaseNode) {
745 return new ChoiceCaseBuilder(moduleName, line, qname, schemaPath, ((ChoiceCaseNode) node));
747 throw new YangParseException(moduleName, line, "Failed to copy node: Unknown type of DataSchemaNode: "
752 public static Set<GroupingBuilder> wrapGroupings(final String moduleName, final int line,
753 final Set<GroupingDefinition> nodes, final SchemaPath parentPath, final QName parentQName) {
754 Set<GroupingBuilder> result = new HashSet<>();
755 for (GroupingDefinition node : nodes) {
756 QName qname = QName.create(parentQName, node.getQName().getLocalName());
757 SchemaPath schemaPath = parentPath.createChild(qname);
758 result.add(new GroupingBuilderImpl(moduleName, line, qname, schemaPath, node));
763 public static Set<TypeDefinitionBuilder> wrapTypedefs(final String moduleName, final int line,
764 final DataNodeContainer dataNode, final SchemaPath parentPath, final QName parentQName) {
765 Set<TypeDefinition<?>> nodes = dataNode.getTypeDefinitions();
766 Set<TypeDefinitionBuilder> result = new HashSet<>();
767 for (TypeDefinition<?> node : nodes) {
768 QName qname = QName.create(parentQName, node.getQName().getLocalName());
769 SchemaPath schemaPath = parentPath.createChild(qname);
770 result.add(new TypeDefinitionBuilderImpl(moduleName, line, qname, schemaPath, ((ExtendedType) node)));
775 public static List<UnknownSchemaNodeBuilderImpl> wrapUnknownNodes(final String moduleName, final int line,
776 final List<UnknownSchemaNode> nodes, final SchemaPath parentPath, final QName parentQName) {
777 List<UnknownSchemaNodeBuilderImpl> result = new ArrayList<>();
778 for (UnknownSchemaNode node : nodes) {
779 QName qname = QName.create(parentQName, node.getQName().getLocalName());
780 SchemaPath schemaPath = parentPath.createChild(qname);
781 result.add(new UnknownSchemaNodeBuilderImpl(moduleName, line, qname, schemaPath, node));
786 private static final class ByteSourceImpl extends ByteSource {
787 private final String toString;
788 private final byte[] data;
790 private ByteSourceImpl(final InputStream input) throws IOException {
791 toString = input.toString();
792 data = ByteStreams.toByteArray(input);
796 public InputStream openStream() throws IOException {
797 return new NamedByteArrayInputStream(data, toString);
801 public static ModuleBuilder getModuleByPrefix(final ModuleBuilder module, final String prefix) {
802 if (prefix == null || prefix.isEmpty() || prefix.equals(module.getPrefix())) {
805 return module.getImportedModule(prefix);
809 public static ModuleBuilder findModule(final QName qname, final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
810 TreeMap<Date, ModuleBuilder> map = modules.get(qname.getNamespace());
814 if (qname.getRevision() == null) {
815 return map.lastEntry().getValue();
817 return map.get(qname.getRevision());
820 public static Map<String, TreeMap<Date, URI>> createYangNamespaceContext(
821 final Collection<? extends ParseTree> modules, final Optional<SchemaContext> context) {
822 Map<String, TreeMap<Date, URI>> namespaceContext = new HashMap<>();
823 Set<Submodule_stmtContext> submodules = new HashSet<>();
824 // first read ParseTree collection and separate modules and submodules
825 for (ParseTree module : modules) {
826 for (int i = 0; i < module.getChildCount(); i++) {
827 ParseTree moduleTree = module.getChild(i);
828 if (moduleTree instanceof Submodule_stmtContext) {
829 // put submodule context to separate collection
830 submodules.add((Submodule_stmtContext) moduleTree);
831 } else if (moduleTree instanceof Module_stmtContext) {
832 // get name, revision and namespace from module
833 Module_stmtContext moduleCtx = (Module_stmtContext) moduleTree;
834 final String moduleName = ParserListenerUtils.stringFromNode(moduleCtx);
836 URI namespace = null;
837 for (int j = 0; j < moduleCtx.getChildCount(); j++) {
838 ParseTree moduleCtxChildTree = moduleCtx.getChild(j);
839 if (moduleCtxChildTree instanceof Revision_stmtsContext) {
840 String revisionDateStr = YangModelDependencyInfo
841 .getLatestRevision((Revision_stmtsContext) moduleCtxChildTree);
842 if (revisionDateStr == null) {
845 rev = QName.parseRevision(revisionDateStr);
848 if (moduleCtxChildTree instanceof Module_header_stmtsContext) {
849 Module_header_stmtsContext headerCtx = (Module_header_stmtsContext) moduleCtxChildTree;
850 for (int k = 0; k < headerCtx.getChildCount(); k++) {
851 ParseTree ctx = headerCtx.getChild(k);
852 if (ctx instanceof Namespace_stmtContext) {
853 final String namespaceStr = ParserListenerUtils.stringFromNode(ctx);
854 namespace = URI.create(namespaceStr);
860 // update namespaceContext
861 TreeMap<Date, URI> revToNs = namespaceContext.get(moduleName);
862 if (revToNs == null) {
863 revToNs = new TreeMap<>();
864 revToNs.put(rev, namespace);
865 namespaceContext.put(moduleName, revToNs);
867 revToNs.put(rev, namespace);
871 // after all ParseTree-s are parsed update namespaceContext with modules
872 // from SchemaContext
873 if (context.isPresent()) {
874 for (Module module : context.get().getModules()) {
875 TreeMap<Date, URI> revToNs = namespaceContext.get(module.getName());
876 if (revToNs == null) {
877 revToNs = new TreeMap<>();
878 revToNs.put(module.getRevision(), module.getNamespace());
879 namespaceContext.put(module.getName(), revToNs);
881 revToNs.put(module.getRevision(), module.getNamespace());
884 // when all modules are processed, traverse submodules and update
885 // namespaceContext with mapping for submodules
886 for (Submodule_stmtContext submodule : submodules) {
887 final String moduleName = ParserListenerUtils.stringFromNode(submodule);
888 for (int i = 0; i < submodule.getChildCount(); i++) {
889 ParseTree subHeaderCtx = submodule.getChild(i);
890 if (subHeaderCtx instanceof Submodule_header_stmtsContext) {
891 for (int j = 0; j < subHeaderCtx.getChildCount(); j++) {
892 ParseTree belongsCtx = subHeaderCtx.getChild(j);
893 if (belongsCtx instanceof Belongs_to_stmtContext) {
894 final String belongsTo = ParserListenerUtils.stringFromNode(belongsCtx);
895 TreeMap<Date, URI> ns = namespaceContext.get(belongsTo);
897 throw new YangParseException(moduleName, submodule.getStart().getLine(), String.format(
898 "Unresolved belongs-to statement: %s", belongsTo));
900 // submodule get namespace and revision from module
901 TreeMap<Date, URI> subNs = new TreeMap<>();
902 subNs.put(ns.firstKey(), ns.firstEntry().getValue());
903 namespaceContext.put(moduleName, subNs);
909 return namespaceContext;