* Local name part of QName. MUST NOT BE null.
* @return
* @throws NullPointerException
- * If any of paramaters is null.
+ * If any of parameters is null.
* @throws IllegalArgumentException
* If <code>namespace</code> is not valid URI or
* <code>revision</code> is not according to format
*/
public static QName create(final String namespace, final String revision, final String localName)
throws IllegalArgumentException {
- final URI namespaceUri;
+ final URI namespaceUri = parseNamespace(namespace);
+ final Date revisionDate = parseRevision(revision);
+ return create(namespaceUri, revisionDate, localName);
+ }
+
+ private static URI parseNamespace(final String namespace) {
try {
- namespaceUri = new URI(namespace);
+ return new URI(namespace);
} catch (URISyntaxException ue) {
throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
}
+ }
- Date revisionDate = parseRevision(revision);
- return create(namespaceUri, revisionDate, localName);
+ /**
+ * Creates new QName.
+ *
+ * @param namespace
+ * Namespace of QName, MUST NOT BE Null.
+ * @param localName
+ * Local name part of QName. MUST NOT BE null.
+ * @return
+ * @throws NullPointerException
+ * If any of parameters is null.
+ * @throws IllegalArgumentException
+ * If <code>namespace</code> is not valid URI.
+ */
+ public static QName create(final String namespace, final String localName) throws IllegalArgumentException {
+ return create(parseNamespace(namespace), null, localName);
}
@Override
@Nonnull ModificationType getModificationType();
/**
- * Return the before-image of data corresponding to the node.
+ * Return the after-image of data corresponding to the node.
*
- * @return Node data as they were present in the tree before
- * the modification was applied.
+ * @return Node data as they will be present in the tree after
+ * the modification is applied.
*/
- Optional<NormalizedNode<?, ?>> getDataAfter();
+ @Nonnull Optional<NormalizedNode<?, ?>> getDataAfter();
/**
- * Return the after-image of data corresponding to the node.
+ * Return the before-image of data corresponding to the node.
*
- * @return Node data as they will be present in the tree after
- * the modification is applied.
+ * @return Node data as they were present in the tree before
+ * the modification was applied.
*/
- Optional<NormalizedNode<?, ?>> getDataBefore();
+ @Nonnull Optional<NormalizedNode<?, ?>> getDataBefore();
}
*/
package org.opendaylight.yangtools.yang.data.impl.schema;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import java.util.Map;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.ModifyAction;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableChoiceNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public final class ImmutableNodes {
public static ChoiceNode choiceNode(final QName name) {
return ImmutableChoiceNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(name)).build();
}
+
+ /**
+ * Convert YangInstanceIdentifier into a normalized node structure
+ *
+ * @param ctx schema context to used during serialization
+ * @param id instance identifier to convert to node structure starting from root
+ * @return serialized normalized node for provided instance Id
+ */
+ public static NormalizedNode<?, ?> fromInstanceId(final SchemaContext ctx, final YangInstanceIdentifier id) {
+ return fromInstanceId(ctx, id, Optional.<NormalizedNode<?, ?>>absent(), Optional.<Map.Entry<QName, ModifyAction>>absent());
+ }
+
+ /**
+ * Convert YangInstanceIdentifier into a normalized node structure
+ *
+ * @param ctx schema context to used during serialization
+ * @param id instance identifier to convert to node structure starting from root
+ * @param deepestElement pre-built deepest child that will be inserted at the last path argument of provided instance Id
+ * @return serialized normalized node for provided instance Id with overridden last child.
+ */
+ public static NormalizedNode<?, ?> fromInstanceId(final SchemaContext ctx, final YangInstanceIdentifier id, final NormalizedNode<?, ?> deepestElement) {
+ return fromInstanceId(ctx, id, Optional.<NormalizedNode<?, ?>>of(deepestElement), Optional.<Map.Entry<QName, ModifyAction>>absent());
+ }
+
+ /**
+ * Convert YangInstanceIdentifier into a normalized node structure
+ *
+ * @param ctx schema context to used during serialization
+ * @param id instance identifier to convert to node structure starting from root
+ * @param deepestElement pre-built deepest child that will be inserted at the last path argument of provided instance Id
+ * @param operation modify operation attribute to be added to the deepest child. QName is the operation attribute key and ModifyAction is the value.
+ * @return serialized normalized node for provided instance Id with (optionally) overridden last child and (optionally) marked with specific operation attribute.
+ */
+ public static NormalizedNode<?, ?> fromInstanceId(final SchemaContext ctx, final YangInstanceIdentifier id, final Optional<NormalizedNode<?, ?>> deepestElement, final Optional<Map.Entry<QName, ModifyAction>> operation) {
+ Preconditions.checkNotNull(ctx);
+ Preconditions.checkNotNull(id);
+ final YangInstanceIdentifier.PathArgument topLevelElement = id.getPathArguments().iterator().next();
+ final DataSchemaNode dataChildByName = ctx.getDataChildByName(topLevelElement.getNodeType());
+ Preconditions.checkNotNull(dataChildByName, "Cannot find %s node in schema context. Instance identifier has to start from root", topLevelElement);
+ final InstanceIdToNodes<?> instanceIdToNodes = InstanceIdToNodes.fromSchemaAndQNameChecked(ctx, topLevelElement.getNodeType());
+ return instanceIdToNodes.create(id, deepestElement, operation);
+ }
}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.ModifyAction;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.AttributesBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+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.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
+
+/**
+* Base strategy for converting an instance identifier into a normalized node structure for container-like types.
+*/
+abstract class InstanceIdToCompositeNodes<T extends YangInstanceIdentifier.PathArgument> extends
+ InstanceIdToNodes<T> {
+
+ protected InstanceIdToCompositeNodes(final T identifier) {
+ super(identifier);
+ }
+
+ private static YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifierFrom(final AugmentationSchema augmentation) {
+ final ImmutableSet.Builder<QName> potentialChildren = ImmutableSet.builder();
+ for (final DataSchemaNode child : augmentation.getChildNodes()) {
+ potentialChildren.add(child.getQName());
+ }
+ return new YangInstanceIdentifier.AugmentationIdentifier(potentialChildren.build());
+ }
+
+ private static DataNodeContainer augmentationProxy(final AugmentationSchema augmentation, final DataNodeContainer schema) {
+ final Set<DataSchemaNode> children = new HashSet<>();
+ for (final DataSchemaNode augNode : augmentation.getChildNodes()) {
+ children.add(schema.getDataChildByName(augNode.getQName()));
+ }
+ return new EffectiveAugmentationSchema(augmentation, children);
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public final NormalizedNode<?, ?> create(final YangInstanceIdentifier instanceId, final Optional<NormalizedNode<?, ?>> lastChild, final Optional<Map.Entry<QName,ModifyAction>> operation) {
+ checkNotNull(instanceId);
+ final Iterator<YangInstanceIdentifier.PathArgument> iterator = instanceId.getPathArguments().iterator();
+ final YangInstanceIdentifier.PathArgument legacyData = iterator.next();
+
+ if (!isMixin(this) && getIdentifier().getNodeType() != null) {
+ checkArgument(getIdentifier().getNodeType().equals(legacyData.getNodeType()),
+ "Node QName must be %s was %s", getIdentifier().getNodeType(), legacyData.getNodeType());
+ }
+ final NormalizedNodeContainerBuilder builder = createBuilder(legacyData);
+
+ if (iterator.hasNext()) {
+ final YangInstanceIdentifier.PathArgument childPath = iterator.next();
+ final InstanceIdToNodes childOp = getChildOperation(childPath);
+
+ final YangInstanceIdentifier childId = YangInstanceIdentifier.create(Iterables.skip(instanceId.getPathArguments(), 1));
+ builder.addChild(childOp.create(childId, lastChild, operation));
+ } else {
+ if(lastChild.isPresent()) {
+ builder.withValue(Lists.newArrayList((Collection<?>) lastChild.get().getValue()));
+ }
+ if(operation.isPresent()) {
+ Preconditions.checkArgument(builder instanceof AttributesBuilder<?>);
+ addModifyOpIfPresent(operation, ((AttributesBuilder<?>) builder));
+ }
+ }
+
+ return builder.build();
+ }
+
+ private InstanceIdToNodes getChildOperation(final YangInstanceIdentifier.PathArgument childPath) {
+ final InstanceIdToNodes childOp;
+ try {
+ childOp = getChild(childPath);
+ } catch (final RuntimeException e) {
+ throw new IllegalArgumentException(String.format("Failed to process child node %s", childPath), e);
+ }
+ checkArgument(childOp != null, "Node %s is not allowed inside %s", childPath, getIdentifier());
+ return childOp;
+ }
+
+ @SuppressWarnings("rawtypes")
+ protected abstract NormalizedNodeContainerBuilder<?, ?, ?, ?> createBuilder(final YangInstanceIdentifier.PathArgument compositeNode);
+
+ static abstract class DataContainerNormalizationOperation<T extends YangInstanceIdentifier.PathArgument> extends
+ InstanceIdToCompositeNodes<T> {
+
+ private final DataNodeContainer schema;
+ private final Map<YangInstanceIdentifier.PathArgument, InstanceIdToNodes<?>> byArg;
+
+ protected DataContainerNormalizationOperation(final T identifier, final DataNodeContainer schema) {
+ super(identifier);
+ this.schema = schema;
+ this.byArg = new ConcurrentHashMap<>();
+ }
+
+ @Override
+ public InstanceIdToNodes<?> getChild(final YangInstanceIdentifier.PathArgument child) {
+ InstanceIdToNodes<?> potential = byArg.get(child);
+ if (potential != null) {
+ return potential;
+ }
+ potential = fromLocalSchema(child);
+ return register(potential);
+ }
+
+ private InstanceIdToNodes<?> fromLocalSchema(final YangInstanceIdentifier.PathArgument child) {
+ if (child instanceof YangInstanceIdentifier.AugmentationIdentifier) {
+ return fromSchemaAndQNameChecked(schema, ((YangInstanceIdentifier.AugmentationIdentifier) child).getPossibleChildNames()
+ .iterator().next());
+ }
+ return fromSchemaAndQNameChecked(schema, child.getNodeType());
+ }
+
+ private InstanceIdToNodes<?> register(final InstanceIdToNodes<?> potential) {
+ if (potential != null) {
+ byArg.put(potential.getIdentifier(), potential);
+ }
+ return potential;
+ }
+ }
+
+ static final class ListItemNormalization extends
+ DataContainerNormalizationOperation<YangInstanceIdentifier.NodeIdentifierWithPredicates> {
+
+ protected ListItemNormalization(final YangInstanceIdentifier.NodeIdentifierWithPredicates identifier, final ListSchemaNode schema) {
+ super(identifier, schema);
+ }
+
+ @Override
+ protected NormalizedNodeContainerBuilder<?, ?, ?, ?> createBuilder(final YangInstanceIdentifier.PathArgument currentArg) {
+ final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> builder = Builders
+ .mapEntryBuilder().withNodeIdentifier((YangInstanceIdentifier.NodeIdentifierWithPredicates) currentArg);
+ for (final Map.Entry<QName, Object> keyValue : ((YangInstanceIdentifier.NodeIdentifierWithPredicates) currentArg).getKeyValues().entrySet()) {
+ builder.addChild(Builders.leafBuilder()
+ //
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(keyValue.getKey())).withValue(keyValue.getValue())
+ .build());
+ }
+ return builder;
+ }
+
+ }
+
+ static final class UnkeyedListItemNormalization extends DataContainerNormalizationOperation<YangInstanceIdentifier.NodeIdentifier> {
+
+ protected UnkeyedListItemNormalization(final ListSchemaNode schema) {
+ super(new YangInstanceIdentifier.NodeIdentifier(schema.getQName()), schema);
+ }
+
+ @Override
+ protected NormalizedNodeContainerBuilder<?, ?, ?, ?> createBuilder(final YangInstanceIdentifier.PathArgument compositeNode) {
+ return Builders.unkeyedListEntryBuilder().withNodeIdentifier(getIdentifier());
+ }
+
+ }
+
+ static final class ContainerTransformation extends DataContainerNormalizationOperation<YangInstanceIdentifier.NodeIdentifier> {
+
+ protected ContainerTransformation(final ContainerSchemaNode schema) {
+ super(new YangInstanceIdentifier.NodeIdentifier(schema.getQName()), schema);
+ }
+
+ @Override
+ protected NormalizedNodeContainerBuilder<?, ?, ?, ?> createBuilder(final YangInstanceIdentifier.PathArgument compositeNode) {
+ return Builders.containerBuilder().withNodeIdentifier(getIdentifier());
+ }
+ }
+
+ static final class OrderedLeafListMixinNormalization extends UnorderedLeafListMixinNormalization {
+
+
+ public OrderedLeafListMixinNormalization(final LeafListSchemaNode potential) {
+ super(potential);
+ }
+
+ @Override
+ protected NormalizedNodeContainerBuilder<?, ?, ?, ?> createBuilder(final YangInstanceIdentifier.PathArgument compositeNode) {
+ return Builders.orderedLeafSetBuilder().withNodeIdentifier(getIdentifier());
+ }
+ }
+
+ static class UnorderedLeafListMixinNormalization extends InstanceIdToCompositeNodes<YangInstanceIdentifier.NodeIdentifier> implements MixinNormalizationOp {
+
+ private final InstanceIdToNodes<?> innerOp;
+
+ public UnorderedLeafListMixinNormalization(final LeafListSchemaNode potential) {
+ super(new YangInstanceIdentifier.NodeIdentifier(potential.getQName()));
+ innerOp = new InstanceIdToSimpleNodes.LeafListEntryNormalization(potential);
+ }
+
+ @Override
+ protected NormalizedNodeContainerBuilder<?, ?, ?, ?> createBuilder(final YangInstanceIdentifier.PathArgument compositeNode) {
+ return Builders.leafSetBuilder().withNodeIdentifier(getIdentifier());
+ }
+
+ @Override
+ public InstanceIdToNodes<?> getChild(final YangInstanceIdentifier.PathArgument child) {
+ if (child instanceof YangInstanceIdentifier.NodeWithValue) {
+ return innerOp;
+ }
+ return null;
+ }
+ }
+
+ static final class AugmentationNormalization extends DataContainerNormalizationOperation<YangInstanceIdentifier.AugmentationIdentifier> implements MixinNormalizationOp {
+
+ public AugmentationNormalization(final AugmentationSchema augmentation, final DataNodeContainer schema) {
+ super(augmentationIdentifierFrom(augmentation), augmentationProxy(augmentation, schema));
+ }
+
+ @Override
+ protected NormalizedNodeContainerBuilder<?, ?, ?, ?> createBuilder(final YangInstanceIdentifier.PathArgument compositeNode) {
+ return Builders.augmentationBuilder().withNodeIdentifier(getIdentifier());
+ }
+ }
+
+ static class UnorderedMapMixinNormalization extends InstanceIdToCompositeNodes<YangInstanceIdentifier.NodeIdentifier> implements MixinNormalizationOp {
+
+ private final ListItemNormalization innerNode;
+
+ public UnorderedMapMixinNormalization(final ListSchemaNode list) {
+ super(new YangInstanceIdentifier.NodeIdentifier(list.getQName()));
+ this.innerNode = new ListItemNormalization(new YangInstanceIdentifier.NodeIdentifierWithPredicates(list.getQName(),
+ Collections.<QName, Object>emptyMap()), list);
+ }
+
+ @Override
+ protected NormalizedNodeContainerBuilder<?, ?, ?, ?> createBuilder(final YangInstanceIdentifier.PathArgument compositeNode) {
+ return Builders.mapBuilder().withNodeIdentifier(getIdentifier());
+ }
+
+ @Override
+ public InstanceIdToNodes<?> getChild(final YangInstanceIdentifier.PathArgument child) {
+ if (child.getNodeType().equals(getIdentifier().getNodeType())) {
+ return innerNode;
+ }
+ return null;
+ }
+ }
+
+ static final class OrderedMapMixinNormalization extends UnorderedMapMixinNormalization {
+
+ public OrderedMapMixinNormalization(final ListSchemaNode list) {
+ super(list);
+ }
+
+ @Override
+ protected NormalizedNodeContainerBuilder<?, ?, ?, ?> createBuilder(final YangInstanceIdentifier.PathArgument compositeNode) {
+ return Builders.orderedMapBuilder().withNodeIdentifier(getIdentifier());
+ }
+
+ }
+
+ static class ChoiceNodeNormalization extends InstanceIdToCompositeNodes<YangInstanceIdentifier.NodeIdentifier> implements MixinNormalizationOp {
+
+ private final ImmutableMap<YangInstanceIdentifier.PathArgument, InstanceIdToNodes<?>> byArg;
+
+ protected ChoiceNodeNormalization(final ChoiceSchemaNode schema) {
+ super(new YangInstanceIdentifier.NodeIdentifier(schema.getQName()));
+ final ImmutableMap.Builder<YangInstanceIdentifier.PathArgument, InstanceIdToNodes<?>> byArgBuilder = ImmutableMap.builder();
+
+ for (final ChoiceCaseNode caze : schema.getCases()) {
+ for (final DataSchemaNode cazeChild : caze.getChildNodes()) {
+ final InstanceIdToNodes<?> childOp = fromDataSchemaNode(cazeChild);
+ byArgBuilder.put(childOp.getIdentifier(), childOp);
+ }
+ }
+ byArg = byArgBuilder.build();
+ }
+
+ @Override
+ public InstanceIdToNodes<?> getChild(final YangInstanceIdentifier.PathArgument child) {
+ return byArg.get(child);
+ }
+
+ @Override
+ protected NormalizedNodeContainerBuilder<?, ?, ?, ?> createBuilder(final YangInstanceIdentifier.PathArgument compositeNode) {
+ return Builders.choiceBuilder().withNodeIdentifier(getIdentifier());
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.FluentIterable;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map.Entry;
+import javax.xml.transform.dom.DOMSource;
+import org.opendaylight.yangtools.concepts.Identifiable;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.ModifyAction;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.AttributesBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+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.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+/**
+ * Base strategy for converting an instance identifier into a normalized node structure.
+ * Use provided static methods for generic YangInstanceIdentifier -> NormalizedNode translation in ImmutableNodes.
+ */
+abstract class InstanceIdToNodes<T extends PathArgument> implements Identifiable<T> {
+
+ private final T identifier;
+
+ @Override
+ public T getIdentifier() {
+ return identifier;
+ }
+
+ protected InstanceIdToNodes(final T identifier) {
+ this.identifier = identifier;
+ }
+
+ /**
+ * Build a strategy for the next path argument
+ *
+ * @param child child identifier
+ * @return transformation strategy for a specific child
+ */
+ abstract InstanceIdToNodes<?> getChild(final PathArgument child);
+
+ /**
+ *
+ * Convert instance identifier into a NormalizedNode structure
+ *
+ * @param instanceId Instance identifier to transform into NormalizedNodes
+ * @param deepestChild Optional normalized node to be inserted as the last child
+ * @param operation Optional modify operation to be set on the last child
+ * @return NormalizedNode structure corresponding to submitted instance ID
+ */
+ abstract NormalizedNode<?, ?> create(YangInstanceIdentifier instanceId, Optional<NormalizedNode<?, ?>> deepestChild, Optional<Entry<QName,ModifyAction>> operation);
+
+
+ public void addModifyOpIfPresent(final Optional<Entry<QName,ModifyAction>> operation, final AttributesBuilder<?> builder) {
+ if(operation.isPresent()) {
+ builder.withAttributes(Collections.singletonMap(operation.get().getKey(), modifyOperationToXmlString(operation.get().getValue())));
+ }
+ }
+
+ public static String modifyOperationToXmlString(final ModifyAction operation) {
+ return operation.name().toLowerCase();
+ }
+
+ static boolean isMixin(final InstanceIdToNodes<?> op) {
+ return op instanceof MixinNormalizationOp;
+ }
+
+ /**
+ * Marker interface for Mixin nodes normalization operations
+ */
+ interface MixinNormalizationOp {}
+
+
+ private static class UnkeyedListMixinNormalization extends InstanceIdToCompositeNodes<NodeIdentifier> implements MixinNormalizationOp {
+
+ private final UnkeyedListItemNormalization innerNode;
+
+ public UnkeyedListMixinNormalization(final ListSchemaNode list) {
+ super(new NodeIdentifier(list.getQName()));
+ this.innerNode = new UnkeyedListItemNormalization(list);
+ }
+
+ @Override
+ protected NormalizedNodeContainerBuilder<?, ?, ?, ?> createBuilder(final PathArgument compositeNode) {
+ return Builders.unkeyedListBuilder().withNodeIdentifier(getIdentifier());
+ }
+
+ @Override
+ public InstanceIdToNodes<?> getChild(final PathArgument child) {
+ if (child.getNodeType().equals(getIdentifier().getNodeType())) {
+ return innerNode;
+ }
+ return null;
+ }
+ }
+
+ private static class AnyXmlNormalization extends InstanceIdToNodes<NodeIdentifier> {
+
+ protected AnyXmlNormalization(final AnyXmlSchemaNode schema) {
+ super(new NodeIdentifier(schema.getQName()));
+ }
+
+ @Override
+ public InstanceIdToNodes<?> getChild(final PathArgument child) {
+ return null;
+ }
+
+ @Override
+ public NormalizedNode<?, ?> create(final YangInstanceIdentifier instanceId, final Optional<NormalizedNode<?, ?>> deepestChild, final Optional<Entry<QName,ModifyAction>> operation) {
+ if(deepestChild.isPresent()) {
+ Preconditions.checkState(deepestChild instanceof AnyXmlNode);
+ final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
+ Builders.anyXmlBuilder().withNodeIdentifier(getIdentifier()).withValue(((AnyXmlNode) deepestChild).getValue());
+ addModifyOpIfPresent(operation, anyXmlBuilder);
+ return anyXmlBuilder.build();
+ }
+
+ final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> builder =
+ Builders.anyXmlBuilder().withNodeIdentifier(getIdentifier());
+ addModifyOpIfPresent(operation, builder);
+ return builder.build();
+ }
+
+ }
+
+ private static Optional<DataSchemaNode> findChildSchemaNode(final DataNodeContainer parent, final QName child) {
+ DataSchemaNode potential = parent.getDataChildByName(child);
+ if (potential == null) {
+ final Iterable<ChoiceSchemaNode> choices = FluentIterable.from(parent.getChildNodes()).filter(ChoiceSchemaNode.class);
+ potential = findChoice(choices, child);
+ }
+ return Optional.fromNullable(potential);
+ }
+
+ static InstanceIdToNodes<?> fromSchemaAndQNameChecked(final DataNodeContainer schema, final QName child) {
+ final Optional<DataSchemaNode> potential = findChildSchemaNode(schema, child);
+ Preconditions.checkArgument(potential.isPresent(),
+ "Supplied QName %s is not valid according to schema %s, potential children nodes: %s", child, schema, schema.getChildNodes());
+
+ final DataSchemaNode result = potential.get();
+ // We try to look up if this node was added by augmentation
+ if ((schema instanceof DataSchemaNode) && result.isAugmenting()) {
+ return fromAugmentation(schema, (AugmentationTarget) schema, result);
+ }
+ return fromDataSchemaNode(result);
+ }
+
+ private static ChoiceSchemaNode findChoice(final Iterable<ChoiceSchemaNode> choices, final QName child) {
+ ChoiceSchemaNode foundChoice = null;
+ choiceLoop:
+ for (final ChoiceSchemaNode choice : choices) {
+ for (final ChoiceCaseNode caze : choice.getCases()) {
+ if (findChildSchemaNode(caze, child).isPresent()) {
+ foundChoice = choice;
+ break choiceLoop;
+ }
+ }
+ }
+ return foundChoice;
+ }
+
+ /**
+ * Returns a SchemaPathUtil for provided child node
+ * <p/>
+ * If supplied child is added by Augmentation this operation returns
+ * a SchemaPathUtil for augmentation,
+ * otherwise returns a SchemaPathUtil for child as
+ * call for {@link #fromDataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode)}.
+ */
+ private static InstanceIdToNodes<?> fromAugmentation(final DataNodeContainer parent,
+ final AugmentationTarget parentAug, final DataSchemaNode child) {
+ AugmentationSchema augmentation = null;
+ for (final AugmentationSchema aug : parentAug.getAvailableAugmentations()) {
+ final DataSchemaNode potential = aug.getDataChildByName(child.getQName());
+ if (potential != null) {
+ augmentation = aug;
+ break;
+ }
+
+ }
+ if (augmentation != null) {
+ return new InstanceIdToCompositeNodes.AugmentationNormalization(augmentation, parent);
+ } else {
+ return fromDataSchemaNode(child);
+ }
+ }
+
+ static InstanceIdToNodes<?> fromDataSchemaNode(final DataSchemaNode potential) {
+ if (potential instanceof ContainerSchemaNode) {
+ return new InstanceIdToCompositeNodes.ContainerTransformation((ContainerSchemaNode) potential);
+ } else if (potential instanceof ListSchemaNode) {
+ return fromListSchemaNode((ListSchemaNode) potential);
+ } else if (potential instanceof LeafSchemaNode) {
+ return new InstanceIdToSimpleNodes.LeafNormalization((LeafSchemaNode) potential);
+ } else if (potential instanceof ChoiceSchemaNode) {
+ return new InstanceIdToCompositeNodes.ChoiceNodeNormalization((ChoiceSchemaNode) potential);
+ } else if (potential instanceof LeafListSchemaNode) {
+ return fromLeafListSchemaNode((LeafListSchemaNode) potential);
+ } else if (potential instanceof AnyXmlSchemaNode) {
+ return new AnyXmlNormalization((AnyXmlSchemaNode) potential);
+ }
+ return null;
+ }
+
+ private static InstanceIdToNodes<?> fromListSchemaNode(final ListSchemaNode potential) {
+ final List<QName> keyDefinition = potential.getKeyDefinition();
+ if (keyDefinition == null || keyDefinition.isEmpty()) {
+ return new UnkeyedListMixinNormalization(potential);
+ }
+ if (potential.isUserOrdered()) {
+ return new InstanceIdToCompositeNodes.OrderedMapMixinNormalization(potential);
+ }
+ return new InstanceIdToCompositeNodes.UnorderedMapMixinNormalization(potential);
+ }
+
+ private static InstanceIdToNodes<?> fromLeafListSchemaNode(final LeafListSchemaNode potential) {
+ if (potential.isUserOrdered()) {
+ return new InstanceIdToCompositeNodes.OrderedLeafListMixinNormalization(potential);
+ }
+ return new InstanceIdToCompositeNodes.UnorderedLeafListMixinNormalization(potential);
+ }
+
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterables;
+import java.util.Map;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.ModifyAction;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+
+/**
+* Base strategy for converting an instance identifier into a normalized node structure for leaf and leaf-list types.
+*/
+abstract class InstanceIdToSimpleNodes<T extends YangInstanceIdentifier.PathArgument> extends InstanceIdToNodes<T> {
+
+ protected InstanceIdToSimpleNodes(final T identifier) {
+ super(identifier);
+ }
+
+ @Override
+ public NormalizedNode<?, ?> create(final YangInstanceIdentifier instanceId, final Optional<NormalizedNode<?, ?>> deepestChild, final Optional<Map.Entry<QName,ModifyAction>> operation) {
+ checkNotNull(instanceId);
+ final YangInstanceIdentifier.PathArgument pathArgument = Iterables.get(instanceId.getPathArguments(), 0);
+ final NormalizedNodeAttrBuilder<? extends YangInstanceIdentifier.PathArgument, Object, ? extends NormalizedNode<? extends YangInstanceIdentifier.PathArgument, Object>> builder = getBuilder(pathArgument);
+
+ if(deepestChild.isPresent()) {
+ builder.withValue(deepestChild.get().getValue());
+ }
+
+ addModifyOpIfPresent(operation, builder);
+ return builder.build();
+ }
+
+ protected abstract NormalizedNodeAttrBuilder<? extends YangInstanceIdentifier.PathArgument, Object, ? extends NormalizedNode<? extends YangInstanceIdentifier.PathArgument, Object>> getBuilder(YangInstanceIdentifier.PathArgument node);
+
+ @Override
+ public InstanceIdToNodes<?> getChild(final YangInstanceIdentifier.PathArgument child) {
+ return null;
+ }
+
+ static final class LeafNormalization extends InstanceIdToSimpleNodes<YangInstanceIdentifier.NodeIdentifier> {
+
+ protected LeafNormalization(final LeafSchemaNode potential) {
+ super(new YangInstanceIdentifier.NodeIdentifier(potential.getQName()));
+ }
+
+ @Override
+ protected NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> getBuilder(final YangInstanceIdentifier.PathArgument node) {
+ return Builders.leafBuilder().withNodeIdentifier(getIdentifier());
+ }
+ }
+
+ static final class LeafListEntryNormalization extends InstanceIdToSimpleNodes<YangInstanceIdentifier.NodeWithValue> {
+
+ public LeafListEntryNormalization(final LeafListSchemaNode potential) {
+ super(new YangInstanceIdentifier.NodeWithValue(potential.getQName(), null));
+ }
+
+ @Override
+ protected NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeWithValue, Object, LeafSetEntryNode<Object>> getBuilder(final YangInstanceIdentifier.PathArgument node) {
+ Preconditions.checkArgument(node instanceof YangInstanceIdentifier.NodeWithValue);
+ return Builders.leafSetEntryBuilder().withNodeIdentifier((YangInstanceIdentifier.NodeWithValue) node).withValue(((YangInstanceIdentifier.NodeWithValue) node).getValue());
+ }
+
+ }
+}
import java.util.Map;
import java.util.Set;
import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
return dataChildByName == null ? findSchemaForChild(schema, qname, schema.getChildNodes()) : dataChildByName;
}
+ @Nullable
+ public static DataSchemaNode findSchemaForChild(final DataNodeContainer schema, final QName qname, final boolean strictMode) {
+ if (strictMode) {
+ return findSchemaForChild(schema, qname);
+ }
+
+ Optional<DataSchemaNode> childSchemaOptional = findFirstSchema(qname, schema.getChildNodes());
+ if (!childSchemaOptional.isPresent()) {
+ return null;
+ }
+ return childSchemaOptional.get();
+ }
+
public static DataSchemaNode findSchemaForChild(final DataNodeContainer schema, final QName qname, final Iterable<DataSchemaNode> childNodes) {
Optional<DataSchemaNode> childSchema = findFirstSchema(qname, childNodes);
Preconditions.checkState(childSchema.isPresent(),
@Override
protected final DataSchemaNode getSchemaForChild(final AugmentationSchema schema, final QName childQName) {
- return SchemaUtils.findSchemaForChild(schema, childQName);
+ return SchemaUtils.findSchemaForChild(schema, childQName, strictParsing());
}
@Override
// process Child nodes
for (QName childPartialQName : mappedChildElements.keySet()) {
DataSchemaNode childSchema = getSchemaForChild(schema, childPartialQName);
+ //with strict parsing an exception would be already thrown, with nonstrict we want to ignore this node
+ if (childSchema == null) {
+ continue;
+ }
List<E> childrenForQName = mappedChildElements.get(childPartialQName);
// Augment
return Collections.emptyMap();
}
+ protected boolean strictParsing() {
+ return true;
+ }
+
private boolean isMarkedAs(final Map<QName, ?> mappedAugmentChildNodes, final QName qName) {
return mappedAugmentChildNodes.containsKey(qName);
}
@Override
protected final DataSchemaNode getSchemaForChild(final ContainerSchemaNode schema, final QName childQName) {
- return SchemaUtils.findSchemaForChild(schema, childQName);
+ return SchemaUtils.findSchemaForChild(schema, childQName, strictParsing());
}
@Override
@Override
protected final DataSchemaNode getSchemaForChild(final ListSchemaNode schema, final QName childQName) {
- return SchemaUtils.findSchemaForChild(schema, childQName);
+ return SchemaUtils.findSchemaForChild(schema, childQName, strictParsing());
}
@Override
final class AugmentationNodeDomParser extends AugmentationNodeBaseParser<Element> {
private final NodeParserDispatcher<Element> dispatcher;
+ private final boolean strictParsing;
AugmentationNodeDomParser(final NodeParserDispatcher<Element> dispatcher) {
this.dispatcher = Preconditions.checkNotNull(dispatcher);
+ this.strictParsing = super.strictParsing();
+ }
+
+ AugmentationNodeDomParser(final NodeParserDispatcher<Element> dispatcher, final boolean strictParsing) {
+ this.dispatcher = Preconditions.checkNotNull(dispatcher);
+ this.strictParsing = strictParsing;
}
@Override
return dispatcher;
}
+ @Override
+ protected boolean strictParsing() {
+ return strictParsing;
+ }
}
final class ContainerNodeDomParser extends ContainerNodeBaseParser<Element> {
private final NodeParserDispatcher<Element> dispatcher;
+ private final boolean strictParsing;
ContainerNodeDomParser(final NodeParserDispatcher<Element> dispatcher) {
this.dispatcher = Preconditions.checkNotNull(dispatcher);
+ this.strictParsing = super.strictParsing();
+ }
+
+ ContainerNodeDomParser(final NodeParserDispatcher<Element> dispatcher, final boolean strictParsing) {
+ this.dispatcher = Preconditions.checkNotNull(dispatcher);
+ this.strictParsing = strictParsing;
}
@Override
protected LinkedListMultimap<QName, Element> mapChildElements(Iterable<Element> elements) {
return DomUtils.mapChildElementsForSingletonNode(elements.iterator().next());
}
+
+ @Override
+ protected boolean strictParsing() {
+ return this.strictParsing;
+ }
}
private final OrderedListNodeDomParser orderedListNodeParser;
private final AnyXmlDomParser anyXmlNodeParser;
- private DomToNormalizedNodeParserFactory(final XmlCodecProvider codecProvider, final SchemaContext schema) {
+ private DomToNormalizedNodeParserFactory(final XmlCodecProvider codecProvider, final SchemaContext schema, final boolean strictParsing) {
leafNodeParser = new LeafNodeDomParser(codecProvider, schema);
leafSetEntryNodeParser = new LeafSetEntryNodeDomParser(codecProvider, schema);
leafSetNodeParser = new LeafSetNodeDomParser(leafSetEntryNodeParser);
};
- containerNodeParser = new ContainerNodeDomParser(dispatcher);
- mapEntryNodeParser = new MapEntryNodeDomParser(dispatcher);
+ containerNodeParser = new ContainerNodeDomParser(dispatcher, strictParsing);
+ mapEntryNodeParser = new MapEntryNodeDomParser(dispatcher, strictParsing);
mapNodeParser = new MapNodeDomParser(mapEntryNodeParser);
orderedListNodeParser = new OrderedListNodeDomParser(mapEntryNodeParser);
unkeyedListEntryNodeParser = new UnkeyedListEntryNodeDomParser(dispatcher);
unkeyedListNodeParser = new UnkeyedListNodeDomParser(unkeyedListEntryNodeParser);
choiceNodeParser = new ChoiceNodeDomParser(dispatcher);
- augmentationNodeParser = new AugmentationNodeDomParser(dispatcher);
+ augmentationNodeParser = new AugmentationNodeDomParser(dispatcher, strictParsing);
}
@Deprecated
augmentationNodeParser = new AugmentationNodeDomParser(dispatcher);
}
+ public static DomToNormalizedNodeParserFactory getInstance(final XmlCodecProvider codecProvider, final SchemaContext schema, final boolean strictParsing) {
+ return new DomToNormalizedNodeParserFactory(codecProvider, schema, strictParsing);
+ }
+
public static DomToNormalizedNodeParserFactory getInstance(final XmlCodecProvider codecProvider, final SchemaContext schema) {
- return new DomToNormalizedNodeParserFactory(codecProvider, schema);
+ return new DomToNormalizedNodeParserFactory(codecProvider, schema, true);
}
@Deprecated
final class MapEntryNodeDomParser extends ListEntryNodeDomParser<MapEntryNode> {
+ private final boolean strictParsing;
+
MapEntryNodeDomParser(final NodeParserDispatcher<Element> dispatcher) {
super(dispatcher);
+ this.strictParsing = super.strictParsing();
+ }
+
+ MapEntryNodeDomParser(final NodeParserDispatcher<Element> dispatcher, final boolean strictParsing) {
+ super(dispatcher);
+ this.strictParsing = strictParsing;
}
@Override
ListSchemaNode schema) {
return Builders.mapEntryBuilder(schema);
}
+
+ @Override
+ protected boolean strictParsing() {
+ return strictParsing;
+ }
}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html.
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema;
+
+import static org.junit.Assert.assertEquals;
+
+import com.google.common.base.Function;
+import com.google.common.collect.Collections2;
+import com.google.common.io.ByteSource;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collections;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
+import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
+
+public class InstanceIdToNodesTest {
+
+ private static final String NS = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:normalization:test";
+ private static final String REVISION = "2014-03-13";
+ private static final QName ID = QName.create(NS, REVISION, "id");
+ private SchemaContext ctx;
+
+ private final YangInstanceIdentifier.NodeIdentifier rootContainer = new YangInstanceIdentifier.NodeIdentifier(QName.create(NS, REVISION, "test"));
+ private final YangInstanceIdentifier.NodeIdentifier outerContainer = new YangInstanceIdentifier.NodeIdentifier(QName.create(NS, REVISION, "outer-container"));
+ private final YangInstanceIdentifier.NodeIdentifier augmentedLeaf = new YangInstanceIdentifier.NodeIdentifier(QName.create(NS, REVISION, "augmented-leaf"));
+ private final YangInstanceIdentifier.AugmentationIdentifier augmentation = new YangInstanceIdentifier.AugmentationIdentifier(Collections.singleton(augmentedLeaf.getNodeType()));
+
+ private final YangInstanceIdentifier.NodeIdentifier outerList = new YangInstanceIdentifier.NodeIdentifier(QName.create(NS, REVISION, "outer-list"));
+ private final YangInstanceIdentifier.NodeIdentifierWithPredicates outerListWithKey = new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(NS, REVISION, "outer-list"), ID, 1);
+ private final YangInstanceIdentifier.NodeIdentifier choice = new YangInstanceIdentifier.NodeIdentifier(QName.create(NS, REVISION, "outer-choice"));
+ private final YangInstanceIdentifier.NodeIdentifier leafFromCase = new YangInstanceIdentifier.NodeIdentifier(QName.create(NS, REVISION, "one"));
+
+ private final YangInstanceIdentifier.NodeIdentifier leafList = new YangInstanceIdentifier.NodeIdentifier(QName.create(NS, REVISION, "ordered-leaf-list"));
+ private final YangInstanceIdentifier.NodeWithValue leafListWithValue = new YangInstanceIdentifier.NodeWithValue(leafList.getNodeType(), "abcd");
+
+ static SchemaContext createTestContext() throws IOException, YangSyntaxErrorException {
+ final YangParserImpl parser = new YangParserImpl();
+ return parser.parseSources(Collections2.transform(Collections.singletonList("/filter-test.yang"), new Function<String, ByteSource>() {
+ @Override
+ public ByteSource apply(final String input) {
+ return new ByteSource() {
+ @Override
+ public InputStream openStream() throws IOException {
+ return InstanceIdToNodesTest.class.getResourceAsStream(input);
+ }
+ };
+ }
+ }));
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ ctx = createTestContext();
+
+ }
+
+ @Test
+ public void testInAugment() throws Exception {
+ final ContainerNode expectedFilter = Builders.containerBuilder().withNodeIdentifier(rootContainer).withChild(
+ Builders.containerBuilder().withNodeIdentifier(outerContainer).withChild(
+ Builders.augmentationBuilder().withNodeIdentifier(augmentation).withChild(
+ Builders.leafBuilder().withNodeIdentifier(augmentedLeaf).build()
+ ).build()
+ ).build()
+ ).build();
+
+ final NormalizedNode<?, ?> filter = ImmutableNodes.fromInstanceId(ctx, YangInstanceIdentifier.create(rootContainer, outerContainer, augmentation, augmentedLeaf));
+ assertEquals(expectedFilter, filter);
+ }
+
+ @Test
+ public void testInAugmentLeafOverride() throws Exception {
+ final LeafNode<Object> lastLeaf = Builders.leafBuilder().withNodeIdentifier(augmentedLeaf).withValue("randomValue").build();
+
+ final ContainerNode expectedFilter = Builders.containerBuilder().withNodeIdentifier(rootContainer).withChild(
+ Builders.containerBuilder().withNodeIdentifier(outerContainer).withChild(
+ Builders.augmentationBuilder().withNodeIdentifier(augmentation).withChild(
+ lastLeaf
+ ).build()
+ ).build()
+ ).build();
+
+ final NormalizedNode<?, ?> filter = ImmutableNodes.fromInstanceId(ctx, YangInstanceIdentifier.create(rootContainer, outerContainer, augmentation, augmentedLeaf), lastLeaf);
+ assertEquals(expectedFilter, filter);
+ }
+
+ @Test
+ public void testListChoice() throws Exception {
+ final ContainerNode expectedFilter = Builders.containerBuilder().withNodeIdentifier(rootContainer).withChild(
+ Builders.mapBuilder().withNodeIdentifier(outerList).withChild(
+ Builders.mapEntryBuilder().withNodeIdentifier(outerListWithKey).withChild(
+ Builders.leafBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ID)).withValue(1).build()
+ ).withChild(
+ Builders.choiceBuilder().withNodeIdentifier(choice).withChild(
+ Builders.leafBuilder().withNodeIdentifier(leafFromCase).build()
+ ).build()
+ ).build()
+ ).build()
+ ).build();
+
+ final NormalizedNode<?, ?> filter = ImmutableNodes.fromInstanceId(ctx, YangInstanceIdentifier.create(rootContainer, outerList, outerListWithKey, choice, leafFromCase));
+ assertEquals(expectedFilter, filter);
+ }
+
+ @Test
+ public void testTopContainerLastChildOverride() throws Exception {
+ final ContainerNode expectedStructure = Builders.containerBuilder().withNodeIdentifier(rootContainer).withChild(
+ Builders.mapBuilder().withNodeIdentifier(outerList).withChild(
+ Builders.mapEntryBuilder().withNodeIdentifier(outerListWithKey).withChild(
+ Builders.leafBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ID)).withValue(1).build()
+ ).withChild(
+ Builders.choiceBuilder().withNodeIdentifier(choice).withChild(
+ Builders.leafBuilder().withNodeIdentifier(leafFromCase).build()
+ ).build()
+ ).build()
+ ).build()
+ ).build();
+
+ final NormalizedNode<?, ?> filter = ImmutableNodes.fromInstanceId(ctx, YangInstanceIdentifier.create(rootContainer), expectedStructure);
+ assertEquals(expectedStructure, filter);
+ }
+
+ @Test
+ public void testListLastChildOverride() throws Exception {
+ final MapEntryNode outerListEntry = Builders.mapEntryBuilder().withNodeIdentifier(outerListWithKey).withChild(
+ Builders.leafBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ID)).withValue(1).build()
+ ).build();
+ final MapNode lastChild = Builders.mapBuilder().withNodeIdentifier(this.outerList).withChild(
+ outerListEntry
+ ).build();
+ final ContainerNode expectedStructure = Builders.containerBuilder().withNodeIdentifier(rootContainer).withChild(
+ lastChild
+ ).build();
+
+ NormalizedNode<?, ?> filter = ImmutableNodes.fromInstanceId(ctx, YangInstanceIdentifier.create(rootContainer, outerList, outerListWithKey), outerListEntry);
+ assertEquals(expectedStructure, filter);
+ filter = ImmutableNodes.fromInstanceId(ctx, YangInstanceIdentifier.create(rootContainer, outerList, outerListWithKey));
+ assertEquals(expectedStructure, filter);
+ }
+
+ @Test
+ public void testLeafList() throws Exception {
+ final ContainerNode expectedFilter = Builders.containerBuilder().withNodeIdentifier(rootContainer).withChild(
+ Builders.orderedLeafSetBuilder().withNodeIdentifier(leafList).withChild(
+ Builders.leafSetEntryBuilder().withNodeIdentifier(leafListWithValue).withValue(leafListWithValue.getValue()).build()
+ ).build()
+ ).build();
+
+ final NormalizedNode<?, ?> filter = ImmutableNodes.fromInstanceId(ctx, YangInstanceIdentifier.create(rootContainer, leafList, leafListWithValue));
+ assertEquals(expectedFilter, filter);
+ }
+}
\ No newline at end of file
--- /dev/null
+module normalization-test {
+ yang-version 1;
+ namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:normalization:test";
+ prefix "norm-test";
+
+ revision "2014-03-13" {
+ description "Initial revision.";
+ }
+
+ grouping outer-grouping {
+ }
+
+ container test {
+ list outer-list {
+ key id;
+ leaf id {
+ type uint16;
+ }
+ choice outer-choice {
+ case one {
+ leaf one {
+ type string;
+ }
+ }
+ case two-three {
+ leaf two {
+ type string;
+ }
+ leaf three {
+ type string;
+ }
+ }
+ }
+ list inner-list {
+ key name;
+ ordered-by user;
+
+ leaf name {
+ type string;
+ }
+ leaf value {
+ type string;
+ }
+ }
+ }
+
+ list unkeyed-list {
+ leaf name {
+ type string;
+ }
+ }
+
+ leaf-list unordered-leaf-list {
+ type string;
+ }
+
+ leaf-list ordered-leaf-list {
+ ordered-by user;
+ type string;
+ }
+
+ container outer-container {
+ }
+
+ anyxml any-xml-data;
+ }
+
+ augment /norm-test:test/norm-test:outer-container {
+
+ leaf augmented-leaf {
+ type string;
+ }
+ }
+}
\ No newline at end of file
* Represents unique path to the every node inside the module.
*/
public abstract class SchemaPath implements Immutable {
+
/**
* An absolute SchemaPath.
*/
*/
private volatile ImmutableList<QName> legacyPath;
+ protected SchemaPath(final SchemaPath parent, final QName qname) {
+ this.parent = parent;
+ this.qname = qname;
+
+ int h = parent == null ? 0 : parent.hashCode();
+ if (qname != null) {
+ h = h * 31 + qname.hashCode();
+ }
+
+ hash = h;
+ }
+
private ImmutableList<QName> getLegacyPath() {
ImmutableList<QName> ret = legacyPath;
if (ret == null) {
return getLegacyPath();
}
- protected SchemaPath(final SchemaPath parent, final QName qname) {
- this.parent = parent;
- this.qname = qname;
-
- int h = parent == null ? 0 : parent.hashCode();
- if (qname != null) {
- h = h * 31 + qname.hashCode();
- }
-
- hash = h;
- }
-
/**
* Constructs new instance of this class with the concrete path.
*
return this;
}
- SchemaPath parent = this;
+ SchemaPath parentPath = this;
for (QName qname : relative) {
- parent = parent.createInstance(parent, qname);
+ parentPath = parentPath.createInstance(parentPath, qname);
}
- return parent;
+ return parentPath;
}
/**
public SchemaPath createChild(final SchemaPath relative) {
Preconditions.checkArgument(!relative.isAbsolute(), "Child creation requires relative path");
- SchemaPath parent = this;
+ SchemaPath parentPath = this;
for (QName qname : relative.getPathFromRoot()) {
- parent = parent.createInstance(parent, qname);
+ parentPath = parentPath.createInstance(parentPath, qname);
}
- return parent;
+ return parentPath;
}
/**
*
*/
public abstract class SchemaNodeIdentifier implements Immutable {
+
/**
* An absolute schema node identifier.
*/
*/
private volatile ImmutableList<QName> legacyPath;
+ protected SchemaNodeIdentifier(final SchemaNodeIdentifier parent, final QName qname) {
+ this.parent = parent;
+ this.qname = qname;
+
+ int h = parent == null ? 0 : parent.hashCode();
+ if (qname != null) {
+ h = h * 31 + qname.hashCode();
+ }
+
+ hash = h;
+ }
+
private ImmutableList<QName> getLegacyPath() {
ImmutableList<QName> ret = legacyPath;
if (ret == null) {
return getLegacyPath();
}
- protected SchemaNodeIdentifier(final SchemaNodeIdentifier parent, final QName qname) {
- this.parent = parent;
- this.qname = qname;
-
- int h = parent == null ? 0 : parent.hashCode();
- if (qname != null) {
- h = h * 31 + qname.hashCode();
- }
-
- hash = h;
- }
-
/**
* Constructs new instance of this class with the concrete path.
*
return this;
}
- SchemaNodeIdentifier parent = this;
+ SchemaNodeIdentifier parentNode = this;
for (QName qname : relative) {
- parent = parent.createInstance(parent, qname);
+ parentNode = parentNode.createInstance(parentNode, qname);
}
- return parent;
+ return parentNode;
}
/**
public SchemaNodeIdentifier createChild(final SchemaNodeIdentifier relative) {
Preconditions.checkArgument(!relative.isAbsolute(), "Child creation requires relative path");
- SchemaNodeIdentifier parent = this;
+ SchemaNodeIdentifier parentNode = this;
for (QName qname : relative.getPathFromRoot()) {
- parent = parent.createInstance(parent, qname);
+ parentNode = parentNode.createInstance(parentNode, qname);
}
- return parent;
+ return parentNode;
}
/**
*/
@Beta
public class SchemaResolutionException extends SchemaSourceException {
+
+ private static final String MESSAGE_BLUEPRINT = "%s, resolved sources: %s, unsatisfied imports: %s";
+
private static final long serialVersionUID = 1L;
private final Multimap<SourceIdentifier, ModuleImport> unsatisfiedImports;
private final Collection<SourceIdentifier> resolvedSources;
this.resolvedSources = ImmutableList.copyOf(resolvedSources);
}
- private static final String MESSAGE_BLUEPRINT = "%s, resolved sources: %s, unsatisfied imports: %s";
private static String formatMessage(final String message, final Collection<SourceIdentifier> resolvedSources, final Multimap<SourceIdentifier, ModuleImport> unsatisfiedImports) {
return String.format(MESSAGE_BLUEPRINT, message, resolvedSources, unsatisfiedImports);
}
* A {@link SchemaSourceFilter} which accepts any schema source it is presented with.
*/
public static final SchemaSourceFilter ALWAYS_ACCEPT = new SchemaSourceFilter() {
- private final Iterable<Class<? extends SchemaSourceRepresentation>> REPRESENTATIONS =
+ private final Iterable<Class<? extends SchemaSourceRepresentation>> Representations =
Collections.<Class<? extends SchemaSourceRepresentation>>singletonList(SchemaSourceRepresentation.class);
@Override
public Iterable<Class<? extends SchemaSourceRepresentation>> supportedRepresentations() {
- return REPRESENTATIONS;
+ return Representations;
}
@Override
*/
public static final Pattern REVISION_PATTERN = Pattern.compile("\\d\\d\\d\\d-\\d\\d-\\d\\d");
-
private static final ObjectCache CACHE = ObjectCacheFactory.getObjectCache(SourceIdentifier.class);
private static final long serialVersionUID = 1L;
private final String revision;
private final String name;
+ /**
+ *
+ * Creates new YANG Schema source identifier for sources without revision.
+ * {@link SourceIdentifier#NOT_PRESENT_FORMATTED_REVISION} as default revision.
+ *
+ * @param name Name of schema
+ */
+ public SourceIdentifier(final String name) {
+ this(name, NOT_PRESENT_FORMATTED_REVISION);
+ }
+
/**
* Creates new YANG Schema source identifier.
*
return CACHE.getReference(this);
}
- /**
- *
- * Creates new YANG Schema source identifier for sources without revision.
- * {@link SourceIdentifier#NOT_PRESENT_FORMATTED_REVISION} as default revision.
- *
- * @param name Name of schema
- */
- public SourceIdentifier(final String name) {
- this(name, NOT_PRESENT_FORMATTED_REVISION);
- }
-
/**
* Returns model name
*
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
import org.antlr.v4.runtime.tree.ParseTree;
private static final Date NULL_DATE = new Date(0L);
private static final String INPUT = "input";
private static final String OUTPUT = "output";
+ private static final String CHILD_NOT_FOUND_IN_NODE_STR = "Child {} not found in node {}";
private BuilderUtils() {
}
* current line in yang model
* @return module builder if found, null otherwise
*/
- public static ModuleBuilder findModuleFromBuilders(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+ public static ModuleBuilder findModuleFromBuilders(final Map<String, NavigableMap<Date, ModuleBuilder>> modules,
final ModuleBuilder module, final String prefix, final int line) {
ModuleBuilder dependentModule;
Date dependentModuleRevision;
String dependentModuleName = dependentModuleImport.getModuleName();
dependentModuleRevision = dependentModuleImport.getRevision();
- TreeMap<Date, ModuleBuilder> moduleBuildersByRevision = modules.get(dependentModuleName);
+ NavigableMap<Date, ModuleBuilder> moduleBuildersByRevision = modules.get(dependentModuleName);
if (moduleBuildersByRevision == null) {
return null;
}
public static ModuleBuilder findModuleFromBuilders(ModuleImport imp, Iterable<ModuleBuilder> modules) {
String name = imp.getModuleName();
Date revision = imp.getRevision();
- TreeMap<Date, ModuleBuilder> map = new TreeMap<>();
+ NavigableMap<Date, ModuleBuilder> map = new TreeMap<>();
for (ModuleBuilder module : modules) {
- if (module != null) {
- if (module.getName().equals(name)) {
- map.put(module.getRevision(), module);
- }
+ if (module != null && module.getName().equals(name)) {
+ map.put(module.getRevision(), module);
}
}
if (map.isEmpty()) {
*/
public static Module findModuleFromContext(final SchemaContext context, final ModuleBuilder currentModule,
final String prefix, final int line) {
- TreeMap<Date, Module> modulesByRevision = new TreeMap<>();
+ NavigableMap<Date, Module> modulesByRevision = new TreeMap<>();
ModuleImport dependentModuleImport = currentModule.getImport(prefix);
if (dependentModuleImport == null) {
node = findUnknownNode(name, parent);
}
} else if (parent instanceof RpcDefinitionBuilder) {
- if ("input".equals(name)) {
+ if (INPUT.equals(name)) {
node = ((RpcDefinitionBuilder) parent).getInput();
- } else if ("output".equals(name)) {
+ } else if (OUTPUT.equals(name)) {
node = ((RpcDefinitionBuilder) parent).getOutput();
} else {
if (node == null) {
return castOptional(SchemaNodeBuilder.class, findCaseInChoice((ChoiceBuilder) parent, child));
} else if (parent instanceof RpcDefinitionBuilder) {
return castOptional(SchemaNodeBuilder.class, findContainerInRpc((RpcDefinitionBuilder) parent, child));
-
} else {
- LOG.trace("Child {} not found in node {}", child, parent);
+ LOG.trace(CHILD_NOT_FOUND_IN_NODE_STR, child, parent);
return Optional.absent();
}
}
final QName child) {
if (INPUT.equals(child.getLocalName())) {
if (parent.getInput() == null) {
- QName qname = QName.create(parent.getQName().getModule(), "input");
+ QName qname = QName.create(parent.getQName().getModule(), INPUT);
final ContainerSchemaNodeBuilder inputBuilder = new ContainerSchemaNodeBuilder(parent.getModuleName(),
parent.getLine(), qname, parent.getPath().createChild(qname));
inputBuilder.setParent(parent);
return Optional.of(parent.getInput());
} else if (OUTPUT.equals(child.getLocalName())) {
if (parent.getOutput() == null) {
- QName qname = QName.create(parent.getQName().getModule(), "output");
+ QName qname = QName.create(parent.getQName().getModule(), OUTPUT);
final ContainerSchemaNodeBuilder outputBuilder = new ContainerSchemaNodeBuilder(parent.getModuleName(),
parent.getLine(), qname, parent.getPath().createChild(qname));
outputBuilder.setParent(parent);
}
return Optional.of(parent.getOutput());
}
- LOG.trace("Child {} not found in node {}", child, parent);
+ LOG.trace(CHILD_NOT_FOUND_IN_NODE_STR, child, parent);
return Optional.absent();
}
return Optional.of(caze);
}
}
- LOG.trace("Child {} not found in node {}", child, parent);
+ LOG.trace(CHILD_NOT_FOUND_IN_NODE_STR, child, parent);
return Optional.absent();
}
return Optional.of(childNode);
}
}
- LOG.trace("Child {} not found in node {}", child, parent);
+ LOG.trace(CHILD_NOT_FOUND_IN_NODE_STR, child, parent);
return Optional.absent();
}
return Optional.<SchemaNodeBuilder> of(childNode);
}
}
- LOG.trace("Child {} not found in node {}", child, builder);
+ LOG.trace(CHILD_NOT_FOUND_IN_NODE_STR, child, builder);
return Optional.absent();
}
final SchemaPath schemaPath = parentPath.createChild(qname);
if (node instanceof AnyXmlSchemaNode) {
- return new AnyXmlBuilder(moduleName, line, qname, schemaPath, ((AnyXmlSchemaNode) node));
+ return new AnyXmlBuilder(moduleName, line, qname, schemaPath, (AnyXmlSchemaNode) node);
} else if (node instanceof ChoiceSchemaNode) {
- return new ChoiceBuilder(moduleName, line, qname, schemaPath, ((ChoiceSchemaNode) node));
+ return new ChoiceBuilder(moduleName, line, qname, schemaPath, (ChoiceSchemaNode) node);
} else if (node instanceof ContainerSchemaNode) {
- return new ContainerSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((ContainerSchemaNode) node));
+ return new ContainerSchemaNodeBuilder(moduleName, line, qname, schemaPath, (ContainerSchemaNode) node);
} else if (node instanceof LeafSchemaNode) {
- return new LeafSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((LeafSchemaNode) node));
+ return new LeafSchemaNodeBuilder(moduleName, line, qname, schemaPath, (LeafSchemaNode) node);
} else if (node instanceof LeafListSchemaNode) {
- return new LeafListSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((LeafListSchemaNode) node));
+ return new LeafListSchemaNodeBuilder(moduleName, line, qname, schemaPath, (LeafListSchemaNode) node);
} else if (node instanceof ListSchemaNode) {
- return new ListSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((ListSchemaNode) node));
+ return new ListSchemaNodeBuilder(moduleName, line, qname, schemaPath, (ListSchemaNode) node);
} else if (node instanceof ChoiceCaseNode) {
- return new ChoiceCaseBuilder(moduleName, line, qname, schemaPath, ((ChoiceCaseNode) node));
+ return new ChoiceCaseBuilder(moduleName, line, qname, schemaPath, (ChoiceCaseNode) node);
} else {
throw new YangParseException(moduleName, line, "Failed to copy node: Unknown type of DataSchemaNode: "
+ node);
for (TypeDefinition<?> node : nodes) {
QName qname = QName.create(parentQName, node.getQName().getLocalName());
SchemaPath schemaPath = parentPath.createChild(qname);
- result.add(new TypeDefinitionBuilderImpl(moduleName, line, qname, schemaPath, ((ExtendedType) node)));
+ result.add(new TypeDefinitionBuilderImpl(moduleName, line, qname, schemaPath, (ExtendedType) node));
}
return result;
}
}
}
- public static ModuleBuilder findModule(final QName qname, final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
- TreeMap<Date, ModuleBuilder> map = modules.get(qname.getNamespace());
+ public static ModuleBuilder findModule(final QName qname, final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
+ NavigableMap<Date, ModuleBuilder> map = modules.get(qname.getNamespace());
if (map == null) {
return null;
}
return map.get(qname.getRevision());
}
- public static Map<String, TreeMap<Date, URI>> createYangNamespaceContext(
+ public static Map<String, NavigableMap<Date, URI>> createYangNamespaceContext(
final Collection<? extends ParseTree> modules, final Optional<SchemaContext> context) {
- Map<String, TreeMap<Date, URI>> namespaceContext = new HashMap<>();
+ Map<String, NavigableMap<Date, URI>> namespaceContext = new HashMap<>();
Set<Submodule_stmtContext> submodules = new HashSet<>();
// first read ParseTree collection and separate modules and submodules
for (ParseTree module : modules) {
}
}
// update namespaceContext
- TreeMap<Date, URI> revToNs = namespaceContext.get(moduleName);
+ NavigableMap<Date, URI> revToNs = namespaceContext.get(moduleName);
if (revToNs == null) {
revToNs = new TreeMap<>();
revToNs.put(rev, namespace);
// from SchemaContext
if (context.isPresent()) {
for (Module module : context.get().getModules()) {
- TreeMap<Date, URI> revToNs = namespaceContext.get(module.getName());
+ NavigableMap<Date, URI> revToNs = namespaceContext.get(module.getName());
if (revToNs == null) {
revToNs = new TreeMap<>();
revToNs.put(module.getRevision(), module.getNamespace());
ParseTree belongsCtx = subHeaderCtx.getChild(j);
if (belongsCtx instanceof Belongs_to_stmtContext) {
final String belongsTo = ParserListenerUtils.stringFromNode(belongsCtx);
- TreeMap<Date, URI> ns = namespaceContext.get(belongsTo);
+ NavigableMap<Date, URI> ns = namespaceContext.get(belongsTo);
if (ns == null) {
throw new YangParseException(moduleName, submodule.getStart().getLine(), String.format(
"Unresolved belongs-to statement: %s", belongsTo));
}
// submodule get namespace and revision from module
- TreeMap<Date, URI> subNs = new TreeMap<>();
+ NavigableMap<Date, URI> subNs = new TreeMap<>();
subNs.put(ns.firstKey(), ns.firstEntry().getValue());
namespaceContext.put(moduleName, subNs);
}
copy.setAddedByUses(old.isAddedByUses());
copy.setConfiguration(old.isConfiguration());
for (UnknownSchemaNodeBuilder un : old.getUnknownNodes()) {
- copy.addUnknownNodeBuilder((copy(un, copy, updateQName)));
+ copy.addUnknownNodeBuilder(copy(un, copy, updateQName));
}
return copy;
copy.addAugmentation(copyAugment(augment, copy));
}
for (UnknownSchemaNodeBuilder un : old.getUnknownNodes()) {
- copy.addUnknownNodeBuilder((copy(un, copy, updateQName)));
+ copy.addUnknownNodeBuilder(copy(un, copy, updateQName));
}
return copy;
copy.addUsesNode(copyUses(oldUses, copy));
}
for (UnknownSchemaNodeBuilder un : old.getUnknownNodes()) {
- copy.addUnknownNodeBuilder((copy(un, copy, updateQName)));
+ copy.addUnknownNodeBuilder(copy(un, copy, updateQName));
}
return copy;
copy.addAugmentation(copyAugment(augment, copy));
}
for (UnknownSchemaNodeBuilder un : old.getUnknownNodes()) {
- copy.addUnknownNodeBuilder((copy(un, copy, updateQName)));
+ copy.addUnknownNodeBuilder(copy(un, copy, updateQName));
}
return copy;
copy.setAddedByUses(old.isAddedByUses());
copy.setConfiguration(old.isConfiguration());
for (UnknownSchemaNodeBuilder un : old.getUnknownNodes()) {
- copy.addUnknownNodeBuilder((copy(un, copy, updateQName)));
+ copy.addUnknownNodeBuilder(copy(un, copy, updateQName));
}
if (old.getType() == null) {
copy.setAddedByUses(old.isAddedByUses());
copy.setConfiguration(old.isConfiguration());
for (UnknownSchemaNodeBuilder un : old.getUnknownNodes()) {
- copy.addUnknownNodeBuilder((copy(un, copy, updateQName)));
+ copy.addUnknownNodeBuilder(copy(un, copy, updateQName));
}
if (old.getType() == null) {
copy.addAugmentation(copyAugment(augment, copy));
}
for (UnknownSchemaNodeBuilder un : old.getUnknownNodes()) {
- copy.addUnknownNodeBuilder((copy(un, copy, updateQName)));
+ copy.addUnknownNodeBuilder(copy(un, copy, updateQName));
}
copy.setUserOrdered(old.isUserOrdered());
copy.addUsesNode(copyUses(oldUses, copy));
}
for (UnknownSchemaNodeBuilder un : old.getUnknownNodes()) {
- copy.addUnknownNodeBuilder((copy(un, copy, updateQName)));
+ copy.addUnknownNodeBuilder(copy(un, copy, updateQName));
}
return copy;
}
for (UnknownSchemaNodeBuilder un : old.getUnknownNodes()) {
- type.addUnknownNodeBuilder((copy(un, type, updateQName)));
+ type.addUnknownNodeBuilder(copy(un, type, updateQName));
}
type.setRanges(old.getRanges());
copy.addUsesNode(copyUses(oldUses, copy));
}
for (UnknownSchemaNodeBuilder un : old.getUnknownNodes()) {
- copy.addUnknownNodeBuilder((copy(un, copy, false)));
+ copy.addUnknownNodeBuilder(copy(un, copy, false));
}
return copy;
c.setStatus(old.getStatus());
c.setAddedByUses(old.isAddedByUses());
for (UnknownSchemaNodeBuilder un : old.getUnknownNodes()) {
- c.addUnknownNodeBuilder((copy(un, c, updateQName)));
+ c.addUnknownNodeBuilder(copy(un, c, updateQName));
}
c.setExtensionBuilder(old.getExtensionBuilder());
c.setExtensionDefinition(old.getExtensionDefinition());
import java.util.Comparator;
import java.util.Date;
import java.util.Map;
+import java.util.NavigableMap;
import java.util.Set;
-import java.util.TreeMap;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
public final class GroupingUtils {
private static final Logger LOG = LoggerFactory.getLogger(GroupingUtils.class);
- private static final Splitter COLON_SPLITTER = Splitter.on(':');
private static final Splitter SLASH_SPLITTER = Splitter.on('/');
private GroupingUtils() {
* if no grouping found
*/
public static GroupingBuilder getTargetGroupingFromModules(final UsesNodeBuilder usesBuilder,
- final Map<URI, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
+ final Map<URI, NavigableMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
final int line = usesBuilder.getLine();
SchemaPath groupingPath = usesBuilder.getTargetGroupingPath();
*/
public class ModuleBuilder extends AbstractDocumentedDataNodeContainerBuilder implements DocumentedNodeBuilder {
+ private static final String GROUPING_STR = "Grouping";
+ private static final String TYPEDEF_STR = "typedef";
private ModuleImpl instance;
private final String name;
private final String sourcePath;
public ExtensionBuilder addExtension(final QName qname, final int line, final SchemaPath path) {
checkNotSealed();
- Builder parent = getActualNode();
- if (!(parent.equals(this))) {
+ Builder parentBuilder = getActualNode();
+ if (!(parentBuilder.equals(this))) {
throw new YangParseException(name, line, "extension can be defined only in module or submodule");
}
}
}
final ExtensionBuilder builder = new ExtensionBuilderImpl(name, line, qname, path);
- builder.setParent(parent);
+ builder.setParent(parentBuilder);
addedExtensions.add(builder);
return builder;
}
checkNotSealed();
final ContainerSchemaNodeBuilder builder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
- Builder parent = getActualNode();
- builder.setParent(parent);
- addChildToParent(parent, builder, qname.getLocalName());
+ Builder parentBuilder = getActualNode();
+ builder.setParent(parentBuilder);
+ addChildToParent(parentBuilder, builder, qname.getLocalName());
return builder;
}
checkNotSealed();
final ListSchemaNodeBuilder builder = new ListSchemaNodeBuilder(name, line, qname, schemaPath);
- Builder parent = getActualNode();
- builder.setParent(parent);
- addChildToParent(parent, builder, qname.getLocalName());
+ Builder parentBuilder = getActualNode();
+ builder.setParent(parentBuilder);
+ addChildToParent(parentBuilder, builder, qname.getLocalName());
allLists.add(builder);
return builder;
checkNotSealed();
final LeafSchemaNodeBuilder builder = new LeafSchemaNodeBuilder(name, line, qname, schemaPath);
- Builder parent = getActualNode();
- builder.setParent(parent);
- addChildToParent(parent, builder, qname.getLocalName());
+ Builder parentBuilder = getActualNode();
+ builder.setParent(parentBuilder);
+ addChildToParent(parentBuilder, builder, qname.getLocalName());
return builder;
}
checkNotSealed();
final LeafListSchemaNodeBuilder builder = new LeafListSchemaNodeBuilder(name, line, qname, schemaPath);
- Builder parent = getActualNode();
- builder.setParent(parent);
- addChildToParent(parent, builder, qname.getLocalName());
+ Builder parentBuilder = getActualNode();
+ builder.setParent(parentBuilder);
+ addChildToParent(parentBuilder, builder, qname.getLocalName());
return builder;
}
checkNotSealed();
final GroupingBuilder builder = new GroupingBuilderImpl(name, line, qname, path);
- Builder parent = getActualNode();
- builder.setParent(parent);
+ Builder parentBuilder = getActualNode();
+ builder.setParent(parentBuilder);
String groupingName = qname.getLocalName();
- if (parent.equals(this)) {
+ if (parentBuilder.equals(this)) {
for (GroupingBuilder addedGrouping : getGroupingBuilders()) {
if (addedGrouping.getQName().getLocalName().equals(groupingName)) {
- raiseYangParserException("", "Grouping", groupingName, line, addedGrouping.getLine());
+ raiseYangParserException("", GROUPING_STR, groupingName, line, addedGrouping.getLine());
}
}
addGrouping(builder);
} else {
- if (parent instanceof DataNodeContainerBuilder) {
- DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
+ if (parentBuilder instanceof DataNodeContainerBuilder) {
+ DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parentBuilder;
for (GroupingBuilder addedGrouping : parentNode.getGroupingBuilders()) {
if (addedGrouping.getQName().getLocalName().equals(groupingName)) {
- raiseYangParserException("", "Grouping", groupingName, line, addedGrouping.getLine());
+ raiseYangParserException("", GROUPING_STR, groupingName, line, addedGrouping.getLine());
}
}
parentNode.addGrouping(builder);
- } else if (parent instanceof RpcDefinitionBuilder) {
- RpcDefinitionBuilder parentNode = (RpcDefinitionBuilder) parent;
+ } else if (parentBuilder instanceof RpcDefinitionBuilder) {
+ RpcDefinitionBuilder parentNode = (RpcDefinitionBuilder) parentBuilder;
for (GroupingBuilder child : parentNode.getGroupings()) {
if (child.getQName().getLocalName().equals(groupingName)) {
- raiseYangParserException("", "Grouping", groupingName, line, child.getLine());
+ raiseYangParserException("", GROUPING_STR, groupingName, line, child.getLine());
}
}
parentNode.addGrouping(builder);
final AugmentationSchemaBuilder builder = new AugmentationSchemaBuilderImpl(name, line, augmentTargetStr,
targetPath, order);
- Builder parent = getActualNode();
- builder.setParent(parent);
+ Builder parentBuilder = getActualNode();
+ builder.setParent(parentBuilder);
- if (parent.equals(this)) {
+ if (parentBuilder.equals(this)) {
// augment can be declared only under 'module' ...
if (!(augmentTargetStr.startsWith("/"))) {
throw new YangParseException(
augmentBuilders.add(builder);
} else {
// ... or 'uses' statement
- if (parent instanceof UsesNodeBuilder) {
+ if (parentBuilder instanceof UsesNodeBuilder) {
if (augmentTargetStr.startsWith("/")) {
throw new YangParseException(name, line,
"If 'augment' statement is a substatement to the 'uses' statement, it cannot contain absolute path ("
+ augmentTargetStr + ")");
}
- ((UsesNodeBuilder) parent).addAugment(builder);
+ ((UsesNodeBuilder) parentBuilder).addAugment(builder);
} else {
throw new YangParseException(name, line, "Augment can be declared only under module or uses statement.");
}
checkNotSealed();
final UsesNodeBuilder usesBuilder = new UsesNodeBuilderImpl(name, line, grouping);
- Builder parent = getActualNode();
- usesBuilder.setParent(parent);
+ Builder parentBuilder = getActualNode();
+ usesBuilder.setParent(parentBuilder);
- if (parent.equals(this)) {
+ if (parentBuilder.equals(this)) {
addUsesNode(usesBuilder);
} else {
- if (!(parent instanceof DataNodeContainerBuilder)) {
+ if (!(parentBuilder instanceof DataNodeContainerBuilder)) {
throw new YangParseException(name, line, "Unresolved parent of uses '" + grouping + "'.");
}
- ((DataNodeContainerBuilder) parent).addUsesNode(usesBuilder);
+ ((DataNodeContainerBuilder) parentBuilder).addUsesNode(usesBuilder);
}
- if (parent instanceof AugmentationSchemaBuilder) {
+ if (parentBuilder instanceof AugmentationSchemaBuilder) {
usesBuilder.setAugmenting(true);
}
public void addRefine(final RefineHolderImpl refine) {
checkNotSealed();
- final Builder parent = getActualNode();
- if (!(parent instanceof UsesNodeBuilder)) {
+ final Builder parentBuilder = getActualNode();
+ if (!(parentBuilder instanceof UsesNodeBuilder)) {
throw new YangParseException(name, refine.getLine(), "refine can be defined only in uses statement");
}
- ((UsesNodeBuilder) parent).addRefine(refine);
- refine.setParent(parent);
+ ((UsesNodeBuilder) parentBuilder).addRefine(refine);
+ refine.setParent(parentBuilder);
}
public RpcDefinitionBuilder addRpc(final int line, final QName qname, final SchemaPath path) {
checkNotSealed();
- Builder parent = getActualNode();
- if (!(parent.equals(this))) {
+ Builder parentBuilder = getActualNode();
+ if (!(parentBuilder.equals(this))) {
throw new YangParseException(name, line, "rpc can be defined only in module or submodule");
}
final RpcDefinitionBuilder rpcBuilder = new RpcDefinitionBuilder(name, line, qname, path);
- rpcBuilder.setParent(parent);
+ rpcBuilder.setParent(parentBuilder);
String rpcName = qname.getLocalName();
checkNotConflictingInDataNamespace(rpcName, line);
public ContainerSchemaNodeBuilder addRpcInput(final int line, final QName qname, final SchemaPath schemaPath) {
checkNotSealed();
- final Builder parent = getActualNode();
- if (!(parent instanceof RpcDefinitionBuilder)) {
+ final Builder parentBuilder = getActualNode();
+ if (!(parentBuilder instanceof RpcDefinitionBuilder)) {
throw new YangParseException(name, line, "input can be defined only in rpc statement");
}
- final RpcDefinitionBuilder rpc = (RpcDefinitionBuilder) parent;
+ final RpcDefinitionBuilder rpc = (RpcDefinitionBuilder) parentBuilder;
final ContainerSchemaNodeBuilder inputBuilder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
inputBuilder.setParent(rpc);
public ContainerSchemaNodeBuilder addRpcOutput(final SchemaPath schemaPath, final QName qname, final int line) {
checkNotSealed();
- final Builder parent = getActualNode();
- if (!(parent instanceof RpcDefinitionBuilder)) {
+ final Builder parentBuilder = getActualNode();
+ if (!(parentBuilder instanceof RpcDefinitionBuilder)) {
throw new YangParseException(name, line, "output can be defined only in rpc statement");
}
- final RpcDefinitionBuilder rpc = (RpcDefinitionBuilder) parent;
+ final RpcDefinitionBuilder rpc = (RpcDefinitionBuilder) parentBuilder;
final ContainerSchemaNodeBuilder outputBuilder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
outputBuilder.setParent(rpc);
public NotificationBuilder addNotification(final int line, final QName qname, final SchemaPath path) {
checkNotSealed();
- final Builder parent = getActualNode();
- if (!(parent.equals(this))) {
+ final Builder parentBuilder = getActualNode();
+ if (!(parentBuilder.equals(this))) {
throw new YangParseException(name, line, "notification can be defined only in module or submodule");
}
checkNotConflictingInDataNamespace(notificationName, line);
final NotificationBuilder builder = new NotificationBuilder(name, line, qname, path);
- builder.setParent(parent);
+ builder.setParent(parentBuilder);
addedNotifications.add(builder);
return builder;
}
public FeatureBuilder addFeature(final int line, final QName qname, final SchemaPath path) {
- Builder parent = getActualNode();
- if (!(parent.equals(this))) {
+ Builder parentBuilder = getActualNode();
+ if (!(parentBuilder.equals(this))) {
throw new YangParseException(name, line, "feature can be defined only in module or submodule");
}
final FeatureBuilder builder = new FeatureBuilder(name, line, qname, path);
- builder.setParent(parent);
+ builder.setParent(parentBuilder);
String featureName = qname.getLocalName();
for (FeatureBuilder addedFeature : addedFeatures) {
public ChoiceBuilder addChoice(final int line, final QName qname, final SchemaPath path) {
final ChoiceBuilder builder = new ChoiceBuilder(name, line, qname, path);
- Builder parent = getActualNode();
- builder.setParent(parent);
- addChildToParent(parent, builder, qname.getLocalName());
+ Builder parentBuilder = getActualNode();
+ builder.setParent(parentBuilder);
+ addChildToParent(parentBuilder, builder, qname.getLocalName());
return builder;
}
public ChoiceCaseBuilder addCase(final int line, final QName qname, final SchemaPath path) {
- Builder parent = getActualNode();
- if (parent == null || parent.equals(this)) {
+ Builder parentBuilder = getActualNode();
+ if (parentBuilder == null || parentBuilder.equals(this)) {
throw new YangParseException(name, line, "'case' parent not found");
}
final ChoiceCaseBuilder builder = new ChoiceCaseBuilder(name, line, qname, path);
- builder.setParent(parent);
+ builder.setParent(parentBuilder);
- if (parent instanceof ChoiceBuilder) {
- ((ChoiceBuilder) parent).addCase(builder);
- } else if (parent instanceof AugmentationSchemaBuilder) {
- ((AugmentationSchemaBuilder) parent).addChildNode(builder);
+ if (parentBuilder instanceof ChoiceBuilder) {
+ ((ChoiceBuilder) parentBuilder).addCase(builder);
+ } else if (parentBuilder instanceof AugmentationSchemaBuilder) {
+ ((AugmentationSchemaBuilder) parentBuilder).addChildNode(builder);
} else {
throw new YangParseException(name, line, "Unresolved parent of 'case' " + qname.getLocalName());
}
public AnyXmlBuilder addAnyXml(final int line, final QName qname, final SchemaPath schemaPath) {
final AnyXmlBuilder builder = new AnyXmlBuilder(name, line, qname, schemaPath);
- Builder parent = getActualNode();
- builder.setParent(parent);
- addChildToParent(parent, builder, qname.getLocalName());
+ Builder parentBuilder = getActualNode();
+ builder.setParent(parentBuilder);
+ addChildToParent(parentBuilder, builder, qname.getLocalName());
return builder;
}
String nodeName = typedefBuilder.getQName().getLocalName();
for (TypeDefinitionBuilder tdb : getTypeDefinitionBuilders()) {
if (tdb.getQName().getLocalName().equals(nodeName)) {
- raiseYangParserException("", "typedef", nodeName, typedefBuilder.getLine(), tdb.getLine());
+ raiseYangParserException("", TYPEDEF_STR, nodeName, typedefBuilder.getLine(), tdb.getLine());
}
}
super.addTypedef(typedefBuilder);
public TypeDefinitionBuilderImpl addTypedef(final int line, final QName qname, final SchemaPath path) {
final TypeDefinitionBuilderImpl builder = new TypeDefinitionBuilderImpl(name, line, qname, path);
- Builder parent = getActualNode();
- builder.setParent(parent);
+ Builder parentBuilder = getActualNode();
+ builder.setParent(parentBuilder);
String typedefName = qname.getLocalName();
- if (parent.equals(this)) {
+ if (parentBuilder.equals(this)) {
addTypedef(builder);
} else {
- if (parent instanceof DataNodeContainerBuilder) {
- DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
+ if (parentBuilder instanceof DataNodeContainerBuilder) {
+ DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parentBuilder;
for (TypeDefinitionBuilder child : parentNode.getTypeDefinitionBuilders()) {
if (child.getQName().getLocalName().equals(typedefName)) {
- raiseYangParserException("", "typedef", typedefName, line, child.getLine());
+ raiseYangParserException("", TYPEDEF_STR, typedefName, line, child.getLine());
}
}
parentNode.addTypedef(builder);
- } else if (parent instanceof RpcDefinitionBuilder) {
- RpcDefinitionBuilder rpcParent = (RpcDefinitionBuilder) parent;
+ } else if (parentBuilder instanceof RpcDefinitionBuilder) {
+ RpcDefinitionBuilder rpcParent = (RpcDefinitionBuilder) parentBuilder;
for (TypeDefinitionBuilder tdb : rpcParent.getTypeDefinitions()) {
if (tdb.getQName().getLocalName().equals(builder.getQName().getLocalName())) {
- raiseYangParserException("", "typedef", typedefName, line, tdb.getLine());
+ raiseYangParserException("", TYPEDEF_STR, typedefName, line, tdb.getLine());
}
}
rpcParent.addTypedef(builder);
}
public void setType(final TypeDefinition<?> type) {
- Builder parent = getActualNode();
- if (!(parent instanceof TypeAwareBuilder)) {
+ Builder parentBuilder = getActualNode();
+ if (!(parentBuilder instanceof TypeAwareBuilder)) {
throw new YangParseException("Failed to set type '" + type.getQName().getLocalName()
- + "'. Invalid parent node: " + parent);
+ + "'. Invalid parent node: " + parentBuilder);
}
- ((TypeAwareBuilder) parent).setType(type);
+ ((TypeAwareBuilder) parentBuilder).setType(type);
}
public UnionTypeBuilder addUnionType(final int line, final QNameModule module) {
- final Builder parent = getActualNode();
- if (parent == null) {
+ final Builder parentBuilder = getActualNode();
+ if (parentBuilder == null) {
throw new YangParseException(name, line, "Unresolved parent of union type");
} else {
final UnionTypeBuilder union = new UnionTypeBuilder(name, line);
- if (parent instanceof TypeAwareBuilder) {
- ((TypeAwareBuilder) parent).setTypedef(union);
+ if (parentBuilder instanceof TypeAwareBuilder) {
+ ((TypeAwareBuilder) parentBuilder).setTypedef(union);
return union;
} else {
throw new YangParseException(name, line, "Invalid parent of union type.");
public void addIdentityrefType(final int line, final SchemaPath schemaPath, final String baseString) {
final IdentityrefTypeBuilder identityref = new IdentityrefTypeBuilder(name, line, baseString, schemaPath);
- final Builder parent = getActualNode();
- if (parent == null) {
+ final Builder parentBuilder = getActualNode();
+ if (parentBuilder == null) {
throw new YangParseException(name, line, "Unresolved parent of identityref type.");
} else {
- if (parent instanceof TypeAwareBuilder) {
- final TypeAwareBuilder typeParent = (TypeAwareBuilder) parent;
+ if (parentBuilder instanceof TypeAwareBuilder) {
+ final TypeAwareBuilder typeParent = (TypeAwareBuilder) parentBuilder;
typeParent.setTypedef(identityref);
dirtyNodes.add(typeParent);
} else {
}
public DeviationBuilder addDeviation(final int line, final SchemaPath targetPath) {
- Builder parent = getActualNode();
- if (!(parent.equals(this))) {
+ Builder parentBuilder = getActualNode();
+ if (!(parentBuilder.equals(this))) {
throw new YangParseException(name, line, "deviation can be defined only in module or submodule");
}
final DeviationBuilder builder = new DeviationBuilder(name, line, targetPath);
- builder.setParent(parent);
+ builder.setParent(parentBuilder);
deviationBuilders.add(builder);
return builder;
}
public IdentitySchemaNodeBuilder addIdentity(final QName qname, final int line, final SchemaPath path) {
- Builder parent = getActualNode();
- if (!(parent.equals(this))) {
+ Builder parentBuilder = getActualNode();
+ if (!(parentBuilder.equals(this))) {
throw new YangParseException(name, line, "identity can be defined only in module or submodule");
}
String identityName = qname.getLocalName();
}
final IdentitySchemaNodeBuilder builder = new IdentitySchemaNodeBuilder(name, line, qname, path);
- builder.setParent(parent);
+ builder.setParent(parentBuilder);
addedIdentities.add(builder);
return builder;
}
}
public UnknownSchemaNodeBuilderImpl addUnknownSchemaNode(final int line, final QName qname, final SchemaPath path) {
- final Builder parent = getActualNode();
+ final Builder parentBuilder = getActualNode();
final UnknownSchemaNodeBuilderImpl builder = new UnknownSchemaNodeBuilderImpl(name, line, qname, path);
- builder.setParent(parent);
+ builder.setParent(parentBuilder);
allUnknownNodes.add(builder);
- if (parent.equals(this)) {
+ if (parentBuilder.equals(this)) {
addedUnknownNodes.add(builder);
} else {
- if (parent instanceof SchemaNodeBuilder) {
- parent.addUnknownNodeBuilder(builder);
- } else if (parent instanceof DataNodeContainerBuilder) {
- parent.addUnknownNodeBuilder(builder);
- } else if (parent instanceof RefineHolderImpl) {
- parent.addUnknownNodeBuilder(builder);
+ if (parentBuilder instanceof SchemaNodeBuilder) {
+ parentBuilder.addUnknownNodeBuilder(builder);
+ } else if (parentBuilder instanceof DataNodeContainerBuilder) {
+ parentBuilder.addUnknownNodeBuilder(builder);
+ } else if (parentBuilder instanceof RefineHolderImpl) {
+ parentBuilder.addUnknownNodeBuilder(builder);
} else {
throw new YangParseException(name, line, "Unresolved parent of unknown node '" + qname.getLocalName()
+ "'");
import java.util.Collections;
import java.util.Date;
import java.util.List;
+import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
import org.opendaylight.yangtools.concepts.Immutable;
}
private static <T extends SchemaNode> Set<T> toImmutableSortedSet(final Set<T> original) {
- TreeSet<T> sorted = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
+ NavigableSet<T> sorted = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
sorted.addAll(original);
return Collections.unmodifiableSet(sorted);
}
private final Set<TypeDefinitionBuilder> addedTypedefs = new HashSet<>();
private final Set<GroupingBuilder> addedGroupings = new HashSet<>();
+ RpcDefinitionBuilder(final String moduleName, final int line, final QName qname, final SchemaPath path) {
+ super(moduleName, line, qname);
+ this.schemaPath = Preconditions.checkNotNull(path, "Schema Path must not be null");
+ }
+
public ContainerSchemaNodeBuilder getInput() {
return inputBuilder;
}
return outputBuilder;
}
- RpcDefinitionBuilder(final String moduleName, final int line, final QName qname, final SchemaPath path) {
- super(moduleName, line, qname);
- this.schemaPath = Preconditions.checkNotNull(path, "Schema Path must not be null");
- }
-
@Override
public RpcDefinition build() {
if (instance != null) {
import java.net.URI;
import java.util.Date;
import java.util.Map;
+import java.util.NavigableMap;
import java.util.Set;
-import java.util.TreeMap;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
* current module
*/
public static void resolveType(final TypeAwareBuilder nodeToResolve,
- final Map<URI, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
+ final Map<URI, NavigableMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
QName unknownTypeQName = nodeToResolve.getTypeQName();
final ModuleBuilder dependentModuleBuilder = BuilderUtils.findModule(unknownTypeQName, modules);
if (dependentModuleBuilder == null) {
* current module
*/
public static void resolveTypeUnion(final UnionTypeBuilder union,
- final Map<URI, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
+ final Map<URI, NavigableMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
// special handling for identityref types under union
for (TypeDefinitionBuilder unionType : union.getTypedefs()) {
if (unionType instanceof IdentityrefTypeBuilder) {
* @return TypeDefinitionBuilder of node type
*/
private static TypeDefinitionBuilder findUnknownTypeDefinition(final TypeAwareBuilder nodeToResolve,
- final ModuleBuilder dependentModuleBuilder, final Map<URI, TreeMap<Date, ModuleBuilder>> modules,
+ final ModuleBuilder dependentModuleBuilder, final Map<URI, NavigableMap<Date, ModuleBuilder>> modules,
final ModuleBuilder module) {
final int line = nodeToResolve.getLine();
final QName unknownTypeQName = nodeToResolve.getTypeQName();
}
private static TypeConstraints findConstraintsFromTypeBuilder(final TypeAwareBuilder nodeToResolve,
- final TypeConstraints constraints, final Map<URI, TreeMap<Date, ModuleBuilder>> modules,
+ final TypeConstraints constraints, final Map<URI, NavigableMap<Date, ModuleBuilder>> modules,
final ModuleBuilder builder) {
// union and identityref types cannot be restricted
Iterable<String> keyList = ValidationUtil.listKeysFromId(key);
Set<String> duplicates = ValidationUtil.getDuplicates(keyList);
- if (duplicates.size() != 0) {
+ if (!duplicates.isEmpty()) {
ValidationUtil.ex(ValidationUtil.f("(In (sub)module:%s) %s:%s, %s:%s contains duplicates:%s",
rootParentName, ValidationUtil.getSimpleStatementName(parent.getClass()),
ValidationUtil.getName(parent), ValidationUtil.getSimpleStatementName(ctx.getClass()), key,
// module builders sorted by dependencies
List<ModuleBuilder> sortedBuilders = ModuleDependencySort.sort(resolved);
- Map<URI, TreeMap<Date, ModuleBuilder>> modules = resolveModulesWithImports(sortedBuilders, null);
+ Map<URI, NavigableMap<Date, ModuleBuilder>> modules = resolveModulesWithImports(sortedBuilders, null);
Collection<Module> unsorted = build(modules).values();
Set<Module> result = new LinkedHashSet<>(
ModuleDependencySort.sort(unsorted.toArray(new Module[unsorted.size()])));
}
final List<ModuleBuilder> sorted = resolveModuleBuilders(sources, context);
- final Map<URI, TreeMap<Date, ModuleBuilder>> modules = resolveModulesWithImports(sorted, context);
+ final Map<URI, NavigableMap<Date, ModuleBuilder>> modules = resolveModulesWithImports(sorted, context);
final Set<Module> unsorted = new LinkedHashSet<>(build(modules).values());
if (context != null) {
return resolveSchemaContext(result);
}
- private static Map<URI, TreeMap<Date, ModuleBuilder>> resolveModulesWithImports(final List<ModuleBuilder> sorted,
+ private static Map<URI, NavigableMap<Date, ModuleBuilder>> resolveModulesWithImports(final List<ModuleBuilder> sorted,
final SchemaContext context) {
- final Map<URI, TreeMap<Date, ModuleBuilder>> modules = orderModules(sorted);
+ final Map<URI, NavigableMap<Date, ModuleBuilder>> modules = orderModules(sorted);
for (ModuleBuilder module : sorted) {
if (module != null) {
for (ModuleImport imp : module.getImports().values()) {
if (targetModule == null) {
Module result = findModuleFromContext(context, module, prefix, 0);
targetModule = new ModuleBuilder(result);
- TreeMap<Date, ModuleBuilder> map = modules.get(targetModule.getNamespace());
+ NavigableMap<Date, ModuleBuilder> map = modules.get(targetModule.getNamespace());
if (map == null) {
map = new TreeMap<>();
map.put(targetModule.getRevision(), targetModule);
public Collection<Module> buildModules(final Collection<ModuleBuilder> builders) {
Collection<ModuleBuilder> unsorted = resolveSubmodules(builders);
List<ModuleBuilder> sorted = ModuleDependencySort.sort(unsorted);
- Map<URI, TreeMap<Date, ModuleBuilder>> modules = resolveModulesWithImports(sorted, null);
+ Map<URI, NavigableMap<Date, ModuleBuilder>> modules = resolveModulesWithImports(sorted, null);
Map<ModuleBuilder, Module> builderToModule = build(modules);
return builderToModule.values();
}
Map<ByteSource, ModuleBuilder> sourceToBuilder = resolveSources(sources, context);
// sort and check for duplicates
List<ModuleBuilder> sorted = ModuleDependencySort.sort(sourceToBuilder.values());
- Map<URI, TreeMap<Date, ModuleBuilder>> modules = resolveModulesWithImports(sorted, null);
+ Map<URI, NavigableMap<Date, ModuleBuilder>> modules = resolveModulesWithImports(sorted, null);
Map<ModuleBuilder, Module> builderToModule = build(modules);
Map<ModuleBuilder, ByteSource> builderToSource = HashBiMap.create(sourceToBuilder).inverse();
sorted = ModuleDependencySort.sort(builderToModule.keySet());
// validate yang
new YangModelBasicValidator(walker).validate(sourceToTree.values());
- Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
+ Map<String, NavigableMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
sourceToTree.values(), Optional.fromNullable(context));
YangParserListenerImpl yangModelParser;
for (Map.Entry<ByteSource, ParseTree> entry : sourceToTree.entrySet()) {
private Map<ByteSource, ModuleBuilder> resolveSubmodules(final Map<ByteSource, ModuleBuilder> builders) {
Map<ByteSource, ModuleBuilder> modules = new HashMap<>();
- Map<String, TreeMap<Date, ModuleBuilder>> submodules = new HashMap<>();
+ Map<String, NavigableMap<Date, ModuleBuilder>> submodules = new HashMap<>();
for (Map.Entry<ByteSource, ModuleBuilder> entry : builders.entrySet()) {
ModuleBuilder builder = entry.getValue();
if (builder.isSubmodule()) {
String submoduleName = builder.getName();
- TreeMap<Date, ModuleBuilder> map = submodules.get(submoduleName);
+ NavigableMap<Date, ModuleBuilder> map = submodules.get(submoduleName);
if (map == null) {
map = new TreeMap<>();
map.put(builder.getRevision(), builder);
private Collection<ModuleBuilder> resolveSubmodules(final Collection<ModuleBuilder> builders) {
Collection<ModuleBuilder> modules = new HashSet<>();
- Map<String, TreeMap<Date, ModuleBuilder>> submodules = new HashMap<>();
+ Map<String, NavigableMap<Date, ModuleBuilder>> submodules = new HashMap<>();
for (ModuleBuilder builder : builders) {
if (builder.isSubmodule()) {
String submoduleName = builder.getName();
- TreeMap<Date, ModuleBuilder> map = submodules.get(submoduleName);
+ NavigableMap<Date, ModuleBuilder> map = submodules.get(submoduleName);
if (map == null) {
map = new TreeMap<>();
map.put(builder.getRevision(), builder);
* @return collection of module builders with resolved submodules
*/
private void resolveSubmodules(final ModuleBuilder module,
- final Map<String, TreeMap<Date, ModuleBuilder>> submodules) {
+ final Map<String, NavigableMap<Date, ModuleBuilder>> submodules) {
Map<String, Date> includes = module.getIncludedModules();
for (Map.Entry<String, Date> entry : includes.entrySet()) {
NavigableMap<Date, ModuleBuilder> subs = submodules.get(entry.getKey());
}
}
- if (submodule.getIncludedModules().size() > 0) {
+ if (!submodule.getIncludedModules().isEmpty()) {
resolveSubmodules(submodule, submodules);
}
addSubmoduleToModule(submodule, module);
* topologically sorted modules
* @return modules ordered by namespace and revision
*/
- private static Map<URI, TreeMap<Date, ModuleBuilder>> orderModules(final List<ModuleBuilder> modules) {
- final Map<URI, TreeMap<Date, ModuleBuilder>> result = new LinkedHashMap<>();
+ private static Map<URI, NavigableMap<Date, ModuleBuilder>> orderModules(final List<ModuleBuilder> modules) {
+ final Map<URI, NavigableMap<Date, ModuleBuilder>> result = new LinkedHashMap<>();
for (final ModuleBuilder builder : modules) {
if (builder == null) {
continue;
rev = new Date(0);
}
- TreeMap<Date, ModuleBuilder> builderByRevision = result.get(ns);
+ NavigableMap<Date, ModuleBuilder> builderByRevision = result.get(ns);
if (builderByRevision == null) {
builderByRevision = new TreeMap<>();
builderByRevision.put(rev, builder);
// if this is submodule, add parent to filtered and pick its imports
if (main.isSubmodule()) {
- TreeMap<Date, ModuleBuilder> dependencies = new TreeMap<>();
+ NavigableMap<Date, ModuleBuilder> dependencies = new TreeMap<>();
for (ModuleBuilder mb : other) {
if (mb.getName().equals(main.getBelongsTo())) {
dependencies.put(mb.getRevision(), mb);
filterImports(builder, other, filtered);
}
} else {
- if (mi.getRevision().equals(builder.getRevision())) {
- if (!filtered.contains(builder)) {
- filtered.add(builder);
- filterImports(builder, other, filtered);
- }
+ if (!filtered.contains(builder) && mi.getRevision().equals(builder.getRevision())) {
+ filtered.add(builder);
+ filterImports(builder, other, filtered);
}
}
}
* all loaded modules
* @return modules mapped on their builders
*/
- private Map<ModuleBuilder, Module> build(final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
+ private Map<ModuleBuilder, Module> build(final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
resolveDirtyNodes(modules);
resolveAugmentsTargetPath(modules);
resolveUsesTargetGrouping(modules);
// build
final Map<ModuleBuilder, Module> result = new LinkedHashMap<>();
- for (Map.Entry<URI, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+ for (Map.Entry<URI, NavigableMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue().entrySet()) {
final ModuleBuilder moduleBuilder = childEntry.getValue();
final Module module = moduleBuilder.build();
* @param modules
* all loaded modules
*/
- private void resolveDirtyNodes(final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
- for (Map.Entry<URI, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+ private void resolveDirtyNodes(final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
+ for (Map.Entry<URI, NavigableMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue().entrySet()) {
final ModuleBuilder module = childEntry.getValue();
resolveUnknownNodes(modules, module);
* @param module
* current module
*/
- private void resolveDirtyNodes(final Map<URI, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
+ private void resolveDirtyNodes(final Map<URI, NavigableMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
final Set<TypeAwareBuilder> dirtyNodes = module.getDirtyNodes();
if (!dirtyNodes.isEmpty()) {
for (TypeAwareBuilder nodeToResolve : dirtyNodes) {
* @param modules
* all loaded modules
*/
- private void resolveAugmentsTargetPath(final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
+ private void resolveAugmentsTargetPath(final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
// collect augments from all loaded modules
final List<AugmentationSchemaBuilder> allAugments = new ArrayList<>();
- for (Map.Entry<URI, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+ for (Map.Entry<URI, NavigableMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
allAugments.addAll(inner.getValue().getAllAugments());
}
* all loaded modules topologically sorted (based on dependencies
* between each other)
*/
- private void resolveAugments(final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
+ private void resolveAugments(final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
List<ModuleBuilder> all = new ArrayList<>();
- for (Map.Entry<URI, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+ for (Map.Entry<URI, NavigableMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
all.add(inner.getValue());
}
* @return true if augment process succeed
*/
private boolean resolveUsesAugment(final AugmentationSchemaBuilder augment, final ModuleBuilder module,
- final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
+ final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
if (augment.isResolved()) {
return true;
}
* @return true if augment process succeed
*/
private boolean resolveAugment(final AugmentationSchemaBuilder augment, final ModuleBuilder module,
- final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
+ final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
if (augment.isResolved()) {
return true;
}
* @param modules
* all loaded modules
*/
- private void resolveIdentities(final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
- for (Map.Entry<URI, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+ private void resolveIdentities(final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
+ for (Map.Entry<URI, NavigableMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
ModuleBuilder module = inner.getValue();
final Set<IdentitySchemaNodeBuilder> identities = module.getAddedIdentities();
* @param modules
* all loaded modules
*/
- private void resolveUsesTargetGrouping(final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
+ private void resolveUsesTargetGrouping(final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
final List<UsesNodeBuilder> allUses = new ArrayList<>();
- for (Map.Entry<URI, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+ for (Map.Entry<URI, NavigableMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
allUses.addAll(inner.getValue().getAllUsesNodes());
}
* @param modules
* all loaded modules
*/
- private void resolveUsesForGroupings(final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
+ private void resolveUsesForGroupings(final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
final Set<GroupingBuilder> allGroupings = new HashSet<>();
- for (Map.Entry<URI, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+ for (Map.Entry<URI, NavigableMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
ModuleBuilder module = inner.getValue();
allGroupings.addAll(module.getAllGroupings());
* @param modules
* all loaded modules
*/
- private void resolveUsesForNodes(final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
- for (Map.Entry<URI, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+ private void resolveUsesForNodes(final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
+ for (Map.Entry<URI, NavigableMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
ModuleBuilder module = inner.getValue();
List<UsesNodeBuilder> usesNodes = module.getAllUsesNodes();
* @param modules
* all loaded modules
*/
- private void resolveUses(final UsesNodeBuilder usesNode, final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
+ private void resolveUses(final UsesNodeBuilder usesNode, final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
if (!usesNode.isResolved()) {
DataNodeContainerBuilder parent = usesNode.getParent();
ModuleBuilder module = BuilderUtils.getParentModule(parent);
DataSchemaNodeBuilder nextNodeAfterUses = null;
for (DataSchemaNodeBuilder childNode : childNodes) {
- if (!(childNode.isAddedByUses()) && !(childNode.isAugmenting())) {
- if (childNode.getLine() > usesLine) {
- nextNodeAfterUses = childNode;
- break;
- }
+ if (!childNode.isAddedByUses() && !childNode.isAugmenting() && childNode.getLine() > usesLine) {
+ nextNodeAfterUses = childNode;
+ break;
}
}
* @param module
* current module
*/
- private void resolveUnknownNodes(final Map<URI, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
+ private void resolveUnknownNodes(final Map<URI, NavigableMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
for (UnknownSchemaNodeBuilder usnb : module.getAllUnknownNodes()) {
QName nodeType = usnb.getNodeType();
String localName = usnb.getNodeType().getLocalName();
* @param modules
* all loaded modules
*/
- private void checkChoiceCasesForDuplicityQNames(final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
- for (Map.Entry<URI, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+ private void checkChoiceCasesForDuplicityQNames(final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
+ for (Map.Entry<URI, NavigableMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue().entrySet()) {
final ModuleBuilder moduleBuilder = childEntry.getValue();
final Module module = moduleBuilder.build();
}
private void findDuplicityNodesIn(final ChoiceSchemaNode choiceNode, final Module module, final ModuleBuilder moduleBuilder,
- final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
- final Set<QName> duplicityTestSet = new HashSet<QName>();
+ final Map<URI, NavigableMap<Date, ModuleBuilder>> modules) {
+ final Set<QName> duplicityTestSet = new HashSet<>();
for (ChoiceCaseNode choiceCaseNode : choiceNode.getCases()) {
}
private List<ChoiceSchemaNode> getChoicesFrom(final Module module) {
- final List<ChoiceSchemaNode> allChoices = new ArrayList<ChoiceSchemaNode>();
+ final List<ChoiceSchemaNode> allChoices = new ArrayList<>();
for (DataSchemaNode dataSchemaNode : module.getChildNodes()) {
findChoicesIn(dataSchemaNode, allChoices);
import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.parseYinValue;
import static org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils.stringFromNode;
-import com.google.common.base.Splitter;
-import com.google.common.base.Strings;
-import com.google.common.collect.Iterables;
import java.net.URI;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
+
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.base.Splitter;
+import com.google.common.base.Strings;
+import com.google.common.collect.Iterables;
public final class YangParserListenerImpl extends YangParserBaseListener {
private static final Logger LOG = LoggerFactory.getLogger(YangParserListenerImpl.class);
private static final Splitter COLON_SPLITTER = Splitter.on(':');
private static final String AUGMENT_STR = "augment";
- private final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
+ private static final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
+ private static final String IMPORT_STR = "import";
+ private static final String UNION_STR = "union";
+ private static final String UNKNOWN_NODE_STR = "unknown-node";
private final SchemaPathStack stack = new SchemaPathStack();
- private final Map<String, TreeMap<Date, URI>> namespaceContext;
+ private final Map<String, NavigableMap<Date, URI>> namespaceContext;
private final String sourcePath;
private QName moduleQName = QName.create(null, new Date(0L), "dummy");
private ModuleBuilder moduleBuilder;
private int augmentOrder;
private String yangModelPrefix;
- public YangParserListenerImpl(final Map<String, TreeMap<Date, URI>> namespaceContext, final String sourcePath) {
+ public YangParserListenerImpl(final Map<String, NavigableMap<Date, URI>> namespaceContext, final String sourcePath) {
this.namespaceContext = namespaceContext;
this.sourcePath = sourcePath;
}
* @param tree
* @return new instance of YangParserListenerImpl
*/
- public static YangParserListenerImpl create(final Map<String, TreeMap<Date, URI>> namespaceContext,
+ public static YangParserListenerImpl create(final Map<String, NavigableMap<Date, URI>> namespaceContext,
final String sourcePath, final ParseTreeWalker walker, final ParseTree tree) {
final YangParserListenerImpl ret = new YangParserListenerImpl(namespaceContext, sourcePath);
walker.walk(ret, tree);
return ret;
}
-
-
@Override
public void enterModule_stmt(final YangParser.Module_stmtContext ctx) {
moduleName = stringFromNode(ctx);
@Override
public void enterBelongs_to_stmt(final YangParser.Belongs_to_stmtContext ctx) {
final String belongsTo = stringFromNode(ctx);
- TreeMap<Date, URI> context = namespaceContext.get(belongsTo);
+ NavigableMap<Date, URI> context = namespaceContext.get(belongsTo);
final Map.Entry<Date, URI> entry = context.firstEntry();
// TODO
// Submodule will contain namespace and revision from module to which it
public void enterImport_stmt(final Import_stmtContext ctx) {
final int line = ctx.getStart().getLine();
final String importName = stringFromNode(ctx);
- enterLog("import", importName, line);
+ enterLog(IMPORT_STR, importName, line);
String importPrefix = null;
Date importRevision = null;
@Override
public void exitImport_stmt(final Import_stmtContext ctx) {
- exitLog("import");
+ exitLog(IMPORT_STR);
}
@Override
public void enterInclude_stmt(YangParser.Include_stmtContext ctx) {
final int line = ctx.getStart().getLine();
final String includeName = stringFromNode(ctx);
- enterLog("import", includeName, line);
+ enterLog(IMPORT_STR, includeName, line);
Date includeRevision = null;
for (int i = 0; i < ctx.getChildCount(); i++) {
moduleBuilder.addInclude(includeName, includeRevision);
}
- @Override public void exitInclude_stmt(YangParser.Include_stmtContext ctx) {
+ @Override
+ public void exitInclude_stmt(YangParser.Include_stmtContext ctx) {
exitLog("include");
}
stack.push();
final SchemaPath targetPath = parseXPathString(augmentPath, line);
- final AugmentationSchemaBuilder builder = moduleBuilder.addAugment(line, augmentPath, targetPath, augmentOrder++);
+ final AugmentationSchemaBuilder builder = moduleBuilder.addAugment(line, augmentPath, targetPath,
+ augmentOrder++);
for (int i = 0; i < ctx.getChildCount(); i++) {
ParseTree child = ctx.getChild(i);
} else {
QName qname;
switch (typeName) {
- case "union":
- qname = BaseTypes.UNION_QNAME;
- stack.addNodeToPath(qname);
+ case UNION_STR:
+ stack.addNodeToPath(BaseTypes.UNION_QNAME);
final UnionTypeBuilder unionBuilder = moduleBuilder.addUnionType(line, moduleQName.getModule());
- final Builder parent = moduleBuilder.getActualNode();
- unionBuilder.setParent(parent);
+ final Builder parentBuilder = moduleBuilder.getActualNode();
+ unionBuilder.setParent(parentBuilder);
moduleBuilder.enterNode(unionBuilder);
break;
case "identityref":
parent.setTypeQName(typeQName);
moduleBuilder.markActualNodeDirty();
} else {
- ParserListenerUtils.parseUnknownTypeWithBody(typeBody, parent, typeQName, moduleBuilder,
- moduleQName, stack.currentSchemaPath());
+ ParserListenerUtils.parseUnknownTypeWithBody(typeBody, parent, typeQName, moduleBuilder, moduleQName,
+ stack.currentSchemaPath());
}
stack.addNodeToPath(QName.create(moduleQName.getModule(), typeQName.getLocalName()));
}
}
/**
- * Method transforms string representation of yang element (i.e. leaf name, container name etc.) into QName.
- * The namespace of QName is assigned from parent module same as revision date of module. If String qname parameter
- * contains ":" the string is evaluated as prefix:name of element. In this case method will look into import map
- * and extract correct ModuleImport. If such import is not present in import map the method will throw {@link YangParseException}
- * <br>
- * If ModuleImport is present but the value of namespace in ModuleImport is <code>null</code> the method will throw {@link YangParseException}
+ * Method transforms string representation of yang element (i.e. leaf name,
+ * container name etc.) into QName. The namespace of QName is assigned from
+ * parent module same as revision date of module. If String qname parameter
+ * contains ":" the string is evaluated as prefix:name of element. In this
+ * case method will look into import map and extract correct ModuleImport.
+ * If such import is not present in import map the method will throw
+ * {@link YangParseException} <br>
+ * If ModuleImport is present but the value of namespace in ModuleImport is
+ * <code>null</code> the method will throw {@link YangParseException}
*
- * @param qnameString QName value as String
- * @param line line in Yang model document where QName occur.
+ * @param qnameString
+ * QName value as String
+ * @param line
+ * line in Yang model document where QName occur.
* @return transformed string qname parameter as QName structure.
*
* @throws YangParseException
if (imp == null) {
LOG.debug("Error in module {} at line {}: No import found with prefix {}", moduleName, line, prefix);
throw new YangParseException(moduleName, line, "Error in module " + moduleName
- + " No import found with prefix " + prefix + " not found.");
+ + " No import found with prefix " + prefix + " not found.");
}
Date revision = imp.getRevision();
- TreeMap<Date, URI> namespaces = namespaceContext.get(imp.getModuleName());
+ NavigableMap<Date, URI> namespaces = namespaceContext.get(imp.getModuleName());
if (namespaces == null) {
throw new YangParseException(moduleName, line, String.format("Imported module %s not found",
imp.getModuleName()));
revision = namespaces.lastEntry().getKey();
namespace = namespaces.lastEntry().getValue();
} else {
- // FIXME: this lookup does not look right, as we will end up with
- // a qname which does not have a namespace. At any rate we
- // should arrive at a QNameModule!
+ // FIXME: this lookup does not look right, as we will end up
+ // with
+ // a qname which does not have a namespace. At any rate we
+ // should arrive at a QNameModule!
namespace = namespaces.get(revision);
}
@Override
public void exitType_stmt(final YangParser.Type_stmtContext ctx) {
final String typeName = stringFromNode(ctx);
- if ("union".equals(typeName)) {
+ if (UNION_STR.equals(typeName)) {
moduleBuilder.exitNode();
}
exitLog("type", stack.removeNodeFromPath());
stack.push();
final SchemaPath targetPath = parseXPathString(augmentPath, line);
- final AugmentationSchemaBuilder builder = moduleBuilder.addAugment(line, augmentPath, targetPath, augmentOrder++);
+ final AugmentationSchemaBuilder builder = moduleBuilder.addAugment(line, augmentPath, targetPath,
+ augmentOrder++);
for (int i = 0; i < ctx.getChildCount(); i++) {
final ParseTree child = ctx.getChild(i);
} else if (childNode instanceof Key_stmtContext) {
final Set<String> key = createListKey((Key_stmtContext) childNode);
builder.setKeys(key);
- } else if (childNode instanceof YangParser.Identifier_stmtContext) {
- if (childNode.getChild(0).toString().equals("union")) {
- throw new YangParseException(moduleName, line, "Union statement is not allowed inside a list statement");
- }
+ } else if (childNode instanceof YangParser.Identifier_stmtContext
+ && UNION_STR.equals(childNode.getChild(0).toString())) {
+ throw new YangParseException(moduleName, line, "Union statement is not allowed inside a list statement");
}
}
}
@Override
public void exitIdentifier_stmt(final YangParser.Identifier_stmtContext ctx) {
moduleBuilder.exitNode();
- exitLog("unknown-node", stack.removeNodeFromPath());
+ exitLog(UNKNOWN_NODE_STR, stack.removeNodeFromPath());
}
- @Override public void enterUnknown_statement(final YangParser.Unknown_statementContext ctx) {
+ @Override
+ public void enterUnknown_statement(final YangParser.Unknown_statementContext ctx) {
handleUnknownNode(ctx.getStart().getLine(), ctx);
}
- @Override public void exitUnknown_statement(final YangParser.Unknown_statementContext ctx) {
+ @Override
+ public void exitUnknown_statement(final YangParser.Unknown_statementContext ctx) {
moduleBuilder.exitNode();
- exitLog("unknown-node", stack.removeNodeFromPath());
+ exitLog(UNKNOWN_NODE_STR, stack.removeNodeFromPath());
}
@Override
private void handleUnknownNode(final int line, final ParseTree ctx) {
final String nodeParameter = stringFromNode(ctx);
- enterLog("unknown-node", nodeParameter, line);
+ enterLog(UNKNOWN_NODE_STR, nodeParameter, line);
final String nodeTypeStr = ctx.getChild(0).getText();
final QName nodeType = parseQName(nodeTypeStr, line);
QName qname = null;
try {
- //FIXME: rewrite whole method to handle unknown nodes properly.
- // This should be bugfix for bug https://bugs.opendaylight.org/show_bug.cgi?id=1539
- // After this fix bug https://bugs.opendaylight.org/show_bug.cgi?id=1538 MUST be fixed since
+ // FIXME: rewrite whole method to handle unknown nodes properly.
+ // This should be bugfix for bug
+ // https://bugs.opendaylight.org/show_bug.cgi?id=1539
+ // After this fix bug
+ // https://bugs.opendaylight.org/show_bug.cgi?id=1538 MUST be fixed
+ // since
// they are dependent!!!
if (Strings.isNullOrEmpty(nodeParameter)) {
qname = nodeType;
}
} else if (child instanceof YangStatementParser.ArgumentContext) {
try {
- if (action)
+ if (action) {
writer.argumentValue(
Utils.stringFromStringContext((YangStatementParser.ArgumentContext) child), ref);
- else
+ } else {
action = true;
+ }
} catch (SourceException e) {
LOG.warn(e.getMessage(), e);
}
return stream;
}
- private final class SourceContext extends AbstractObjectRegistration<URL> //
+ private final class SourceContext extends AbstractObjectRegistration<URL>
implements Identifiable<SourceIdentifier> {
final SourceIdentifier identifier;
YangSourceContext yangSourceContext = YangSourceContext.createFrom(sourcesMap, this);
LOG.debug("Trying to create schema context from {}", sourcesMap.keySet());
- if (yangSourceContext.getMissingDependencies().size() != 0) {
+ if (!yangSourceContext.getMissingDependencies().isEmpty()) {
LOG.debug("Omitting {} because of unresolved dependencies", yangSourceContext.getMissingDependencies().keySet());
LOG.debug("Missing model sources for {}", yangSourceContext.getMissingSources());
}
this.revision = formattedRevision == null ? null : QName.parseRevision(formattedRevision);
this.moduleImports = imports;
this.submoduleIncludes = includes;
- this.dependencies = ImmutableSet.<ModuleImport> builder() //
- .addAll(moduleImports) //
- .addAll(submoduleIncludes) //
+ this.dependencies = ImmutableSet.<ModuleImport> builder()
+ .addAll(moduleImports)
+ .addAll(submoduleIncludes)
.build();
}
return builder.build();
}
- public static String getLatestRevision(final Revision_stmtsContext revision_stmts) {
- List<Revision_stmtContext> revisions = revision_stmts.getRuleContexts(Revision_stmtContext.class);
+ public static String getLatestRevision(final Revision_stmtsContext revisionStmts) {
+ List<Revision_stmtContext> revisions = revisionStmts.getRuleContexts(Revision_stmtContext.class);
String latestRevision = null;
for (Revision_stmtContext revisionStmt : revisions) {
String currentRevision = getArgumentString(revisionStmt);
return builder.build();
}
- private static Date getRevision(final Revision_date_stmtContext revision_date_stmt) {
- if (revision_date_stmt == null) {
+ private static Date getRevision(final Revision_date_stmtContext revisionDateStmt) {
+ if (revisionDateStmt == null) {
return null;
}
- String formatedDate = getArgumentString(revision_date_stmt);
+ String formatedDate = getArgumentString(revisionDateStmt);
return QName.parseRevision(formatedDate);
}
private final String belongsTo;
+ private SubmoduleDependencyInfo(final String name, final String latestRevision, final String belongsTo,
+ final ImmutableSet<ModuleImport> imports, final ImmutableSet<ModuleImport> includes) {
+ super(name, latestRevision, imports, includes);
+ this.belongsTo = belongsTo;
+ }
+
/**
* Returns name of parent module.
*
return belongsTo;
}
- private SubmoduleDependencyInfo(final String name, final String latestRevision, final String belongsTo,
- final ImmutableSet<ModuleImport> imports, final ImmutableSet<ModuleImport> includes) {
- super(name, latestRevision, imports, includes);
- this.belongsTo = belongsTo;
- }
-
@Override
public String toString() {
return "Submodule [name=" + getName() + ", revision=" + getRevision() + ", dependencies="
*/
package org.opendaylight.yangtools.yang.parser.repo;
-import com.google.common.base.Function;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.cache.Cache;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import com.google.common.util.concurrent.AsyncFunction;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.NavigableMap;
import java.util.Set;
-import java.util.TreeMap;
+
import javax.annotation.Nullable;
+
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicate;
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.AsyncFunction;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+
final class SharedSchemaContextFactory implements SchemaContextFactory {
private static final ExceptionMapper<SchemaResolutionException> MAPPER = ReflectiveExceptionMapper.create("resolve sources", SchemaResolutionException.class);
private static final Logger LOG = LoggerFactory.getLogger(SharedSchemaContextFactory.class);
final Map<SourceIdentifier, ParserRuleContext> asts =
Maps.transformValues(srcs, ASTSchemaSource.GET_AST);
- final Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
+ final Map<String, NavigableMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
asts.values(), Optional.<SchemaContext>absent());
final ParseTreeWalker walker = new ParseTreeWalker();
*
*/
@Override
- public void onLinkageDeclared(StmtContext.Mutable<A, D, E> stmt) throws InferenceException, SourceException {
+ public void onLinkageDeclared(StmtContext.Mutable<A, D, E> stmt) throws SourceException {
// NOOP for most implementations
}
*
*/
@Override
- public void onStatementDefinitionDeclared(StmtContext.Mutable<A, D, E> stmt) throws InferenceException,
- SourceException {
+ public void onStatementDefinitionDeclared(StmtContext.Mutable<A, D, E> stmt) throws SourceException {
// NOOP for most implementations
}
*
*/
@Override
- public void onFullDefinitionDeclared(StmtContext.Mutable<A, D, E> stmt) throws InferenceException, SourceException {
+ public void onFullDefinitionDeclared(StmtContext.Mutable<A, D, E> stmt) throws SourceException {
// NOOP for most implementations
}
@Nullable <K, V, N extends IdentifierNamespace<K, V>> V getFromLocalStorage(Class<N> type, K key);
- //<K, V, N extends IdentifierNamespace<K, V>> Map<K, V> getAllFromLocalStorage(Class<N> type);
-
@Nullable <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(Class<N> type, K key, V value);
}
public abstract V getFrom(NamespaceStorageNode storage, K key);
- //public abstract Map<K, V> getAllFrom(NamespaceStorageNode storage);
-
public abstract void addTo(NamespaceStorageNode storage,K key,V value);
@Override
return storage.getFromLocalStorage(getIdentifier(), key);
}
-// protected final Map<K, V> getAllFromLocalStorage(NamespaceStorageNode storage) {
-// return storage.getAllFromLocalStorage(getIdentifier());
-// }
-
protected final void addToStorage(NamespaceStorageNode storage,K key,V value) {
storage.addToLocalStorage(getIdentifier(),key,value);
}
return getFromLocalStorage(current,key);
}
-// @Override
-// public Map<K, V> getAllFrom(final NamespaceStorageNode storage) {
-// NamespaceStorageNode current = storage;
-// while(current.getStorageNodeType() != storageType) {
-// current = current.getParentNamespaceStorage();
-// }
-// return getAllFromLocalStorage(current);
-// }
-
@Override
public void addTo(NamespaceBehaviour.NamespaceStorageNode storage, K key, V value) {
NamespaceStorageNode current = storage;
* @param stmt
* Context of added statement.
*/
- void onLinkageDeclared(StmtContext.Mutable<A, D, E> stmt) throws InferenceException,
- SourceException;
+ void onLinkageDeclared(StmtContext.Mutable<A, D, E> stmt) throws SourceException;
/**
*
* Context of added statement. Argument and statement parent is
* accessible.
*/
- void onStatementDefinitionDeclared(StmtContext.Mutable<A, D, E> stmt) throws InferenceException,
- SourceException;
+ void onStatementDefinitionDeclared(StmtContext.Mutable<A, D, E> stmt) throws SourceException;
/**
*
* Context of added statement. Argument and statement parent is
* accessible.
*/
- void onFullDefinitionDeclared(StmtContext.Mutable<A, D, E> stmt) throws InferenceException,
- SourceException;
+ void onFullDefinitionDeclared(StmtContext.Mutable<A, D, E> stmt) throws SourceException;
}
\ No newline at end of file
private final ImmutableMap<QName, StatementSupport<?,?,?>> definitions;
private final ImmutableMap<Class<?>, NamespaceBehaviour<?, ?, ?>> namespaceDefinitions;
- public ImmutableMap<QName, StatementSupport<?, ?, ?>> getDefinitions() {
- return definitions;
- }
-
private StatementSupportBundle(StatementSupportBundle parent,
- ImmutableMap<QName, StatementSupport<?, ?, ?>> statements,
- ImmutableMap<Class<?>, NamespaceBehaviour<?, ?, ?>> namespaces) {
+ ImmutableMap<QName, StatementSupport<?, ?, ?>> statements,
+ ImmutableMap<Class<?>, NamespaceBehaviour<?, ?, ?>> namespaces) {
this.parent = parent;
this.definitions = statements;
this.namespaceDefinitions = namespaces;
}
+ public ImmutableMap<QName, StatementSupport<?, ?, ?>> getDefinitions() {
+ return definitions;
+ }
+
public static Builder builder() {
return new Builder(EMPTY);
}
* Safe cast, previous checkState checks equivalence of key from
* which type argument are derived
*/
- @SuppressWarnings("unchecked")
- NamespaceBehaviour<K, V, N> casted = (NamespaceBehaviour<K, V, N>) potential;
- return casted;
+ return (NamespaceBehaviour<K, V, N>) potential;
}
if (parent != null) {
return parent.getNamespaceBehaviour(namespace);
public static final StmtContext<?, ?, ?> findFirstDeclaredSubstatement(
StmtContext<?, ?, ?> stmtContext, int startIndex, Class<? extends DeclaredStatement<?>>... types) {
- if (startIndex >= types.length)
+ if (startIndex >= types.length) {
return null;
+ }
Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements = stmtContext
.declaredSubstatements();
for (StmtContext<?, ?, ?> subStmtContext : declaredSubstatements) {
if (producesDeclared(subStmtContext,types[startIndex])) {
- if (startIndex + 1 == types.length)
+ if (startIndex + 1 == types.length) {
return subStmtContext;
- else
+ } else {
return findFirstDeclaredSubstatement(subStmtContext,
++startIndex, types);
+ }
}
}
return null;
if (sublevel > 1) {
StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(
subStmtContext, declaredType, --sublevel);
- if (result != null)
+ if (result != null) {
return result;
+ }
}
}
}
} else {
StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(
subStmtContext, declaredType);
- if (result != null)
+ if (result != null) {
return result;
+ }
}
}
* Safe cast, previous checkState checks equivalence of key from
* which type argument are derived
*/
- @SuppressWarnings("unchecked")
- NamespaceBehaviourWithListeners<K, V, N> casted = (NamespaceBehaviourWithListeners<K, V, N>) potential;
- return casted;
+ return (NamespaceBehaviourWithListeners<K, V, N>) potential;
}
throw new NamespaceNotAvailableException("Namespace " + type + "is not available in phase " + currentPhase);
}
private void completePhaseActions() throws ReactorException {
Preconditions.checkState(currentPhase != null);
- ArrayList<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
+ List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
try {
boolean progressing = true;
while(progressing) {
private void tryToResolve() throws InferenceException {
if(action == null) {
- return; // Action was not yet defined
+ // Action was not yet defined
+ return;
}
if(removeSatisfied()) {
applyAction();
boolean allSatisfied = true;
while(prereq.hasNext()) {
if(prereq.next().isDone()) {
- prereq.remove(); // We are removing current prerequisite from list.
+ // We are removing current prerequisite from list.
+ prereq.remove();
} else {
allSatisfied = false;
}
public StatementContextBase<A, D, E> createCopy(QNameModule newQNameModule, StatementContextBase<?, ?, ?> newParent)
throws SourceException {
- StatementContextBase<A, D, E> copy = new RootStatementContext<A, D, E>(
- this, newQNameModule);
- return copy;
+ return new RootStatementContext<>(this, newQNameModule);
}
@Override
import java.util.EventListener;
import java.util.Iterator;
import java.util.LinkedHashMap;
+import java.util.Map;
import javax.annotation.Nonnull;
import org.opendaylight.yangtools.concepts.Identifiable;
import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
private final StatementIdentifier identifier;
private final StatementSourceReference statementDeclSource;
- private LinkedHashMap<StatementIdentifier, StatementContextBase<?, ?, ?> > substatements = new LinkedHashMap<>();
+ private Map<StatementIdentifier, StatementContextBase<?, ?, ?> > substatements = new LinkedHashMap<>();
private Collection<StatementContextBase<?, ?, ?>> declared = new ArrayList<>();
private Collection<StatementContextBase<?, ?, ?>> effective = new ArrayList<>();
import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
-import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory;
import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
}
- public void checkNamespaceAllowed(Class<? extends IdentifierNamespace<?,?>> namespace) throws NamespaceNotAvailableException {
+ public void checkNamespaceAllowed(Class<? extends IdentifierNamespace<?,?>> namespace) {
// Noop
}
@Override
public StatementContextBase<A, D, E> createCopy(QNameModule newQNameModule, StatementContextBase<?, ?, ?> newParent) throws SourceException {
- StatementContextBase<A,D,E> copy = new SubstatementContext<A,D,E>(this,newQNameModule, newParent);
- return copy;
+ return new SubstatementContext<>(this,newQNameModule, newParent);
}
@Override
import java.util.Collection;
import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
import java.util.Set;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
+import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
import org.opendaylight.yangtools.yang.parser.spi.NamespaceToModule;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
+import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
public final class AugmentUtils {
- private AugmentUtils() {
- }
-
private static final String REGEX_PATH_REL1 = "\\.\\.?\\s*/(.+)";
private static final String REGEX_PATH_REL2 = "//.*";
+ private AugmentUtils() {
+ }
+
public static Iterable<QName> parseAugmentPath(StmtContext<?, ?, ?> ctx, String path) {
if (path.matches(REGEX_PATH_REL1) || path.matches(REGEX_PATH_REL2)) {
}
public static void copyFromSourceToTarget(StatementContextBase<?, ?, ?> sourceCtx,
- StatementContextBase<?, ?, ?> targetCtx) throws SourceException {
+ StatementContextBase<?, ?, ?> targetCtx) throws SourceException {
QNameModule newQNameModule = getNewQNameModule(targetCtx, sourceCtx);
copyDeclaredStmts(sourceCtx, targetCtx, newQNameModule);
}
public static void copyDeclaredStmts(StatementContextBase<?, ?, ?> sourceCtx,
- StatementContextBase<?, ?, ?> targetCtx, QNameModule newQNameModule) throws SourceException {
+ StatementContextBase<?, ?, ?> targetCtx, QNameModule newQNameModule) throws SourceException {
Collection<? extends StatementContextBase<?, ?, ?>> declaredSubstatements = sourceCtx.declaredSubstatements();
for (StatementContextBase<?, ?, ?> originalStmtCtx : declaredSubstatements) {
if (needToCopyByAugment(originalStmtCtx)) {
}
public static void copyEffectiveStmts(StatementContextBase<?, ?, ?> sourceCtx,
- StatementContextBase<?, ?, ?> targetCtx, QNameModule newQNameModule) throws SourceException {
+ StatementContextBase<?, ?, ?> targetCtx, QNameModule newQNameModule) throws SourceException {
Collection<? extends StatementContextBase<?, ?, ?>> effectiveSubstatements = sourceCtx.effectiveSubstatements();
for (StatementContextBase<?, ?, ?> originalStmtCtx : effectiveSubstatements) {
if (needToCopyByAugment(originalStmtCtx)) {
}
public static QNameModule getNewQNameModule(StatementContextBase<?, ?, ?> targetCtx,
- StatementContextBase<?, ?, ?> sourceCtx) {
+ StatementContextBase<?, ?, ?> sourceCtx) {
Object targetStmtArgument = targetCtx.getStatementArgument();
final StatementContextBase<?, ?, ?> root = sourceCtx.getRoot();
noCopyDefSet.add(Rfc6020Mapping.USES);
StatementDefinition def = stmtContext.getPublicDefinition();
- return (!noCopyDefSet.contains(def));
+ return !noCopyDefSet.contains(def);
}
public static boolean isReusedByAugment(StmtContext<?, ?, ?> stmtContext) {
- HashSet<StatementDefinition> reusedDefSet = new HashSet<>();
+ Set<StatementDefinition> reusedDefSet = new HashSet<>();
reusedDefSet.add(Rfc6020Mapping.TYPEDEF);
StatementDefinition def = stmtContext.getPublicDefinition();
- if (reusedDefSet.contains(def))
- return true;
- else
- return false;
+
+ return reusedDefSet.contains(def);
}
public static StatementContextBase<?, ?, ?> getAugmentTargetCtx(
final Mutable<SchemaNodeIdentifier, AugmentStatement, EffectiveStatement<SchemaNodeIdentifier, AugmentStatement>> augmentNode) {
- final SchemaNodeIdentifier augmentTargetPath = augmentNode.getStatementArgument();
+ final SchemaNodeIdentifier augmentTargetNode = augmentNode.getStatementArgument();
+
+ List<StatementContextBase<?, ?, ?>> rootStatementCtxList = new LinkedList<>();
+
+ if (augmentTargetNode.isAbsolute()) {
+
+ QNameModule module;
+ if (augmentTargetNode != null) {
+ module = augmentTargetNode.getPathFromRoot().iterator().next().getModule();
+ } else {
+ throw new IllegalArgumentException(
+ "Augment argument null, something bad happened in some of previous parsing phases");
+ }
+
+ StatementContextBase<?, ?, ?> rootStatementCtx = (StatementContextBase<?, ?, ?>) augmentNode.getFromNamespace(
+ NamespaceToModule.class, module);
+ rootStatementCtxList.add(rootStatementCtx);
+
+ final Map<?, ?> subModules = rootStatementCtx.getAllFromNamespace(IncludedModuleContext.class);
+ if (subModules != null) {
+ rootStatementCtxList.addAll((Collection<? extends StatementContextBase<?, ?, ?>>) subModules.values());
+ }
- QNameModule module;
- if (augmentTargetPath != null) {
- module = augmentTargetPath.getPathFromRoot().iterator().next().getModule();
} else {
- throw new IllegalArgumentException(
- "Augment argument null, something bad happened in some of previous parsing phases");
+ StatementContextBase<?, ?, ?> parent = (StatementContextBase<?, ?, ?>) augmentNode.getParentContext();
+ if (StmtContextUtils.producesDeclared(parent, UsesStatement.class)) {
+ rootStatementCtxList.add(parent.getParentContext());
+ } else {
+ //error
+ }
}
- StatementContextBase<?, ?, ?> rootStatementCtx = (StatementContextBase<?, ?, ?>) augmentNode.getFromNamespace(
- NamespaceToModule.class, module);
+ List<QName> augmentTargetPath = new LinkedList<>();
+
+ augmentTargetPath.addAll((Collection<? extends QName>) augmentTargetNode.getPathFromRoot());
+
+ StatementContextBase<?, ?, ?> augmentTargetCtx = null;
+ for (final StatementContextBase<?, ?, ?> rootStatementCtx : rootStatementCtxList) {
+ augmentTargetCtx = Utils.findCtxOfNodeInRoot(rootStatementCtx,
+ augmentTargetPath);
+ if (augmentTargetCtx != null) break;
+ }
- final StatementContextBase<?, ?, ?> augmentTargetCtx = Utils.findCtxOfNodeInRoot(rootStatementCtx,
- augmentTargetPath);
if (augmentTargetCtx == null) {
*/
package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.CaseEffectiveStatementImpl;
+import java.util.Collection;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.PresenceEffectiveStatementImpl;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-import java.util.Collection;
+import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.CaseEffectiveStatementImpl;
public class CaseStatementImpl extends AbstractDeclaredStatement<QName> implements CaseStatement {
*/
package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.GroupingEffectiveStatementImpl;
-
-import org.opendaylight.yangtools.yang.parser.spi.GroupingNamespace;
-import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
-import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import java.util.Collection;
+
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
-import org.opendaylight.yangtools.yang.model.api.stmt.GroupingStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.DescriptionStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.GroupingStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.ReferenceStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.StatusStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.TypedefStatement;
+import org.opendaylight.yangtools.yang.parser.spi.GroupingNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractDeclaredStatement;
import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
+import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
+import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
+import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.GroupingEffectiveStatementImpl;
public class GroupingStatementImpl extends AbstractDeclaredStatement<QName>
implements GroupingStatement {
import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.WhenStatement;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
+import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
* @param targetCtx
* @throws SourceException
*/
- public static void copyFromSourceToTarget(
- StatementContextBase<?, ?, ?> sourceGrpStmtCtx,
+ public static void copyFromSourceToTarget(StatementContextBase<?, ?, ?> sourceGrpStmtCtx,
StatementContextBase<?, ?, ?> targetCtx) throws SourceException {
- QNameModule newQNameModule = getNewQNameModule(targetCtx,
- sourceGrpStmtCtx);
+ QNameModule newQNameModule = getNewQNameModule(targetCtx, sourceGrpStmtCtx);
copyDeclaredStmts(sourceGrpStmtCtx, targetCtx, newQNameModule);
copyEffectiveStmts(sourceGrpStmtCtx, targetCtx, newQNameModule);
}
- public static void copyDeclaredStmts(
- StatementContextBase<?, ?, ?> sourceGrpStmtCtx,
- StatementContextBase<?, ?, ?> targetCtx, QNameModule newQNameModule)
- throws SourceException {
+ public static void copyDeclaredStmts(StatementContextBase<?, ?, ?> sourceGrpStmtCtx,
+ StatementContextBase<?, ?, ?> targetCtx, QNameModule newQNameModule) throws SourceException {
Collection<? extends StatementContextBase<?, ?, ?>> declaredSubstatements = sourceGrpStmtCtx
.declaredSubstatements();
for (StatementContextBase<?, ?, ?> originalStmtCtx : declaredSubstatements) {
if (needToCopyByUses(originalStmtCtx)) {
- StatementContextBase<?, ?, ?> copy = originalStmtCtx
- .createCopy(newQNameModule, targetCtx);
+ StatementContextBase<?, ?, ?> copy = originalStmtCtx.createCopy(newQNameModule, targetCtx);
targetCtx.addEffectiveSubstatement(copy);
} else if (isReusedByUses(originalStmtCtx)) {
targetCtx.addEffectiveSubstatement(originalStmtCtx);
}
}
- public static void copyEffectiveStmts(
- StatementContextBase<?, ?, ?> sourceGrpStmtCtx,
- StatementContextBase<?, ?, ?> targetCtx, QNameModule newQNameModule)
- throws SourceException {
+ public static void copyEffectiveStmts(StatementContextBase<?, ?, ?> sourceGrpStmtCtx,
+ StatementContextBase<?, ?, ?> targetCtx, QNameModule newQNameModule) throws SourceException {
Collection<? extends StatementContextBase<?, ?, ?>> effectiveSubstatements = sourceGrpStmtCtx
.effectiveSubstatements();
for (StatementContextBase<?, ?, ?> originalStmtCtx : effectiveSubstatements) {
if (needToCopyByUses(originalStmtCtx)) {
- StatementContextBase<?, ?, ?> copy = originalStmtCtx
- .createCopy(newQNameModule, targetCtx);
+ StatementContextBase<?, ?, ?> copy = originalStmtCtx.createCopy(newQNameModule, targetCtx);
targetCtx.addEffectiveSubstatement(copy);
} else if (isReusedByUses(originalStmtCtx)) {
targetCtx.addEffectiveSubstatement(originalStmtCtx);
}
}
- public static QNameModule getNewQNameModule(
- StatementContextBase<?, ?, ?> targetCtx,
+ public static QNameModule getNewQNameModule(StatementContextBase<?, ?, ?> targetCtx,
StmtContext<?, ?, ?> stmtContext) {
if (needToCreateNewQName(stmtContext.getPublicDefinition())) {
Object targetStmtArgument = targetCtx.getStatementArgument();
Object sourceStmtArgument = stmtContext.getStatementArgument();
- if (targetStmtArgument instanceof QName
- && sourceStmtArgument instanceof QName) {
+ if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) {
QName targetQName = (QName) targetStmtArgument;
QNameModule targetQNameModule = targetQName.getModule();
if (targetQNameModule.equals(sourceQNameModule)) {
return null;
- }
- else {
+ } else {
return targetQNameModule;
}
} else {
}
}
- public static boolean needToCreateNewQName(
- StatementDefinition publicDefinition) {
+ public static boolean needToCreateNewQName(StatementDefinition publicDefinition) {
return true;
}
noCopyDefSet.add(Rfc6020Mapping.USES);
StatementDefinition def = stmtContext.getPublicDefinition();
- return (!noCopyDefSet.contains(def));
+ return !noCopyDefSet.contains(def);
}
public static boolean isReusedByUses(StmtContext<?, ?, ?> stmtContext) {
reusedDefSet.add(Rfc6020Mapping.TYPEDEF);
StatementDefinition def = stmtContext.getPublicDefinition();
- return (reusedDefSet.contains(def));
+ return reusedDefSet.contains(def);
}
public static void resolveUsesNode(
Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode,
- StatementContextBase<?, ?, ?> targetNodeStmtCtx)
- throws SourceException {
+ StatementContextBase<?, ?, ?> targetNodeStmtCtx) throws SourceException {
- Collection<StatementContextBase<?, ?, ?>> declaredSubstatements = usesNode
- .declaredSubstatements();
+ Collection<StatementContextBase<?, ?, ?>> declaredSubstatements = usesNode.declaredSubstatements();
for (StatementContextBase<?, ?, ?> subStmtCtx : declaredSubstatements) {
- if (StmtContextUtils.producesDeclared(subStmtCtx,
- WhenStatement.class)) {
- StatementContextBase<?, ?, ?> copy = subStmtCtx.createCopy(
- null, targetNodeStmtCtx);
+ if (StmtContextUtils.producesDeclared(subStmtCtx, WhenStatement.class)) {
+ StatementContextBase<?, ?, ?> copy = subStmtCtx.createCopy(null, targetNodeStmtCtx);
targetNodeStmtCtx.addEffectiveSubstatement(copy);
}
- if (StmtContextUtils.producesDeclared(subStmtCtx,
- RefineStatement.class)) {
+ if (StmtContextUtils.producesDeclared(subStmtCtx, RefineStatement.class)) {
// :TODO resolve and perform refine statement
}
- if (StmtContextUtils.producesDeclared(subStmtCtx,
- AugmentStatement.class)) {
+ if (StmtContextUtils.producesDeclared(subStmtCtx, AugmentStatement.class)) {
// :TODO find target node and perform augmentation
}
// :TODO resolve other uses substatements
import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.firstAttributeOf;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.ModuleEffectiveStatementImpl;
-
-import org.opendaylight.yangtools.yang.parser.spi.source.ModuleQNameToModuleName;
-import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
-import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
-import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
-import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
-import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
-import org.opendaylight.yangtools.yang.model.api.stmt.PrefixStatement;
-import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
-import com.google.common.base.Optional;
import java.net.URI;
import java.util.Date;
+
import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.NamespaceStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.PrefixStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleIdentifierImpl;
import org.opendaylight.yangtools.yang.parser.spi.ModuleNamespace;
import org.opendaylight.yangtools.yang.parser.spi.NamespaceToModule;
import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
-import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
+import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
+import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
+import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
+import org.opendaylight.yangtools.yang.parser.spi.source.ModuleQNameToModuleName;
+import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
+import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.ModuleEffectiveStatementImpl;
+
+import com.google.common.base.Optional;
public class ModuleStatementSupport extends
AbstractStatementSupport<String, ModuleStatement, EffectiveStatement<String, ModuleStatement>> {
@Override
public String parseArgumentValue(StmtContext<?, ?,?> ctx, String value) {
- return (value);
+ return value;
}
@Override
*/
package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
-import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.firstAttributeOf;
import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.findFirstDeclaredSubstatement;
+import static org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils.firstAttributeOf;
-import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
-
-import org.opendaylight.yangtools.yang.model.api.stmt.PrefixStatement;
-import org.opendaylight.yangtools.yang.parser.spi.SubmoduleNamespace;
-import com.google.common.base.Optional;
import java.net.URI;
import java.util.Date;
+
import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.PrefixStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.YangVersionStatement;
import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleIdentifierImpl;
+import org.opendaylight.yangtools.yang.parser.spi.SubmoduleNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
-import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
+import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
+import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
-import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
-import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
-import org.opendaylight.yangtools.yang.model.api.stmt.YangVersionStatement;
-import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
+
+import com.google.common.base.Optional;
public class SubmoduleStatementImpl extends
AbstractRootStatement<SubmoduleStatement> implements SubmoduleStatement {
import static org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.FULL_DECLARATION;
import java.util.Collection;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
-import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
-import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
-import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.DescriptionStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.IfFeatureStatement;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.UsesEffectiveStatementImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implements UsesStatement {
@Override
public void prerequisiteFailed(Collection<? extends Prerequisite<?>> failed) throws InferenceException {
if (failed.contains(sourceGroupingPre)) {
- throw new InferenceException("Grouping " + groupingName + " was not resovled.", usesNode.getStatementSourceReference());
+ throw new InferenceException("Grouping " + groupingName + " was not resolved.", usesNode
+ .getStatementSourceReference());
}
throw new InferenceException("Unknown error occurred.", usesNode.getStatementSourceReference());
}
public Collection<? extends RefineStatement> getRefines() {
return allDeclared(RefineStatement.class);
}
-
- @Override
- public QName argument() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String rawArgument() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Collection<? extends DeclaredStatement<?>> declaredSubstatements() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public StatementDefinition statementDefinition() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public StatementSource getStatementSource() {
- // TODO Auto-generated method stub
- return null;
- }
-
}
import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.common.YangConstants;
import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
+import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
import com.google.common.base.CharMatcher;
public final class Utils {
- private Utils() {
- }
-
private static final Logger LOG = LoggerFactory.getLogger(Utils.class);
private static final CharMatcher DOUBLE_QUOTE_MATCHER = CharMatcher.is('"');
private static final CharMatcher SINGLE_QUOTE_MATCHER = CharMatcher.is('\'');
private static final char SEPARATOR_NODENAME = '/';
- private static final String REGEX_PATH_ABS = "/[^/].+";
+ private static final String REGEX_PATH_ABS = "/[^/].*";
+
+ private Utils() {
+ }
public static List<String> splitPathToNodeNames(String path) {
return path.matches(REGEX_PATH_ABS);
}
+ public static QName trimPrefix(QName identifier) {
+ String prefixedLocalName = identifier.getLocalName();
+ String[] namesParts = prefixedLocalName.split(":");
+
+ if (namesParts.length == 2) {
+ String localName = namesParts[1];
+ return QName.create(identifier.getModule(), localName);
+ }
+
+ return identifier;
+ }
+
+ public static boolean isValidStatementDefinition(PrefixToModule prefixes, QNameToStatementDefinition stmtDef,
+ QName identifier) {
+ if (stmtDef.get(identifier) != null) {
+ return true;
+ } else {
+ String prefixedLocalName = identifier.getLocalName();
+ String[] namesParts = prefixedLocalName.split(":");
+
+ if (namesParts.length == 2) {
+ String prefix = namesParts[0];
+ String localName = namesParts[1];
+ if (prefixes != null && prefixes.get(prefix) != null
+ && stmtDef.get(new QName(YangConstants.RFC6020_YIN_NAMESPACE, localName)) != null) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
public static Iterable<QName> parseXPath(StmtContext<?, ?, ?> ctx, String path) {
validateXPath(path);
public static String stringFromStringContext(final YangStatementParser.ArgumentContext context) {
StringBuilder sb = new StringBuilder();
List<TerminalNode> strings = context.STRING();
- if (strings.size() == 0) {
+ if (strings.isEmpty()) {
strings = Arrays.asList(context.IDENTIFIER());
}
for (TerminalNode stringNode : strings) {
public static QName qNameFromArgument(StmtContext<?, ?, ?> ctx, String value) {
- String prefix = null;
+ String prefix;
QNameModule qNameModule = null;
try {
qNameModule = QNameModule.create(new URI(""), new Date(0));
}
@Nullable
- public static StatementContextBase<?, ?, ?> findCtxOfNodeInRoot(StatementContextBase<?, ?, ?> rootStmtCtx,
- final SchemaNodeIdentifier node) {
+ private static StatementContextBase<?, ?, ?> findCtxOfNodeInSubstatements(
+ StatementContextBase<?, ?, ?> rootStmtCtx, final Iterable<QName> path, boolean searchInEffective) {
StatementContextBase<?, ?, ?> parent = rootStmtCtx;
- final Iterator<QName> pathIter = node.getPathFromRoot().iterator();
+ Iterator<QName> pathIter = path.iterator();
QName targetNode = pathIter.next();
while (pathIter.hasNext()) {
- for (StatementContextBase<?, ?, ?> child : parent.declaredSubstatements()) {
+ for (StatementContextBase<?, ?, ?> child : searchInEffective ? parent.effectiveSubstatements() : parent
+ .declaredSubstatements()) {
if (targetNode.equals(child.getStatementArgument())) {
parent = child;
StatementContextBase<?, ?, ?> targetCtx = null;
- for (StatementContextBase<?, ?, ?> child : parent.declaredSubstatements()) {
+ for (StatementContextBase<?, ?, ?> child : searchInEffective ? parent.effectiveSubstatements() : parent
+ .declaredSubstatements()) {
if (targetNode.equals(child.getStatementArgument())) {
targetCtx = child;
return targetCtx;
}
+ @Nullable
+ public static StatementContextBase<?, ?, ?> findCtxOfNodeInRoot(StatementContextBase<?, ?, ?> rootStmtCtx,
+ final SchemaNodeIdentifier node) {
+
+ System.out.println(node.getPathFromRoot());
+
+ StatementContextBase<?, ?, ?> targetCtx = findCtxOfNodeInSubstatements(rootStmtCtx, node.getPathFromRoot(),
+ false);
+
+ if (targetCtx == null) {
+
+ targetCtx = findCtxOfNodeInSubstatements(rootStmtCtx, node.getPathFromRoot(), true);
+ }
+
+ return targetCtx;
+ }
+
+ @Nullable
+ public static StatementContextBase<?, ?, ?> findCtxOfNodeInRoot(StatementContextBase<?, ?, ?> rootStmtCtx,
+ final Iterable<QName> path) {
+
+ StatementContextBase<?, ?, ?> targetCtx = findCtxOfNodeInSubstatements(rootStmtCtx, path, false);
+
+ if (targetCtx == null) {
+
+ targetCtx = findCtxOfNodeInSubstatements(rootStmtCtx, path, true);
+ }
+
+ return targetCtx;
+ }
+
public static SchemaPath getSchemaPath(StmtContext<?, ?, ?> ctx) {
Iterator<Object> argumentsIterator = ctx.getArgumentsFromRoot().iterator();
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Map;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
+
+import java.util.Map;
import java.util.Set;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- HashMap<QName, DataSchemaNode> childNodes = new HashMap<QName, DataSchemaNode>();
- HashSet<GroupingDefinition> groupings = new HashSet<GroupingDefinition>();
- HashSet<UsesNode> uses = new HashSet<UsesNode>();
- HashSet<TypeDefinition<?>> typeDefinitions = new HashSet<TypeDefinition<?>>();
- HashSet<DataSchemaNode> publicChildNodes = new HashSet<DataSchemaNode>();
+ Map<QName, DataSchemaNode> mutableChildNodes = new HashMap<QName, DataSchemaNode>();
+ Set<GroupingDefinition> mutableGroupings = new HashSet<GroupingDefinition>();
+ Set<UsesNode> mutableUses = new HashSet<UsesNode>();
+ Set<TypeDefinition<?>> mutableTypeDefinitions = new HashSet<TypeDefinition<?>>();
+ Set<DataSchemaNode> mutablePublicChildNodes = new HashSet<DataSchemaNode>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof DataSchemaNode) {
DataSchemaNode dataSchemaNode = (DataSchemaNode) effectiveStatement;
- childNodes.put(dataSchemaNode.getQName(), dataSchemaNode);
- publicChildNodes.add(dataSchemaNode);
+ mutableChildNodes.put(dataSchemaNode.getQName(), dataSchemaNode);
+ mutablePublicChildNodes.add(dataSchemaNode);
}
if (effectiveStatement instanceof UsesNode) {
UsesNode usesNode = (UsesNode) effectiveStatement;
- uses.add(usesNode);
+ mutableUses.add(usesNode);
}
if (effectiveStatement instanceof TypeDefinition) {
TypeDefinition<?> typeDef = (TypeDefinition<?>) effectiveStatement;
- typeDefinitions.add(typeDef);
+ mutableTypeDefinitions.add(typeDef);
}
if (effectiveStatement instanceof GroupingDefinition) {
GroupingDefinition grp = (GroupingDefinition) effectiveStatement;
- groupings.add(grp);
+ mutableGroupings.add(grp);
}
}
- this.childNodes = ImmutableMap.copyOf(childNodes);
- this.groupings = ImmutableSet.copyOf(groupings);
- this.publicChildNodes = ImmutableSet.copyOf(publicChildNodes);
- this.typeDefinitions = ImmutableSet.copyOf(typeDefinitions);
- this.uses = ImmutableSet.copyOf(uses);
+ this.childNodes = ImmutableMap.copyOf(mutableChildNodes);
+ this.groupings = ImmutableSet.copyOf(mutableGroupings);
+ this.publicChildNodes = ImmutableSet.copyOf(mutablePublicChildNodes);
+ this.typeDefinitions = ImmutableSet.copyOf(mutableTypeDefinitions);
+ this.uses = ImmutableSet.copyOf(mutableUses);
}
@Override
DescriptionEffectiveStatementImpl descStmt = firstEffective(DescriptionEffectiveStatementImpl.class);
if (descStmt != null) {
description = descStmt.argument();
- } else
+ } else {
description = "";
+ }
ReferenceEffectiveStatementImpl refStmt = firstEffective(ReferenceEffectiveStatementImpl.class);
if (refStmt != null) {
reference = refStmt.argument();
- } else
+ } else {
reference = "";
+ }
// :TODO
status = null;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
import org.opendaylight.yangtools.yang.common.QName;
public abstract class AbstractEffectiveSchemaContext implements SchemaContext {
- protected static final Supplier<TreeSet<Module>> MODULE_SET_SUPPLIER = new Supplier<TreeSet<Module>>() {
+ protected static final Supplier<NavigableSet<Module>> MODULE_SET_SUPPLIER = new Supplier<NavigableSet<Module>>() {
@Override
- public TreeSet<Module> get() {
+ public NavigableSet<Module> get() {
return new TreeSet<>(REVISION_COMPARATOR);
}
};
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
}
@Override
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
}
public void setCopyOf(final AugmentationSchema build) {
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
- HashSet<AugmentationSchema> augmentations = new HashSet<AugmentationSchema>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
+ Set<AugmentationSchema> augmentationsInit = new HashSet<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
if (effectiveStatement instanceof AugmentationSchema) {
AugmentationSchema augmentationSchema = (AugmentationSchema) effectiveStatement;
- augmentations.add(augmentationSchema);
+ augmentationsInit.add(augmentationSchema);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
- this.augmentations = ImmutableSet.copyOf(augmentations);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
+ this.augmentations = ImmutableSet.copyOf(augmentationsInit);
}
@Override
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
- HashSet<AugmentationSchema> augmentations = new HashSet<AugmentationSchema>();
- HashSet<ChoiceCaseNode> cases = new HashSet<ChoiceCaseNode>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
+ Set<AugmentationSchema> augmentationsInit = new HashSet<>();
+ Set<ChoiceCaseNode> casesInit = new HashSet<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
if (effectiveStatement instanceof AugmentationSchema) {
AugmentationSchema augmentationSchema = (AugmentationSchema) effectiveStatement;
- augmentations.add(augmentationSchema);
+ augmentationsInit.add(augmentationSchema);
}
if (effectiveStatement instanceof ChoiceCaseNode) {
ChoiceCaseNode choiceCaseNode = (ChoiceCaseNode) effectiveStatement;
- cases.add(choiceCaseNode);
+ casesInit.add(choiceCaseNode);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
- this.augmentations = ImmutableSet.copyOf(augmentations);
- this.cases = ImmutableSet.copyOf(cases);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
+ this.augmentations = ImmutableSet.copyOf(augmentationsInit);
+ this.cases = ImmutableSet.copyOf(casesInit);
}
@Override
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
- HashSet<AugmentationSchema> augmentations = new HashSet<AugmentationSchema>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
+ Set<AugmentationSchema> augmentationsInit = new HashSet<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
if (effectiveStatement instanceof AugmentationSchema) {
AugmentationSchema augmentationSchema = (AugmentationSchema) effectiveStatement;
- augmentations.add(augmentationSchema);
+ augmentationsInit.add(augmentationSchema);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
- this.augmentations = ImmutableSet.copyOf(augmentations);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
+ this.augmentations = ImmutableSet.copyOf(augmentationsInit);
}
@Override
this.rootEffectiveStatements = ImmutableList
.copyOf(rootEffectiveStatements);
- HashSet<Module> modules = new HashSet<Module>();
+ Set<Module> modulesInit = new HashSet<>();
for (EffectiveStatement<?, ?> rootEffectiveStatement : rootEffectiveStatements) {
if (rootEffectiveStatement instanceof Module) {
Module module = (Module) rootEffectiveStatement;
- modules.add(module);
+ modulesInit.add(module);
}
}
- this.modules = ImmutableSet.copyOf(modules);
+ this.modules = ImmutableSet.copyOf(modulesInit);
final SetMultimap<URI, Module> nsMap = Multimaps.newSetMultimap(
new TreeMap<URI, Collection<Module>>(), MODULE_SET_SUPPLIER);
final SetMultimap<String, Module> nameMap = Multimaps.newSetMultimap(
new TreeMap<String, Collection<Module>>(), MODULE_SET_SUPPLIER);
- for (Module m : modules) {
+ for (Module m : modulesInit) {
nameMap.put(m.getName(), m);
nsMap.put(m.getNamespace(), m);
}
Collection<StatementContextBase<?, ?, ?>> effectiveSubstatements = ctx
.effectiveSubstatements();
- Collection<StatementContextBase<?, ?, ?>> substatements = new LinkedList<StatementContextBase<?, ?, ?>>();
- substatements.addAll(declaredSubstatements);
- substatements.addAll(effectiveSubstatements);
+ Collection<StatementContextBase<?, ?, ?>> substatementsInit = new LinkedList<>();
+ substatementsInit.addAll(declaredSubstatements);
+ substatementsInit.addAll(effectiveSubstatements);
- this.substatements = FluentIterable.from(substatements)
+ this.substatements = FluentIterable.from(substatementsInit)
.transform(StmtContextUtils.buildEffective()).toList();
}
result = Collection.class.cast(Collections2.filter(substatements,
Predicates.instanceOf(type)));
} catch (NoSuchElementException e) {
- result = Collections.EMPTY_LIST;
+ result = Collections.emptyList();
}
return result;
}
result = Collection.class.cast(Collections2.filter(substatements,
Predicates.instanceOf(type)));
} catch (NoSuchElementException e) {
- result = Collections.EMPTY_LIST;
+ result = Collections.emptyList();
}
return result;
}
if (yinElement != null) {
this.yin = yinElement.argument();
- } else
- yin = false;
+ } else {
+ this.yin = false;
+ }
}
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
}
@Override
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
}
@Override
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
- HashSet<AugmentationSchema> augmentations = new HashSet<AugmentationSchema>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
+ Set<AugmentationSchema> augmentationsInit = new HashSet<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
if (effectiveStatement instanceof AugmentationSchema) {
AugmentationSchema augmentationSchema = (AugmentationSchema) effectiveStatement;
- augmentations.add(augmentationSchema);
+ augmentationsInit.add(augmentationSchema);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
- this.augmentations = ImmutableSet.copyOf(augmentations);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
+ this.augmentations = ImmutableSet.copyOf(augmentationsInit);
}
@Override
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
}
@Override
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
}
@Override
*
*/
private void initKeyDefinition() {
- List<QName> keyDefinition = new LinkedList<QName>();
+ List<QName> keyDefinitionInit = new LinkedList<QName>();
KeyEffectiveStatementImpl key = firstEffective(KeyEffectiveStatementImpl.class);
if (key != null) {
Collection<SchemaNodeIdentifier> keyParts = key.argument();
for (SchemaNodeIdentifier keyPart : keyParts) {
- keyDefinition.add(keyPart.getLastComponent());
+ keyDefinitionInit.add(keyPart.getLastComponent());
}
}
- this.keyDefinition = ImmutableList.copyOf(keyDefinition);
+ this.keyDefinition = ImmutableList.copyOf(keyDefinitionInit);
}
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
- HashSet<AugmentationSchema> augmentations = new HashSet<AugmentationSchema>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<UnknownSchemaNode>();
+ Set<AugmentationSchema> augmentationsInit = new HashSet<AugmentationSchema>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
if (effectiveStatement instanceof AugmentationSchema) {
AugmentationSchema augmentationSchema = (AugmentationSchema) effectiveStatement;
- augmentations.add(augmentationSchema);
+ augmentationsInit.add(augmentationSchema);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
- this.augmentations = ImmutableSet.copyOf(augmentations);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
+ this.augmentations = ImmutableSet.copyOf(augmentationsInit);
}
@Override
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
- HashSet<AugmentationSchema> augmentations = new HashSet<AugmentationSchema>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
+ Set<AugmentationSchema> augmentationsInit = new HashSet<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
if (effectiveStatement instanceof AugmentationSchema) {
AugmentationSchema augmentationSchema = (AugmentationSchema) effectiveStatement;
- augmentations.add(augmentationSchema);
+ augmentationsInit.add(augmentationSchema);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
- this.augmentations = ImmutableSet.copyOf(augmentations);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
+ this.augmentations = ImmutableSet.copyOf(augmentationsInit);
// :TODO other substatement collections ...
}
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
- HashSet<AugmentationSchema> augmentations = new HashSet<AugmentationSchema>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
+ Set<AugmentationSchema> augmentationsInit = new HashSet<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
if (effectiveStatement instanceof AugmentationSchema) {
AugmentationSchema augmentationSchema = (AugmentationSchema) effectiveStatement;
- augmentations.add(augmentationSchema);
+ augmentationsInit.add(augmentationSchema);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
- this.augmentations = ImmutableSet.copyOf(augmentations);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
+ this.augmentations = ImmutableSet.copyOf(augmentationsInit);
}
@Override
private void initSubstatementCollections() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
- HashSet<AugmentationSchema> augmentations = new HashSet<AugmentationSchema>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
+ Set<AugmentationSchema> augmentationsInit = new HashSet<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
if (effectiveStatement instanceof AugmentationSchema) {
AugmentationSchema augmentationSchema = (AugmentationSchema) effectiveStatement;
- augmentations.add(augmentationSchema);
+ augmentationsInit.add(augmentationSchema);
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
- this.augmentations = ImmutableSet.copyOf(augmentations);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
+ this.augmentations = ImmutableSet.copyOf(augmentationsInit);
}
@Override
private void initSubstatements() {
Collection<? extends EffectiveStatement<?, ?>> effectiveSubstatements = effectiveSubstatements();
- LinkedList<UnknownSchemaNode> unknownNodes = new LinkedList<UnknownSchemaNode>();
- HashSet<GroupingDefinition> groupings = new HashSet<GroupingDefinition>();
- HashSet<TypeDefinition<?>> typeDefinitions = new HashSet<TypeDefinition<?>>();
+ List<UnknownSchemaNode> unknownNodesInit = new LinkedList<>();
+ Set<GroupingDefinition> groupingsInit = new HashSet<>();
+ Set<TypeDefinition<?>> typeDefinitionsInit = new HashSet<>();
for (EffectiveStatement<?, ?> effectiveStatement : effectiveSubstatements) {
if (effectiveStatement instanceof UnknownSchemaNode) {
UnknownSchemaNode unknownNode = (UnknownSchemaNode) effectiveStatement;
- unknownNodes.add(unknownNode);
+ unknownNodesInit.add(unknownNode);
}
if (effectiveStatement instanceof GroupingDefinition) {
GroupingDefinition groupingDefinition = (GroupingDefinition) effectiveStatement;
- groupings.add(groupingDefinition);
+ groupingsInit.add(groupingDefinition);
}
if (effectiveStatement instanceof TypeDefinition) {
TypeDefinition<?> typeDefinition = (TypeDefinition<?>) effectiveStatement;
- typeDefinitions.add(typeDefinition);
+ typeDefinitionsInit.add(typeDefinition);
}
if (this.input == null && effectiveStatement instanceof InputEffectiveStatementImpl) {
this.input = (InputEffectiveStatementImpl) effectiveStatement;
}
}
- this.unknownNodes = ImmutableList.copyOf(unknownNodes);
- this.groupings = ImmutableSet.copyOf(groupings);
- this.typeDefinitions = ImmutableSet.copyOf(typeDefinitions);
+ this.unknownNodes = ImmutableList.copyOf(unknownNodesInit);
+ this.groupings = ImmutableSet.copyOf(groupingsInit);
+ this.typeDefinitions = ImmutableSet.copyOf(typeDefinitionsInit);
}
@Override
/**
* Topological sort of dependent nodes in acyclic graphs.
- *
+ *
* @return Sorted {@link List} of {@link Node}s. Order: Nodes with no
* dependencies starting.
* @throws IllegalStateException
private static Set<Node> getDependentNodes(Set<Node> nodes) {
Set<Node> dependentNodes = Sets.newHashSet();
for (Node n : nodes) {
- if (n.getOutEdges().size() == 0) {
+ if (n.getOutEdges().isEmpty()) {
dependentNodes.add(n);
}
}
private final Set<Edge> inEdges;
private final Set<Edge> outEdges;
+ public NodeImpl() {
+ inEdges = Sets.newHashSet();
+ outEdges = Sets.newHashSet();
+ }
+
@Override
public Set<Edge> getInEdges() {
return inEdges;
outEdges.add(e);
to.getInEdges().add(e);
}
-
- public NodeImpl() {
- inEdges = Sets.newHashSet();
- outEdges = Sets.newHashSet();
- }
}
/**
private final Node from;
private final Node to;
+ public EdgeImpl(Node from, Node to) {
+ this.from = from;
+ this.to = to;
+ }
+
@Override
public Node getFrom() {
return from;
return to;
}
- public EdgeImpl(Node from, Node to) {
- this.from = from;
- this.to = to;
-
- }
-
@Override
public int hashCode() {
final int prime = 31;
*/
package org.opendaylight.yangtools.yang.parser.builder.impl;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
-import com.google.common.base.Optional;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.*;
+import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+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.util.Uint16;
-import org.opendaylight.yangtools.yang.parser.builder.api.*;
+import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
+import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.UsesNodeBuilder;
import org.opendaylight.yangtools.yang.parser.util.YangParseException;
+import com.google.common.base.Optional;
+
/**
* Test suite for increasing of test coverage of BuilderUtils implementation.
*
@Test
public void testFindModuleFromBuildersWithNullPrefix() throws Exception {
- final Map<String, TreeMap<Date, ModuleBuilder>> testModules = initModuleBuildersForTest();
+ final Map<String, NavigableMap<Date, ModuleBuilder>> testModules = initModuleBuildersForTest();
ModuleBuilder result = BuilderUtils.findModuleFromBuilders(testModules, masterModule, null, 12);
assertEquals(masterModule, result);
assertEquals(dependentModule, result);
}
- private Map<String, TreeMap<Date, ModuleBuilder>> initModuleBuildersForTest() throws Exception {
- final Map<String, TreeMap<Date, ModuleBuilder>> modules = new HashMap<>();
+ private Map<String, NavigableMap<Date, ModuleBuilder>> initModuleBuildersForTest() throws Exception {
+ final Map<String, NavigableMap<Date, ModuleBuilder>> modules = new HashMap<>();
final String module3Name = "Module3";
ModuleBuilder module3 = new ModuleBuilder(module3Name, "test/module/path/module3.yang");
dependentModule.addModuleImport(module3.getModuleName(), module3.getRevision(), "ter");
- final TreeMap<Date, ModuleBuilder> module1Map = new TreeMap<>();
+ final NavigableMap<Date, ModuleBuilder> module1Map = new TreeMap<>();
module1Map.put(masterModule.getRevision(), masterModule);
- final TreeMap<Date, ModuleBuilder> module2Map = new TreeMap<>();
+ final NavigableMap<Date, ModuleBuilder> module2Map = new TreeMap<>();
module2Map.put(dependentModule.getRevision(), dependentModule);
- final TreeMap<Date, ModuleBuilder> module3Map = new TreeMap<>();
+ final NavigableMap<Date, ModuleBuilder> module3Map = new TreeMap<>();
module3Map.put(module3.getRevision(), module3);
modules.put(masterModule.getName(), module1Map);
@Test(expected = YangParseException.class)
public void testFindModuleFromBuildersWithNoImportedModule() throws Exception {
- final Map<String, TreeMap<Date, ModuleBuilder>> testModules = initModuleBuildersForTest();
+ final Map<String, NavigableMap<Date, ModuleBuilder>> testModules = initModuleBuildersForTest();
BuilderUtils.findModuleFromBuilders(testModules, masterModule, "eth", 12);
}
@Test
public void testFindModule() {
- final Map<URI, TreeMap<Date, ModuleBuilder>> modules = new HashMap<>(1);
- final TreeMap<Date, ModuleBuilder> masterModuleMap = new TreeMap<>();
+ final Map<URI, NavigableMap<Date, ModuleBuilder>> modules = new HashMap<>(1);
+ final NavigableMap<Date, ModuleBuilder> masterModuleMap = new TreeMap<>();
masterModuleMap.put(masterModule.getRevision(), masterModule);
modules.put(masterModule.getNamespace(), masterModuleMap);
+++ /dev/null
-package org.opendaylight.yangtools.yang.stmt.effective.build.test;
-
-import org.antlr.v4.runtime.ANTLRInputStream;
-import org.antlr.v4.runtime.CommonTokenStream;
-import org.antlr.v4.runtime.tree.ParseTreeWalker;
-import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementLexer;
-import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser;
-import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
-import org.opendaylight.yangtools.yang.parser.impl.YangStatementParserListenerImpl;
-import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
-import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
-import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
-import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
-import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-public class YangFileStatementSource implements StatementStreamSource {
-
- private YangStatementParserListenerImpl yangStatementModelParser;
- private YangStatementParser.StatementContext statementContext;
- private ParseTreeWalker walker;
-
- public YangFileStatementSource(String fileName) {
- try {
- statementContext = parseYangSource(loadFile(fileName));
- walker = new ParseTreeWalker();
- yangStatementModelParser = new YangStatementParserListenerImpl(REF);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- private StatementSourceReference REF = new StatementSourceReference() {
-
- @Override
- public StatementSource getStatementSource() {
- return StatementSource.DECLARATION;
- }
- };
-
- @Override
- public void writeLinkage(StatementWriter writer, QNameToStatementDefinition stmtDef) throws SourceException {
- yangStatementModelParser.setAttributes(writer, stmtDef);
- walker.walk(yangStatementModelParser, statementContext);
- }
-
- @Override
- public void writeLinkageAndStatementDefinitions(StatementWriter writer, QNameToStatementDefinition stmtDef, PrefixToModule prefixes) throws SourceException {
- yangStatementModelParser.setAttributes(writer, stmtDef, prefixes);
- walker.walk(yangStatementModelParser, statementContext);
- }
-
- @Override
- public void writeFull(StatementWriter writer, QNameToStatementDefinition stmtDef, PrefixToModule prefixes) throws SourceException {
- yangStatementModelParser.setAttributes(writer, stmtDef, prefixes);
- walker.walk(yangStatementModelParser, statementContext);
- }
-
- private FileInputStream loadFile(String fileName) throws Exception {
- return new FileInputStream(new File(getClass().getResource(fileName).toURI()));
- }
-
- private YangStatementParser.StatementContext parseYangSource(final InputStream stream) throws IOException {
- final YangStatementLexer lexer = new YangStatementLexer(new ANTLRInputStream(stream));
- final CommonTokenStream tokens = new CommonTokenStream(lexer);
- final YangStatementParser parser = new YangStatementParser(tokens);
- //TODO: no error listener yet
- //parser.removeErrorListeners();
- //final YangErrorListener errorListener = new YangErrorListener();
- //parser.addErrorListener(errorListener);
- final YangStatementParser.StatementContext result = parser.statement();
- //errorListener.validate();
- return result;
- }
-}
\ No newline at end of file
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import java.net.URI;
+
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.meta.ModelStatement;
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
-import java.net.URI;
+import com.google.common.collect.ImmutableList;
public class AugmentProcessTest {
private static final YangStatementSourceImpl ROOT = new YangStatementSourceImpl(
"/stmt-test/effective-build/aug-root.yang");
+ private static final QNameModule ROOT_QNAME_MODULE = QNameModule.create(URI.create("root"), null);
private static final QNameModule AUGMENTED_QNAME_MODULE = QNameModule.create(URI.create("aug"), null);
- QName augParent1 = QName.create(AUGMENTED_QNAME_MODULE, "aug-parent1");
- QName augParent2 = QName.create(AUGMENTED_QNAME_MODULE, "aug-parent2");
- QName contTarget = QName.create(AUGMENTED_QNAME_MODULE, "cont-target");
+ private static GroupingDefinition grp2Def;
+
+ private final QName augParent1 = QName.create(AUGMENTED_QNAME_MODULE, "aug-parent1");
+ private final QName augParent2 = QName.create(AUGMENTED_QNAME_MODULE, "aug-parent2");
+ private final QName contTarget = QName.create(AUGMENTED_QNAME_MODULE, "cont-target");
- QName contAdded1 = QName.create(AUGMENTED_QNAME_MODULE, "cont-added1");
- QName contAdded2 = QName.create(AUGMENTED_QNAME_MODULE, "cont-added2");
+ private final QName contAdded1 = QName.create(AUGMENTED_QNAME_MODULE, "cont-added1");
+ private final QName contAdded2 = QName.create(AUGMENTED_QNAME_MODULE, "cont-added2");
- QName list1 = QName.create(AUGMENTED_QNAME_MODULE, "list1");
- QName axml = QName.create(AUGMENTED_QNAME_MODULE, "axml");
+ private final QName list1 = QName.create(AUGMENTED_QNAME_MODULE, "list1");
+ private final QName axml = QName.create(AUGMENTED_QNAME_MODULE, "axml");
- QName contGrp = QName.create(AUGMENTED_QNAME_MODULE, "cont-grp");
- QName axmlGrp = QName.create(AUGMENTED_QNAME_MODULE, "axml-grp");
+ private final QName contGrp = QName.create(AUGMENTED_QNAME_MODULE, "cont-grp");
+ private final QName axmlGrp = QName.create(AUGMENTED_QNAME_MODULE, "axml-grp");
+
+ private final QName augCont1 = QName.create(ROOT_QNAME_MODULE, "aug-cont1");
+ private final QName augCont2 = QName.create(ROOT_QNAME_MODULE, "aug-cont2");
+
+ private final QName grpCont2 = QName.create(ROOT_QNAME_MODULE, "grp-cont2");
+ private final QName grpCont22 = QName.create(ROOT_QNAME_MODULE, "grp-cont22");
+ private final QName grpAdd = QName.create(ROOT_QNAME_MODULE, "grp-add");
@Test
public void readAndParseYangFileTest() throws SourceException, ReactorException {
CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
addSources(reactor, AUGMENTED, ROOT);
- final EffectiveSchemaContext result = reactor.buildEffective();
+ final EffectiveSchemaContext root = reactor.buildEffective();
+ assertNotNull(root);
- assertNotNull(result);
-
- Module augmentedModule = result.findModuleByName("augmented", null);
+ Module augmentedModule = root.findModuleByName("augmented", null);
assertNotNull(augmentedModule);
- ContainerSchemaNode augParent1Node = (ContainerSchemaNode) result.getDataChildByName(augParent1);
+ ContainerSchemaNode augParent1Node = (ContainerSchemaNode) root.getDataChildByName(augParent1);
ContainerSchemaNode augParent2Node = (ContainerSchemaNode) augParent1Node.getDataChildByName(augParent2);
ContainerSchemaNode targetContNode = (ContainerSchemaNode) augParent2Node.getDataChildByName(contTarget);
assertNotNull(targetContNode);
assertNotNull(contGrpNode);
AnyXmlSchemaNode axmlGrpNode = (AnyXmlSchemaNode) contGrpNode.getDataChildByName(axmlGrp);
assertNotNull(axmlGrpNode);
+
+ ContainerSchemaNode augCont1Node = (ContainerSchemaNode) root.getDataChildByName(augCont1);
+ ContainerSchemaNode augCont2Node = (ContainerSchemaNode) augCont1Node.getDataChildByName(augCont2);
+ assertNotNull(augCont2Node);
+
+ ContainerSchemaNode grpCont2Node = (ContainerSchemaNode) augCont2Node.getDataChildByName(grpCont2);
+ ContainerSchemaNode grpCont22Node = (ContainerSchemaNode) grpCont2Node.getDataChildByName(grpCont22);
+ assertNotNull(grpCont22Node);
+
+ ContainerSchemaNode grpAddNode = (ContainerSchemaNode) grpCont22Node.getDataChildByName(grpAdd);
+ assertNotNull(grpAddNode);
+ }
+
+ private <T extends ModelStatement> T findInStatements(QName target, ImmutableList<T> statements) {
+
+ for (final T statement : statements) {
+ if (target.equals(statement.statementDefinition().getArgumentName())) {
+ return statement;
+ }
+ }
+
+ return null;
}
private void addSources(CrossSourceStatementReactor.BuildAction reactor, StatementStreamSource... sources) {
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.yangtools.yang.stmt.test.augment;
+package org.opendaylight.yangtools.yang.stmt.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor.BuildAction;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.EffectiveModelContext;
import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
+import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
public class AugmentTest {
- private static final TestAugmentSource IMPORTED = new TestAugmentSource("imp", "/a");
- private static final TestAugmentSource VALID_ABS = new TestAugmentSource("root", "/aug1/aug11/aug111");
- private static final TestAugmentSource VALID_ABS_PREFIXED = new TestAugmentSource("root",
- "/imp:aug1/imp:aug11/imp:aug111", "imp");
- private static final TestAugmentSource VALID_REL = new TestAugmentSource("root", "aug1/aug11");
- private static final TestAugmentSource VALID_REL_PREFIXED = new TestAugmentSource("root",
- "imp:aug1/imp:aug11/imp:aug111", "imp");
- private static final TestAugmentSource INVALID_REL_WHITE_SPACE = new TestAugmentSource("root", ".. /aug1/aug11");
- private static final TestAugmentSource INVALID_REL1 = new TestAugmentSource("root", "./aug1/aug11");
- private static final TestAugmentSource INVALID_REL2 = new TestAugmentSource("root", "../aug1/aug11");
- private static final TestAugmentSource INVALID_ABS = new TestAugmentSource("root", "//aug1/aug11/aug111");
- private static final TestAugmentSource INVALID_ABS_PREFIXED_NO_IMP = new TestAugmentSource("root",
- "imp:aug1/imp:aug11/imp:aug111");
- private static final TestAugmentSource INVALID_EMPTY = new TestAugmentSource("root", "");
- private static final TestAugmentSource INVALID_XPATH = new TestAugmentSource("root", "/aug1/-");
+ private static final YangStatementSourceImpl IMPORTED = new YangStatementSourceImpl(
+ "/semantic-statement-parser/augment-arg-parsing/imported.yang");
+
+ private static YangStatementSourceImpl VALID_ARGS = new YangStatementSourceImpl(
+ "/semantic-statement-parser/augment-arg-parsing/root-valid-aug-args.yang");
+ private static YangStatementSourceImpl INVALID_REL1 = new YangStatementSourceImpl(
+ "/semantic-statement-parser/augment-arg-parsing/root-invalid-rel1.yang");
+ private static YangStatementSourceImpl INVALID_REL2 = new YangStatementSourceImpl(
+ "/semantic-statement-parser/augment-arg-parsing/root-invalid-rel2.yang");
+ private static YangStatementSourceImpl INVALID_ABS = new YangStatementSourceImpl(
+ "/semantic-statement-parser/augment-arg-parsing/root-invalid-abs.yang");
+ private static YangStatementSourceImpl INVALID_ABS_PREFIXED_NO_IMP = new YangStatementSourceImpl(
+ "/semantic-statement-parser/augment-arg-parsing/root-invalid-abs-no-imp.yang");
+ private static YangStatementSourceImpl INVALID_EMPTY = new YangStatementSourceImpl(
+ "/semantic-statement-parser/augment-arg-parsing/root-invalid-empty.yang");
+ private static YangStatementSourceImpl INVALID_XPATH = new YangStatementSourceImpl(
+ "/semantic-statement-parser/augment-arg-parsing/root-invalid-xpath.yang");
@Test
public void validAugAbsTest() throws SourceException, ReactorException {
BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
- addSources(reactor, VALID_ABS);
+ addSources(reactor, IMPORTED, VALID_ARGS);
- try {
- reactor.build();
- } catch (Exception e) {
- // if augment argument is correct we only catch an exception that it cannot be found in mock model
- assertEquals(NullPointerException.class, e.getClass());
- }
- }
-
- @Test
- public void validAugAbsPrefixedTest() throws SourceException, ReactorException {
-
- BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
- addSources(reactor, IMPORTED, VALID_ABS_PREFIXED);
-
- try {
- reactor.build();
- } catch (Exception e) {
- // if augment argument is correct we only catch an exception that it cannot be found in mock model
- assertEquals(NullPointerException.class, e.getClass());
- }
- }
-
- @Test
- public void validAugRelTest() throws SourceException, ReactorException {
-
- BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
- addSources(reactor, VALID_REL);
-
- try {
- reactor.build();
- } catch (Exception e) {
- // if augment argument is correct we only catch an exception that it cannot be found in mock model
- assertEquals(NullPointerException.class, e.getClass());
- }
- }
-
- @Test
- public void validAugRelPrefixedTest() throws SourceException, ReactorException {
-
- BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
- addSources(reactor, IMPORTED, VALID_REL_PREFIXED);
-
- try {
- reactor.build();
- } catch (Exception e) {
- // if augment argument is correct we only catch an exception that it cannot be found in mock model
- assertEquals(NullPointerException.class, e.getClass());
- }
- }
-
- @Test
- public void validAugRelWhiteSpaceTest() throws SourceException, ReactorException {
-
- BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
- addSources(reactor, INVALID_REL_WHITE_SPACE);
-
- try {
- reactor.build();
- fail("reactor.process should fail due to invalid relative path");
- } catch (Exception e) {
- assertEquals(IllegalArgumentException.class, e.getClass());
- }
+ final EffectiveModelContext result = reactor.build();
+ assertNotNull(result);
}
@Test
}
}
- private void addSources(BuildAction reactor, TestAugmentSource... sources) {
- for (TestAugmentSource source : sources) {
+ private void addSources(BuildAction reactor, YangStatementSourceImpl... sources) {
+ for (YangStatementSourceImpl source : sources) {
reactor.addSource(source);
}
}
-
}
import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter;
+import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
+import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
class ImportBasicTestStatementSource implements StatementStreamSource {
writer.endStatement(REF);
return this;
}
-
-
}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.yangtools.yang.stmt.test.key;
+package org.opendaylight.yangtools.yang.stmt.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
import org.junit.Test;
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor.BuildAction;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.EffectiveModelContext;
import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
-
-import static org.junit.Assert.*;
+import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
public class KeyTest {
- private static final TestKeySource KEY_SIMPLE = new TestKeySource("root", "key");
- private static final TestKeySource KEY_COMP = new TestKeySource("root", "key1 key2 key3");
- private static final TestKeySource KEY_COMP_DUPLICATE = new TestKeySource("root", "key1 key1 key2");
+ private static final YangStatementSourceImpl KEY_SIMPLE_AND_COMP = new YangStatementSourceImpl(
+ "/semantic-statement-parser/key-arg-parsing/key-simple-and-comp.yang");
+ private static final YangStatementSourceImpl KEY_COMP_DUPLICATE = new YangStatementSourceImpl(
+ "/semantic-statement-parser/key-arg-parsing/key-comp-duplicate.yang");
@Test
public void keySimpleTest() throws SourceException, ReactorException {
BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
- addSources(reactor, KEY_SIMPLE);
-
- EffectiveModelContext result = reactor.build();
- assertNotNull(result);
- }
-
- @Test
- public void keyCompositeTest() throws SourceException, ReactorException {
-
- BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
- addSources(reactor, KEY_COMP);
+ addSources(reactor, KEY_SIMPLE_AND_COMP);
EffectiveModelContext result = reactor.build();
assertNotNull(result);
}
}
- private void addSources(BuildAction reactor, TestKeySource... sources) {
- for (TestKeySource source : sources) {
+ private void addSources(BuildAction reactor, YangStatementSourceImpl... sources) {
+ for (YangStatementSourceImpl source : sources) {
reactor.addSource(source);
}
}
+++ /dev/null
-package org.opendaylight.yangtools.yang.stmt.test.augment;
-
-import static org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping.AUGMENT;
-import static org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping.IMPORT;
-import static org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping.MODULE;
-import static org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping.NAMESPACE;
-import static org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping.PREFIX;
-
-import java.util.Arrays;
-
-import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
-import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
-import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
-import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
-import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
-import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
-import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter;
-
-public class TestAugmentSource implements StatementStreamSource {
-
- private static final String NS_PREFIX = "urn:org:opendaylight:yangtools:test:";
-
- private final String name;
- private final String augment;
- private final java.util.List<String> imports;
- private StatementWriter writer;
- private StatementSourceReference REF = new StatementSourceReference() {
-
- @Override
- public StatementSource getStatementSource() {
- return StatementSource.DECLARATION;
- }
- };
-
- public TestAugmentSource(String name, String augment, String... imports) {
- this.name = name;
- this.augment = augment;
- this.imports = Arrays.asList(imports);
- }
-
- @Override
- public void writeFull(StatementWriter writer, QNameToStatementDefinition stmtDef, PrefixToModule prefixes)
- throws SourceException {
- this.writer = writer;
- header();
- extensions();
- body();
- end();
- }
-
- @Override
- public void writeLinkage(StatementWriter writer, QNameToStatementDefinition stmtDef) throws SourceException {
- this.writer = writer;
- header().end();
- }
-
- @Override
- public void writeLinkageAndStatementDefinitions(StatementWriter writer, QNameToStatementDefinition stmtDef,
- PrefixToModule prefixes) throws SourceException {
- this.writer = writer;
- header();
- extensions();
- end();
- }
-
- protected void extensions() throws SourceException {
-
- }
-
- protected void body() throws SourceException {
-
- stmt(AUGMENT).arg(augment);
- end();
- }
-
- TestAugmentSource header() throws SourceException {
-
- stmt(MODULE).arg(name);
- {
- stmt(NAMESPACE).arg(getNamespace()).end();
- stmt(PREFIX).arg(name).end();
- }
-
- for (String impEntry : imports) {
-
- stmt(IMPORT).arg(impEntry);
- {
- stmt(PREFIX).arg(impEntry).end();
- }
- end();
- }
-
- return this;
- }
-
- private String getNamespace() {
- return NS_PREFIX + name;
- }
-
- protected TestAugmentSource arg(String arg) throws SourceException {
- writer.argumentValue(arg, REF);
- return this;
- }
-
- protected TestAugmentSource stmt(Rfc6020Mapping stmt) throws SourceException {
- writer.startStatement(stmt.getStatementName(), REF);
- return this;
- }
-
- protected TestAugmentSource end() throws SourceException {
- writer.endStatement(REF);
- return this;
- }
-}
+++ /dev/null
-package org.opendaylight.yangtools.yang.stmt.test.key;
-
-import static org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping.KEY;
-import static org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping.MODULE;
-import static org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping.NAMESPACE;
-import static org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping.PREFIX;
-
-import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
-import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
-import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
-import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
-import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
-import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
-import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter;
-
-public class TestKeySource implements StatementStreamSource {
-
- private static final String NS_PREFIX = "urn:org:opendaylight:yangtools:test:";
-
- private final String name;
- private final String key;
- private StatementWriter writer;
- private StatementSourceReference REF = new StatementSourceReference() {
-
- @Override
- public StatementSource getStatementSource() {
- return StatementSource.DECLARATION;
- }
- };
-
- public TestKeySource(String name, String key) {
- this.name = name;
- this.key = key;
- }
-
- @Override
- public void writeFull(StatementWriter writer, QNameToStatementDefinition stmtDef, PrefixToModule prefixes)
- throws SourceException {
-
- this.writer = writer;
-
- header();
- extensions();
- body();
- end();
- }
-
- @Override
- public void writeLinkage(StatementWriter writer, QNameToStatementDefinition stmtDef) throws SourceException {
- this.writer = writer;
- header().end();
- }
-
- @Override
- public void writeLinkageAndStatementDefinitions(StatementWriter writer, QNameToStatementDefinition stmtDef,
- PrefixToModule prefixes) throws SourceException {
- this.writer = writer;
- header();
- extensions();
- end();
- }
-
- protected void extensions() throws SourceException {
-
- }
-
- protected void body() throws SourceException {
-
- stmt(Rfc6020Mapping.LIST).arg("lst");
- {
- stmt(KEY).arg(key).end();
- }
- end();
- }
-
- TestKeySource header() throws SourceException {
-
- stmt(MODULE).arg(name);
- {
- stmt(NAMESPACE).arg(getNamespace()).end();
- stmt(PREFIX).arg(name).end();
- }
-
- return this;
- }
-
- private String getNamespace() {
- return NS_PREFIX + name;
- }
-
- protected TestKeySource arg(String arg) throws SourceException {
- writer.argumentValue(arg, REF);
- return this;
- }
-
- protected TestKeySource stmt(Rfc6020Mapping stmt) throws SourceException {
- writer.startStatement(stmt.getStatementName(), REF);
- return this;
- }
-
- protected TestKeySource end() throws SourceException {
- writer.endStatement(REF);
- return this;
- }
-}
--- /dev/null
+module imported {
+ namespace imp;
+ prefix imp;
+
+ container aug1 {
+ container aug11 {
+ container aug111 {
+
+ }
+ }
+ }
+
+ grouping grp {
+ container aug2 {
+ container aug22 {
+ }
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+module root-invalid-abs-no-imp {
+ namespace root;
+ prefix root;
+
+ augment "imp:aug1/imp:aug11/imp:aug111" {
+ container add {
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+module root-invalid-abs {
+ namespace root;
+ prefix root;
+
+ augment "//aug1/aug11/aug111" {
+ container add {
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+module root-invalid-empty {
+ namespace root;
+ prefix root;
+
+ augment "" {
+ container add {
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+module root-invalid-rel1 {
+ namespace root;
+ prefix root;
+
+ augment "./aug1/aug11" {
+ container add {
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+module root-invalid-rel2 {
+ namespace root;
+ prefix root;
+
+ augment "../aug1/aug11" {
+ container add {
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+module root-invalid-xpath {
+ namespace root;
+ prefix root;
+
+ augment "/aug1/-" {
+ container add {
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+module root-valid-aug-args {
+ namespace root;
+ prefix root;
+
+ import imported;
+
+ augment "/aug1/aug11/aug111" {
+ container add {
+ }
+ }
+
+ container aug1 {
+ container aug11 {
+ container aug111 {
+
+ }
+ }
+ }
+
+ augment "/imp:aug1/imp:aug11/imp:aug111" {
+ container add {
+ }
+ }
+
+ grouping grp {
+ container aug2 {
+ container aug22 {
+ }
+ }
+ }
+
+ uses grp {
+
+ augment "aug2/aug22" {
+ container add {
+ }
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+module key-comp-duplicate {
+ namespace root;
+ prefix root;
+
+ list comp {
+ key "key1 key2 key2";
+ container key1 {
+ }
+ container key2 {
+ }
+ container key3 {
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+module key-simple-and-comp {
+ namespace root;
+ prefix root;
+
+ list simple {
+ key "key1";
+ container key1 {
+ }
+ }
+
+ list comp {
+ key "key1 key2 key3";
+ container key1 {
+ }
+ container key2 {
+ }
+ container key3 {
+ }
+ }
+}
\ No newline at end of file
prefix aug;
}
- augment "aug:aug-parent1/aug:aug-parent2/aug:cont-target" {
+ augment "/aug:aug-parent1/aug:aug-parent2/aug:cont-target" {
container cont-added1 {
list list1 {
}
uses aug:grp;
}
+
+ grouping grp2 {
+ container grp-cont2 {
+ container grp-cont22 {
+ }
+ }
+ }
+
+ container aug-cont1 {
+ container aug-cont2 {
+ uses grp2 {
+ augment "grp-cont2/grp-cont22" {
+ container grp-add {
+ }
+ }
+ }
+ }
+ }
}
\ No newline at end of file