From: Moiz Raja Date: Tue, 21 Oct 2014 21:12:19 +0000 (-0700) Subject: BUG 1833 : Remove all unused code from sal-clustering-commons X-Git-Tag: release/lithium~985 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=commitdiff_plain;h=a07755bec17af9099a19437a7d08d1363f44c92f;ds=sidebyside BUG 1833 : Remove all unused code from sal-clustering-commons Change-Id: I7ce05b4ee77b6151f361091b18d1a7bbd8ed408a Signed-off-by: Moiz Raja (cherry picked from commit 4861f2406206bf208a07a703ad8d6808072c6e45) --- diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeToNormalizedNodeBuilder.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeToNormalizedNodeBuilder.java deleted file mode 100644 index 03d632b61f..0000000000 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeToNormalizedNodeBuilder.java +++ /dev/null @@ -1,856 +0,0 @@ -/* - * - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - */ - -package org.opendaylight.controller.cluster.datastore.node; - -import com.google.common.base.Preconditions; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import org.opendaylight.controller.cluster.datastore.node.utils.NodeIdentifierFactory; -import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node; -import org.opendaylight.yangtools.concepts.Identifiable; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; -import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode; -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.LeafSetEntryNode; -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.api.schema.NormalizedNodeContainer; -import org.opendaylight.yangtools.yang.data.impl.schema.Builders; -import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; -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.AugmentationTarget; -import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode; -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; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import static com.google.common.base.Preconditions.checkArgument; - -/** - * NormalizedNodeBuilder is a builder that walks through a tree like structure and constructs a - * NormalizedNode from it. - *

- * A large part of this code has been copied over from a similar class in sal-common-impl which was - * originally supposed to convert a CompositeNode to NormalizedNode - * - * @param - */ -public abstract class NodeToNormalizedNodeBuilder - implements Identifiable { - - private final T identifier; - - protected static final Logger logger = LoggerFactory - .getLogger(NodeToNormalizedNodeBuilder.class); - - @Override - public T getIdentifier() { - return identifier; - } - - ; - - protected NodeToNormalizedNodeBuilder(final T identifier) { - super(); - this.identifier = identifier; - - } - - /** - * @return Should return true if the node that this operation corresponds to is a mixin - */ - public boolean isMixin() { - return false; - } - - - /** - * @return Should return true if the node that this operation corresponds to has a 'key' - * associated with it. This is typically true for a list-item or leaf-list entry in yang - */ - public boolean isKeyedEntry() { - return false; - } - - protected Set getQNameIdentifiers() { - return Collections.singleton(identifier.getNodeType()); - } - - public abstract NodeToNormalizedNodeBuilder getChild( - final PathArgument child); - - public abstract NodeToNormalizedNodeBuilder getChild(QName child); - - public abstract NormalizedNode normalize(QName nodeType, Node node); - - - - private static abstract class SimpleTypeNormalization - extends NodeToNormalizedNodeBuilder { - - protected SimpleTypeNormalization(final T identifier) { - super(identifier); - } - - @Override - public NormalizedNode normalize(final QName nodeType, - final Node node) { - checkArgument(node != null); - return normalizeImpl(nodeType, node); - } - - protected abstract NormalizedNode normalizeImpl(QName nodeType, - Node node); - - @Override - public NodeToNormalizedNodeBuilder getChild( - final PathArgument child) { - return null; - } - - @Override - public NodeToNormalizedNodeBuilder getChild(final QName child) { - return null; - } - - @Override - public NormalizedNode createDefault( - final PathArgument currentArg) { - // TODO Auto-generated method stub - return null; - } - - } - - - private static final class LeafNormalization extends - SimpleTypeNormalization { - - private final LeafSchemaNode schema; - - protected LeafNormalization(final LeafSchemaNode schema, final NodeIdentifier identifier) { - super(identifier); - this.schema = schema; - } - - @Override - protected NormalizedNode normalizeImpl(final QName nodeType, - final Node node) { - Object value = NodeValueCodec.toTypeSafeValue(this.schema, this.schema.getType(), node); - return ImmutableNodes.leafNode(nodeType, value); - - } - - } - - - private static final class LeafListEntryNormalization extends - SimpleTypeNormalization { - - private final LeafListSchemaNode schema; - - public LeafListEntryNormalization(final LeafListSchemaNode potential) { - super(new NodeWithValue(potential.getQName(), null)); - this.schema = potential; - } - - @Override - protected NormalizedNode normalizeImpl(final QName nodeType, - final Node node) { - final Object data = node.getValue(); - if (data == null) { - Preconditions.checkArgument(false, - "No data available in leaf list entry for " + nodeType); - } - - Object value = NodeValueCodec.toTypeSafeValue(this.schema, this.schema.getType(), node); - - NodeWithValue nodeId = new NodeWithValue(nodeType, value); - return Builders.leafSetEntryBuilder().withNodeIdentifier(nodeId) - .withValue(value).build(); - } - - - @Override - public boolean isKeyedEntry() { - return true; - } - } - - - private static abstract class NodeToNormalizationNodeOperation - extends NodeToNormalizedNodeBuilder { - - protected NodeToNormalizationNodeOperation(final T identifier) { - super(identifier); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public final NormalizedNodeContainer normalize( - final QName nodeType, final Node node) { - checkArgument(node != null); - - if (!node.getType().equals(AugmentationNode.class.getSimpleName()) - && !node.getType().equals(ContainerNode.class.getSimpleName()) - && !node.getType().equals(MapNode.class.getSimpleName())) { - checkArgument(nodeType != null); - } - - NormalizedNodeContainerBuilder builder = createBuilder(node); - - Set> usedMixins = new HashSet<>(); - - logNode(node); - - if (node.getChildCount() == 0 && ( - node.getType().equals(LeafSetEntryNode.class.getSimpleName()) - || node.getType().equals(LeafNode.class.getSimpleName()))) { - PathArgument childPathArgument = - NodeIdentifierFactory.getArgument(node.getPath()); - - final NormalizedNode child; - if (childPathArgument instanceof NodeWithValue) { - final NodeWithValue nodeWithValue = - new NodeWithValue(childPathArgument.getNodeType(), - node.getValue()); - child = - Builders.leafSetEntryBuilder() - .withNodeIdentifier(nodeWithValue) - .withValue(node.getValue()).build(); - } else { - child = - ImmutableNodes.leafNode(childPathArgument.getNodeType(), - node.getValue()); - } - builder.addChild(child); - } - - final List children = node.getChildList(); - for (Node nodeChild : children) { - - PathArgument childPathArgument = - NodeIdentifierFactory.getArgument(nodeChild.getPath()); - - QName childNodeType = null; - NodeToNormalizedNodeBuilder childOp = null; - - if (childPathArgument instanceof AugmentationIdentifier) { - childOp = getChild(childPathArgument); - checkArgument(childOp instanceof AugmentationNormalization, childPathArgument); - } else { - childNodeType = childPathArgument.getNodeType(); - childOp = getChild(childNodeType); - } - // We skip unknown nodes if this node is mixin since - // it's nodes and parent nodes are interleaved - if (childOp == null && isMixin()) { - continue; - } else if (childOp == null) { - logger.error( - "childOp is null and this operation is not a mixin : this = {}", - this.toString()); - } - - checkArgument(childOp != null, - "Node %s is not allowed inside %s", - childNodeType, getIdentifier()); - - if (childOp.isMixin()) { - if (usedMixins.contains(childOp)) { - // We already run / processed that mixin, so to avoid - // duplicate we are - // skipping next nodes. - continue; - } - // builder.addChild(childOp.normalize(nodeType, treeCacheNode)); - final NormalizedNode childNode = - childOp.normalize(childNodeType, nodeChild); - if (childNode != null) - builder.addChild(childNode); - usedMixins.add(childOp); - } else { - final NormalizedNode childNode = - childOp.normalize(childNodeType, nodeChild); - if (childNode != null) - builder.addChild(childNode); - } - } - - - try { - return (NormalizedNodeContainer) builder.build(); - } catch (Exception e) { - return null; - } - - } - - private void logNode(Node node) { - //let us find out the type of the node - logger.debug("We got a {} , with identifier {} with {} children", - node.getType(), node.getPath(), - node.getChildList()); - } - - @SuppressWarnings("rawtypes") - protected abstract NormalizedNodeContainerBuilder createBuilder( - final Node node); - - } - - - private static abstract class DataContainerNormalizationOperation - extends NodeToNormalizationNodeOperation { - - private final DataNodeContainer schema; - private final Map> byQName; - private final Map> byArg; - - protected DataContainerNormalizationOperation(final T identifier, - final DataNodeContainer schema) { - super(identifier); - this.schema = schema; - this.byArg = new ConcurrentHashMap<>(); - this.byQName = new ConcurrentHashMap<>(); - } - - @Override - public NodeToNormalizedNodeBuilder getChild( - final PathArgument child) { - NodeToNormalizedNodeBuilder potential = byArg.get(child); - if (potential != null) { - return potential; - } - potential = fromSchema(schema, child); - return register(potential); - } - - @Override - public NodeToNormalizedNodeBuilder getChild(final QName child) { - if (child == null) { - return null; - } - - NodeToNormalizedNodeBuilder potential = byQName.get(child); - if (potential != null) { - return potential; - } - potential = fromSchemaAndPathArgument(schema, child); - return register(potential); - } - - private NodeToNormalizedNodeBuilder register( - final NodeToNormalizedNodeBuilder potential) { - if (potential != null) { - byArg.put(potential.getIdentifier(), potential); - for (QName qName : potential.getQNameIdentifiers()) { - byQName.put(qName, potential); - } - } - return potential; - } - - } - - - private static final class ListItemNormalization extends - DataContainerNormalizationOperation { - - private final List keyDefinition; - private final ListSchemaNode schemaNode; - - protected ListItemNormalization( - final NodeIdentifierWithPredicates identifier, - final ListSchemaNode schema) { - super(identifier, schema); - this.schemaNode = schema; - keyDefinition = schema.getKeyDefinition(); - } - - @Override - protected NormalizedNodeContainerBuilder createBuilder( - final Node node) { - NodeIdentifierWithPredicates nodeIdentifierWithPredicates = - (NodeIdentifierWithPredicates) NodeIdentifierFactory - .createPathArgument(node - .getPath(), schemaNode); - return Builders.mapEntryBuilder() - .withNodeIdentifier( - nodeIdentifierWithPredicates - ); - } - - @Override - public NormalizedNode createDefault( - final PathArgument currentArg) { - DataContainerNodeAttrBuilder - builder = - Builders.mapEntryBuilder().withNodeIdentifier( - (NodeIdentifierWithPredicates) currentArg); - for (Entry keyValue : ((NodeIdentifierWithPredicates) currentArg) - .getKeyValues().entrySet()) { - if (keyValue.getValue() == null) { - throw new NullPointerException( - "Null value found for path : " - + currentArg); - } - builder.addChild(Builders.leafBuilder() - // - .withNodeIdentifier(new NodeIdentifier(keyValue.getKey())) - .withValue(keyValue.getValue()).build()); - } - return builder.build(); - } - - - @Override - public boolean isKeyedEntry() { - return true; - } - } - - - private static final class ContainerNormalization extends - DataContainerNormalizationOperation { - - protected ContainerNormalization(final ContainerSchemaNode schema) { - super(new NodeIdentifier(schema.getQName()), schema); - } - - @Override - protected NormalizedNodeContainerBuilder createBuilder( - final Node node) { - return Builders.containerBuilder() - .withNodeIdentifier(getIdentifier()); - } - - @Override - public NormalizedNode createDefault( - final PathArgument currentArg) { - return Builders.containerBuilder() - .withNodeIdentifier((NodeIdentifier) currentArg).build(); - } - - } - - - private static abstract class MixinNormalizationOp - extends NodeToNormalizationNodeOperation { - - protected MixinNormalizationOp(final T identifier) { - super(identifier); - } - - @Override - public final boolean isMixin() { - return true; - } - - } - - - private static final class LeafListMixinNormalization extends - MixinNormalizationOp { - - private final NodeToNormalizedNodeBuilder innerOp; - - public LeafListMixinNormalization(final LeafListSchemaNode potential) { - super(new NodeIdentifier(potential.getQName())); - innerOp = new LeafListEntryNormalization(potential); - } - - @Override - protected NormalizedNodeContainerBuilder createBuilder( - final Node node) { - return Builders.leafSetBuilder() - .withNodeIdentifier(getIdentifier()); - } - - @Override - public NormalizedNode createDefault( - final PathArgument currentArg) { - return Builders.leafSetBuilder().withNodeIdentifier(getIdentifier()) - .build(); - } - - @Override - public NodeToNormalizedNodeBuilder getChild( - final PathArgument child) { - if (child instanceof NodeWithValue) { - return innerOp; - } - return null; - } - - @Override - public NodeToNormalizedNodeBuilder getChild(final QName child) { - if (getIdentifier().getNodeType().equals(child)) { - return innerOp; - } - return null; - } - - } - - - private static final class AugmentationNormalization extends - MixinNormalizationOp { - - private final Map> byQName; - private final Map> byArg; - - public AugmentationNormalization(final AugmentationSchema augmentation, - final DataNodeContainer schema) { - super(augmentationIdentifierFrom(augmentation)); - - ImmutableMap.Builder> - byQNameBuilder = - ImmutableMap.builder(); - ImmutableMap.Builder> - byArgBuilder = - ImmutableMap.builder(); - - for (DataSchemaNode augNode : augmentation.getChildNodes()) { - DataSchemaNode resolvedNode = - schema.getDataChildByName(augNode.getQName()); - NodeToNormalizedNodeBuilder resolvedOp = - fromDataSchemaNode(resolvedNode); - byArgBuilder.put(resolvedOp.getIdentifier(), resolvedOp); - for (QName resQName : resolvedOp.getQNameIdentifiers()) { - byQNameBuilder.put(resQName, resolvedOp); - } - } - byQName = byQNameBuilder.build(); - byArg = byArgBuilder.build(); - - } - - @Override - public NodeToNormalizedNodeBuilder getChild( - final PathArgument child) { - return byArg.get(child); - } - - @Override - public NodeToNormalizedNodeBuilder getChild(final QName child) { - return byQName.get(child); - } - - @Override - protected Set getQNameIdentifiers() { - return getIdentifier().getPossibleChildNames(); - } - - @SuppressWarnings("rawtypes") - @Override - protected NormalizedNodeContainerBuilder createBuilder( - final Node node) { - return Builders.augmentationBuilder() - .withNodeIdentifier(getIdentifier()); - } - - @Override - public NormalizedNode createDefault( - final PathArgument currentArg) { - return Builders.augmentationBuilder() - .withNodeIdentifier(getIdentifier()) - .build(); - } - - } - - - private static final class ListMixinNormalization extends - MixinNormalizationOp { - - private final ListItemNormalization innerNode; - - public ListMixinNormalization(final ListSchemaNode list) { - super(new NodeIdentifier(list.getQName())); - this.innerNode = - new ListItemNormalization(new NodeIdentifierWithPredicates( - list.getQName(), Collections.emptyMap()), - list); - } - - @SuppressWarnings("rawtypes") - @Override - protected NormalizedNodeContainerBuilder createBuilder( - final Node node) { - return Builders.mapBuilder().withNodeIdentifier(getIdentifier()); - } - - @Override - public NormalizedNode createDefault( - final PathArgument currentArg) { - return Builders.mapBuilder().withNodeIdentifier(getIdentifier()) - .build(); - } - - @Override - public NodeToNormalizedNodeBuilder getChild( - final PathArgument child) { - if (child.getNodeType().equals(getIdentifier().getNodeType())) { - return innerNode; - } - return null; - } - - @Override - public NodeToNormalizedNodeBuilder getChild(final QName child) { - if (getIdentifier().getNodeType().equals(child)) { - return innerNode; - } - return null; - } - - } - - - private static class ChoiceNodeNormalization extends - MixinNormalizationOp { - - private final ImmutableMap> - byQName; - private final ImmutableMap> - byArg; - - protected ChoiceNodeNormalization( - final org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) { - super(new NodeIdentifier(schema.getQName())); - ImmutableMap.Builder> - byQNameBuilder = - ImmutableMap.builder(); - ImmutableMap.Builder> - byArgBuilder = - ImmutableMap.builder(); - - for (ChoiceCaseNode caze : schema.getCases()) { - for (DataSchemaNode cazeChild : caze.getChildNodes()) { - NodeToNormalizedNodeBuilder childOp = - fromDataSchemaNode(cazeChild); - byArgBuilder.put(childOp.getIdentifier(), childOp); - for (QName qname : childOp.getQNameIdentifiers()) { - byQNameBuilder.put(qname, childOp); - } - } - } - byQName = byQNameBuilder.build(); - byArg = byArgBuilder.build(); - } - - @Override - public NodeToNormalizedNodeBuilder getChild( - final PathArgument child) { - return byArg.get(child); - } - - @Override - public NodeToNormalizedNodeBuilder getChild(final QName child) { - return byQName.get(child); - } - - @Override - protected NormalizedNodeContainerBuilder createBuilder( - final Node node) { - return Builders.choiceBuilder().withNodeIdentifier(getIdentifier()); - } - - @Override - public NormalizedNode createDefault( - final PathArgument currentArg) { - return Builders.choiceBuilder().withNodeIdentifier(getIdentifier()) - .build(); - } - } - - /** - * Find an appropriate NormalizedNodeBuilder using both the schema and the - * Path Argument - * - * @param schema - * @param child - * @return - */ - public static NodeToNormalizedNodeBuilder fromSchemaAndPathArgument( - final DataNodeContainer schema, final QName child) { - DataSchemaNode potential = schema.getDataChildByName(child); - if (potential == null) { - Iterable - choices = - FluentIterable.from(schema.getChildNodes()).filter( - org.opendaylight.yangtools.yang.model.api.ChoiceNode.class); - potential = findChoice(choices, child); - } - if (potential == null) { - if (logger.isTraceEnabled()) { - logger.trace("BAD CHILD = {}", child.toString()); - } - } - - checkArgument(potential != null, - "Supplied QName %s is not valid according to schema %s", child, - schema); - - // If the schema in an instance of DataSchemaNode and the potential - // is augmenting something then there is a chance that this may be - // and augmentation node - if ((schema instanceof DataSchemaNode) - && potential.isAugmenting()) { - - AugmentationNormalization augmentation = - fromAugmentation(schema, (AugmentationTarget) schema, - potential); - - // If an augmentation normalization (builder) is not found then - // we fall through to the regular processing - if(augmentation != null){ - return augmentation; - } - } - return fromDataSchemaNode(potential); - } - - /** - * Given a bunch of choice nodes and a the name of child find a choice node for that child which - * has a non-null value - * - * @param choices - * @param child - * @return - */ - private static org.opendaylight.yangtools.yang.model.api.ChoiceNode findChoice( - final Iterable choices, - final QName child) { - org.opendaylight.yangtools.yang.model.api.ChoiceNode foundChoice = null; - choiceLoop: - for (org.opendaylight.yangtools.yang.model.api.ChoiceNode choice : choices) { - for (ChoiceCaseNode caze : choice.getCases()) { - if (caze.getDataChildByName(child) != null) { - foundChoice = choice; - break choiceLoop; - } - } - } - return foundChoice; - } - - - /** - * Create an AugmentationIdentifier based on the AugmentationSchema - * - * @param augmentation - * @return - */ - public static AugmentationIdentifier augmentationIdentifierFrom( - final AugmentationSchema augmentation) { - ImmutableSet.Builder potentialChildren = ImmutableSet.builder(); - for (DataSchemaNode child : augmentation.getChildNodes()) { - potentialChildren.add(child.getQName()); - } - return new AugmentationIdentifier(potentialChildren.build()); - } - - /** - * Create an AugmentationNormalization based on the schema of the DataContainer, the - * AugmentationTarget and the potential schema node - * - * @param schema - * @param augments - * @param potential - * @return - */ - private static AugmentationNormalization fromAugmentation( - final DataNodeContainer schema, final AugmentationTarget augments, - final DataSchemaNode potential) { - AugmentationSchema augmentation = null; - for (AugmentationSchema aug : augments.getAvailableAugmentations()) { - DataSchemaNode child = aug.getDataChildByName(potential.getQName()); - if (child != null) { - augmentation = aug; - break; - } - - } - if (augmentation != null) { - return new AugmentationNormalization(augmentation, schema); - } else { - return null; - } - } - - /** - * @param schema - * @param child - * @return - */ - private static NodeToNormalizedNodeBuilder fromSchema( - final DataNodeContainer schema, final PathArgument child) { - if (child instanceof AugmentationIdentifier) { - QName childQName = ((AugmentationIdentifier) child) - .getPossibleChildNames().iterator().next(); - - return fromSchemaAndPathArgument(schema, childQName); - } - return fromSchemaAndPathArgument(schema, child.getNodeType()); - } - - public static NodeToNormalizedNodeBuilder fromDataSchemaNode( - final DataSchemaNode potential) { - if (potential instanceof ContainerSchemaNode) { - return new ContainerNormalization((ContainerSchemaNode) potential); - } else if (potential instanceof ListSchemaNode) { - return new ListMixinNormalization((ListSchemaNode) potential); - } else if (potential instanceof LeafSchemaNode) { - return new LeafNormalization((LeafSchemaNode) potential, - new NodeIdentifier(potential.getQName())); - } else if (potential instanceof org.opendaylight.yangtools.yang.model.api.ChoiceNode) { - return new ChoiceNodeNormalization( - (org.opendaylight.yangtools.yang.model.api.ChoiceNode) potential); - } else if (potential instanceof LeafListSchemaNode) { - return new LeafListMixinNormalization( - (LeafListSchemaNode) potential); - } - return null; - } - - public static NodeToNormalizedNodeBuilder from(final SchemaContext ctx) { - return new ContainerNormalization(ctx); - } - - public abstract NormalizedNode createDefault(PathArgument currentArg); - -} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeValueCodec.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeValueCodec.java deleted file mode 100644 index b6dbefbbac..0000000000 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeValueCodec.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - */ - -package org.opendaylight.controller.cluster.datastore.node; - -import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory; -import org.opendaylight.controller.cluster.datastore.util.InstanceIdentifierUtils; -import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; -import org.opendaylight.yangtools.yang.data.api.codec.BitsCodec; -import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; -import org.opendaylight.yangtools.yang.model.util.IdentityrefType; -import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType; -import org.opendaylight.yangtools.yang.model.util.Leafref; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NodeValueCodec { - protected static final Logger logger = LoggerFactory - .getLogger(NodeValueCodec.class); - - public static Object toTypeSafeValue(DataSchemaNode schema, TypeDefinition type, NormalizedNodeMessages.Node node){ - - String value = node.getValue(); - - if(schema != null && value != null){ - TypeDefinition baseType = type; - - while (baseType.getBaseType() != null) { - baseType = baseType.getBaseType(); - } - - TypeDefinitionAwareCodec> codec = - TypeDefinitionAwareCodec.from(type); - - if(codec instanceof BitsCodec){ - if(value.contains("[]")){ - value = ""; - } else { - value = value.replace("[", ""); - value = value.replace("]", ""); - value = value.replace(",", " "); - } - } - - if (codec != null) { - return codec.deserialize(value); - } else if(baseType instanceof Leafref) { - return value; - } else if(baseType instanceof IdentityrefType) { - return QNameFactory.create(value); - } else if(baseType instanceof InstanceIdentifierType) { - return InstanceIdentifierUtils.fromSerializable(node.getInstanceIdentifierValue()); - } else { - logger.error("Could not figure out how to transform value " + value + " for schemaType " + type); - } - } - - return value; - } -} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToProtocolBufferNode.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToProtocolBufferNode.java deleted file mode 100644 index 68d3c590e0..0000000000 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToProtocolBufferNode.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - */ - -package org.opendaylight.controller.cluster.datastore.node; - -import com.google.common.base.Preconditions; -import org.opendaylight.controller.cluster.datastore.util.InstanceIdentifierUtils; -import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; -import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node; -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.ChoiceNode; -import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; -import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild; -import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode; -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.LeafSetNode; -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.MixinNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer; -import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode; - -import java.util.Map; - -/** - * NormalizedNodeToProtocolBufferNode walks the NormalizedNode tree converting it to the - * NormalizedMessage.Node - *

- * {@link org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode } is a tree like structure that provides a generic structure for a yang data - * model - */ -public class NormalizedNodeToProtocolBufferNode { - - - private final Node.Builder builderRoot; - private NormalizedNodeMessages.Container container; - - public NormalizedNodeToProtocolBufferNode() { - - builderRoot = Node.newBuilder(); - } - - public void encode(String parentPath, NormalizedNode normalizedNode) { - if (parentPath == null) { - parentPath = ""; - } - - NormalizedNodeMessages.Container.Builder containerBuilder = - NormalizedNodeMessages.Container.newBuilder(); - - if (normalizedNode != null) { - - navigateNormalizedNode(0, parentPath, normalizedNode, builderRoot); - // here we need to put back the Node Tree in Container - - container = - containerBuilder.setParentPath(parentPath).setNormalizedNode( - builderRoot.build()).build(); - } else { - //this can happen when an attempt was made to read from datastore and normalized node was null. - container = containerBuilder.setParentPath(parentPath).build(); - - } - - } - - - private void navigateDataContainerNode(int level, final String parentPath, - final DataContainerNode dataContainerNode, - Node.Builder builderParent) { - - String newParentPath = - parentPath + "/" + dataContainerNode.getIdentifier().toString(); - String type = getDataContainerType(dataContainerNode).getSimpleName(); - builderParent.setPath(dataContainerNode.getIdentifier().toString()) - .setType(type); - - final Iterable> - value = - dataContainerNode.getValue(); - for (NormalizedNode node : value) { - Node.Builder builderChild = Node.newBuilder(); - if (node instanceof MixinNode - && node instanceof NormalizedNodeContainer) { - - navigateNormalizedNodeContainerMixin(level, newParentPath, - (NormalizedNodeContainer) node, builderChild); - } else { - navigateNormalizedNode(level, newParentPath, node, - builderChild); - } - builderParent.addChild(builderChild); - } - } - - private Class getDataContainerType( - NormalizedNodeContainer dataContainerNode) { - if (dataContainerNode instanceof ChoiceNode) { - return ChoiceNode.class; - } else if (dataContainerNode instanceof AugmentationNode) { - return AugmentationNode.class; - } else if (dataContainerNode instanceof ContainerNode) { - return ContainerNode.class; - } else if (dataContainerNode instanceof MapEntryNode) { - return MapEntryNode.class; - } else if (dataContainerNode instanceof UnkeyedListEntryNode) { - return UnkeyedListEntryNode.class; - } else if (dataContainerNode instanceof MapNode) { - return MapNode.class; - } else if (dataContainerNode instanceof LeafSetNode) { - return LeafSetNode.class; - } - throw new IllegalArgumentException( - "could not find the data container node type " - + dataContainerNode.toString() - ); - } - - private void navigateNormalizedNodeContainerMixin(int level, - final String parentPath, - NormalizedNodeContainer node, Node.Builder builderParent) { - String newParentPath = - parentPath + "/" + node.getIdentifier().toString(); - - builderParent.setPath(node.getIdentifier().toString()).setType( - this.getDataContainerType(node).getSimpleName()); - final Iterable> value = node.getValue(); - for (NormalizedNode normalizedNode : value) { - // child node builder - Node.Builder builderChild = Node.newBuilder(); - if (normalizedNode instanceof MixinNode - && normalizedNode instanceof NormalizedNodeContainer) { - navigateNormalizedNodeContainerMixin(level + 1, newParentPath, - (NormalizedNodeContainer) normalizedNode, builderChild); - } else { - navigateNormalizedNode(level, newParentPath, normalizedNode, - builderChild); - } - builderParent.addChild(builderChild); - - } - - - - } - - - private void navigateNormalizedNode(int level, - String parentPath, NormalizedNode normalizedNode, - Node.Builder builderParent) { - - if (normalizedNode instanceof DataContainerNode) { - - final DataContainerNode dataContainerNode = - (DataContainerNode) normalizedNode; - - navigateDataContainerNode(level + 1, parentPath, dataContainerNode, - builderParent); - } else if (normalizedNode instanceof MixinNode - && normalizedNode instanceof NormalizedNodeContainer) { - - navigateNormalizedNodeContainerMixin(level, parentPath, - (NormalizedNodeContainer) normalizedNode, - builderParent); - } else { - if (normalizedNode instanceof LeafNode) { - buildLeafNode(parentPath, normalizedNode, builderParent); - } else if (normalizedNode instanceof LeafSetEntryNode) { - buildLeafSetEntryNode(parentPath, normalizedNode, - builderParent); - } - - } - - } - - private void buildLeafSetEntryNode(String parentPath, - NormalizedNode normalizedNode, - Node.Builder builderParent) { - String path = - parentPath + "/" + normalizedNode.getIdentifier().toString(); - LeafSetEntryNode leafSetEntryNode = (LeafSetEntryNode) normalizedNode; - Map attributes = leafSetEntryNode.getAttributes(); - if (!attributes.isEmpty()) { - NormalizedNodeMessages.Attribute.Builder builder = null; - for (Map.Entry attribute : attributes.entrySet()) { - builder = NormalizedNodeMessages.Attribute.newBuilder(); - - builder - .setName(attribute.getKey().toString()) - .setValue(normalizedNode.getValue().toString()); - - builderParent.addAttributes(builder.build()); - } - } - buildNodeValue(normalizedNode, builderParent); - } - - private void buildLeafNode(String parentPath, - NormalizedNode normalizedNode, - Node.Builder builderParent) { - Preconditions.checkNotNull(parentPath); - Preconditions.checkNotNull(normalizedNode); - String path = - parentPath + "/" + normalizedNode.getIdentifier().toString(); - LeafNode leafNode = (LeafNode) normalizedNode; - Map attributes = leafNode.getAttributes(); - if (!attributes.isEmpty()) { - NormalizedNodeMessages.Attribute.Builder builder = null; - for (Map.Entry attribute : attributes.entrySet()) { - builder = NormalizedNodeMessages.Attribute.newBuilder(); - builder - .setName(attribute.getKey().toString()) - .setValue(attribute.getValue().toString()); - - builderParent.addAttributes(builder.build()); - } - } - - Object value = normalizedNode.getValue(); - if (value == null) { - builderParent - .setPath(normalizedNode.getIdentifier().toString()) - .setType(LeafNode.class.getSimpleName()) - .setValueType(String.class.getSimpleName()) - .setValue(""); - } else { - buildNodeValue(normalizedNode, builderParent); - } - } - - private void buildNodeValue(NormalizedNode normalizedNode, - Node.Builder builderParent) { - - Object value = normalizedNode.getValue(); - - builderParent - .setPath(normalizedNode.getIdentifier().toString()) - .setType(LeafNode.class.getSimpleName()) - .setValueType((value.getClass().getSimpleName())) - .setValue(value.toString()); - - if(value.getClass().equals(YangInstanceIdentifier.class)){ - builderParent.setInstanceIdentifierValue( - InstanceIdentifierUtils - .toSerializable((YangInstanceIdentifier) value)); - } - } - - public NormalizedNodeMessages.Container getContainer() { - return container; - } -} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java index ea3986f4a0..da61e6de73 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java @@ -32,20 +32,6 @@ public class NodeIdentifierFactory { return value; } - public static YangInstanceIdentifier.PathArgument getArgument(String id, DataSchemaNode schemaNode){ - YangInstanceIdentifier.PathArgument value = cache.get(id); - if(value == null){ - synchronized (cache){ - value = cache.get(id); - if(value == null) { - value = createPathArgument(id, schemaNode); - cache.put(id, value); - } - } - } - return value; - } - public static YangInstanceIdentifier.PathArgument createPathArgument(String id, DataSchemaNode schemaNode){ final NodeIdentifierWithPredicatesGenerator nodeIdentifierWithPredicatesGenerator = new NodeIdentifierWithPredicatesGenerator(id, schemaNode); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/util/EncoderDecoderUtil.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/util/EncoderDecoderUtil.java deleted file mode 100644 index 90f5cf3396..0000000000 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/util/EncoderDecoderUtil.java +++ /dev/null @@ -1,333 +0,0 @@ -/* - * - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - */ - -package org.opendaylight.controller.cluster.datastore.util; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode; -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.LeafSetEntryNode; -import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode; -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.codec.xml.XmlDocumentUtils; -import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils; -import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory; -import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer.DomFromNormalizedNodeSerializerFactory; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchema; -import org.opendaylight.yangtools.yang.model.api.ChoiceNode; -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; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.ByteArrayInputStream; -import java.io.StringWriter; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -/* - * - * EncoderDecoderUtil helps in wrapping the NormalizedNode into a SimpleNormalizedNode - * protobuf message containing the XML representation of the NormalizeNode - * - * @author: syedbahm - */ -public class EncoderDecoderUtil { - static DocumentBuilderFactory factory; - - private static DomFromNormalizedNodeSerializerFactory serializerFactory = - DomFromNormalizedNodeSerializerFactory - .getInstance(XmlDocumentUtils.getDocument(), - DomUtils.defaultValueCodecProvider()); - - private static DomToNormalizedNodeParserFactory parserFactory = - DomToNormalizedNodeParserFactory - .getInstance(DomUtils.defaultValueCodecProvider()); - - static { - factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - factory.setCoalescing(true); - factory.setIgnoringElementContentWhitespace(true); - factory.setIgnoringComments(true); - } - - private static DataSchemaNode findChildNode(Collection children, - String name) { - List containers = Lists.newArrayList(); - - for (DataSchemaNode dataSchemaNode : children) { - if (dataSchemaNode.getQName().getLocalName().equals(name)) - return dataSchemaNode; - if (dataSchemaNode instanceof DataNodeContainer) { - containers.add((DataNodeContainer) dataSchemaNode); - } else if (dataSchemaNode instanceof ChoiceNode) { - containers.addAll(((ChoiceNode) dataSchemaNode).getCases()); - } - } - - for (DataNodeContainer container : containers) { - DataSchemaNode retVal = - findChildNode(container.getChildNodes(), name); - if (retVal != null) { - return retVal; - } - } - - return null; - } - - private static DataSchemaNode getSchemaNode(SchemaContext context, - QName qname) { - - for (Module module : context - .findModuleByNamespace(qname.getNamespace())) { - // we will take the first child as the start of the - if (module.getChildNodes() != null || !module.getChildNodes() - .isEmpty()) { - - DataSchemaNode found = - findChildNode(module.getChildNodes(), qname.getLocalName()); - return found; - } - } - return null; - } - - private static String toString(Element xml) { - try { - Transformer transformer = - TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - - StreamResult result = new StreamResult(new StringWriter()); - DOMSource source = new DOMSource(xml); - transformer.transform(source, result); - - return result.getWriter().toString(); - } catch (IllegalArgumentException | TransformerFactoryConfigurationError - | TransformerException e) { - throw new RuntimeException("Unable to serialize xml element " + xml, - e); - } - } - - private static String toString(Iterable xmlIterable) { - try { - Transformer transformer = - TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - - StreamResult result = new StreamResult(new StringWriter()); - Iterator iterator = xmlIterable.iterator(); - DOMSource source; - if(iterator.hasNext()) { - source = new DOMSource((org.w3c.dom.Node) iterator.next()); - transformer.transform(source, result); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - } - - while(iterator.hasNext()) { - source = new DOMSource((org.w3c.dom.Node) iterator.next()); - transformer.transform(source, result); - } - System.out.println(result.getWriter().toString()); - return result.getWriter().toString(); - } catch (IllegalArgumentException | TransformerFactoryConfigurationError - | TransformerException e) { - throw new RuntimeException("Unable to serialize xml element(s) " + xmlIterable.toString(), - e); - } - } - - private static Iterable serialize(DataSchemaNode schemaNode, NormalizedNode normalizedNode){ - if(schemaNode instanceof ContainerSchemaNode){ //1 - return serializerFactory - .getContainerNodeSerializer() - .serialize((ContainerSchemaNode) schemaNode, - (ContainerNode) normalizedNode); - } else if(schemaNode instanceof ChoiceNode){ //2 - return serializerFactory - .getChoiceNodeSerializer() - .serialize((ChoiceNode) schemaNode, - (org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode) normalizedNode); - } else if(schemaNode instanceof LeafSchemaNode){ //3 - return serializerFactory - .getLeafNodeSerializer() - .serialize((LeafSchemaNode) schemaNode, (LeafNode) normalizedNode); - } else if(schemaNode instanceof ListSchemaNode){ //4 - return serializerFactory - .getMapNodeSerializer() - .serialize((ListSchemaNode) schemaNode, (MapNode) normalizedNode); - } else if(schemaNode instanceof LeafListSchemaNode){ //5 - return serializerFactory - .getLeafSetNodeSerializer() - .serialize((LeafListSchemaNode) schemaNode, (LeafSetNode) normalizedNode); - } else if(schemaNode instanceof AugmentationSchema){//6 - return serializerFactory - .getAugmentationNodeSerializer() - .serialize((AugmentationSchema) schemaNode, (AugmentationNode) normalizedNode); - } else if(schemaNode instanceof ListSchemaNode && normalizedNode instanceof LeafSetEntryNode){ //7 - return serializerFactory - .getLeafSetEntryNodeSerializer() - .serialize((LeafListSchemaNode) schemaNode, (LeafSetEntryNode) normalizedNode); - } else if(schemaNode instanceof ListSchemaNode){ //8 - return serializerFactory - .getMapEntryNodeSerializer() - .serialize((ListSchemaNode) schemaNode, (MapEntryNode) normalizedNode); - } - - - - throw new UnsupportedOperationException(schemaNode.getClass().toString()); - } - - private static NormalizedNode parse(Document doc, DataSchemaNode schemaNode){ - if(schemaNode instanceof ContainerSchemaNode){ - return parserFactory - .getContainerNodeParser() - .parse(Collections.singletonList(doc.getDocumentElement()), - (ContainerSchemaNode) schemaNode); - - } else if(schemaNode instanceof ChoiceNode){ - return parserFactory - .getChoiceNodeParser() - .parse(Collections.singletonList(doc.getDocumentElement()), - (ChoiceNode) schemaNode); - } else if(schemaNode instanceof LeafNode){ - return parserFactory - .getLeafNodeParser() - .parse(Collections.singletonList(doc.getDocumentElement()), - (LeafSchemaNode) schemaNode); - } else if(schemaNode instanceof ListSchemaNode){ - return parserFactory - .getMapNodeParser() - .parse(Collections.singletonList(doc.getDocumentElement()), - (ListSchemaNode) schemaNode); - } else if(schemaNode instanceof LeafListSchemaNode){ - return parserFactory - .getLeafSetNodeParser() - .parse(Collections.singletonList(doc.getDocumentElement()), - (LeafListSchemaNode) schemaNode); - } else if(schemaNode instanceof AugmentationSchema){ - return parserFactory - .getAugmentationNodeParser() - .parse(Collections.singletonList(doc.getDocumentElement()), - (AugmentationSchema) schemaNode); - } else if(schemaNode instanceof ListSchemaNode){ - return parserFactory - .getMapEntryNodeParser() - .parse(Collections.singletonList(doc.getDocumentElement()), - (ListSchemaNode) schemaNode); - - } - - throw new UnsupportedOperationException(schemaNode.getClass().toString()); - } - - - /** - * Helps in generation of NormalizedNodeXml message for the supplied NormalizedNode - * - * @param sc --SchemaContext - * @param normalizedNode -- Normalized Node to be encoded - * @return SimpleNormalizedNodeMessage.NormalizedNodeXml - */ - public static SimpleNormalizedNodeMessage.NormalizedNodeXml encode( - SchemaContext sc, NormalizedNode normalizedNode) { - - Preconditions.checkArgument(sc != null, "Schema context found null"); - - Preconditions.checkArgument(normalizedNode != null, - "normalized node found null"); - - DataSchemaNode schemaNode = getSchemaNode(sc, - normalizedNode.getIdentifier() - .getNodeType() - ); - - Preconditions.checkState(schemaNode != null, - "Couldn't find schema node for " + normalizedNode.getIdentifier()); - - Iterable els = serialize(schemaNode, normalizedNode); - - String xmlString = toString(els.iterator().next()); - SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder builder = - SimpleNormalizedNodeMessage.NormalizedNodeXml.newBuilder(); - builder.setXmlString(xmlString); - builder - .setNodeIdentifier(normalizedNode.getIdentifier() - .getNodeType().toString()); - return builder.build(); - - } - - /** - * Utilizes the SimpleNormalizedNodeMessage.NormalizedNodeXml to convert into NormalizedNode - * - * @param sc -- schema context - * @param normalizedNodeXml -- containing the normalized Node XML - * @return NormalizedNode return - * @throws Exception - */ - - public static NormalizedNode decode(SchemaContext sc, - SimpleNormalizedNodeMessage.NormalizedNodeXml normalizedNodeXml) - throws Exception { - - Preconditions - .checkArgument(sc != null, "schema context seems to be null"); - - Preconditions.checkArgument(normalizedNodeXml != null, - "SimpleNormalizedNodeMessage.NormalizedNodeXml found to be null"); - QName qname = QName.create(normalizedNodeXml.getNodeIdentifier()); - - // here we will try to get back the NormalizedNode - DataSchemaNode schemaNode = getSchemaNode(sc, qname); - - // now we need to read the XML - Document doc = - factory.newDocumentBuilder().parse( - new ByteArrayInputStream( - normalizedNodeXml.getXmlString().getBytes( - "utf-8")) - ); - - doc.getDocumentElement().normalize(); - - - return parse(doc, schemaNode); - } - - - -} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/NormalizedNodeXmlConverterTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/NormalizedNodeXmlConverterTest.java deleted file mode 100644 index 853b3e264b..0000000000 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/NormalizedNodeXmlConverterTest.java +++ /dev/null @@ -1,483 +0,0 @@ -/* - * - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - */ -package org.opendaylight.controller.cluster.datastore.util; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import org.custommonkey.xmlunit.Diff; -import org.custommonkey.xmlunit.XMLUnit; -import org.junit.Test; -import org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage; -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.LeafSetEntryNode; -import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; -import org.opendaylight.yangtools.yang.data.api.schema.MapNode; -import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils; -import org.opendaylight.yangtools.yang.data.impl.schema.Builders; -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.api.ListNodeBuilder; -import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder; -import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils; -import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory; -import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer.DomFromNormalizedNodeSerializerFactory; -import org.opendaylight.yangtools.yang.model.api.ChoiceNode; -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.Module; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.net.URI; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Set; - - -/** - * Two of the testcases in the yangtools/yang-data-impl are leveraged (with modification) to create - * the serialization of NormalizedNode using the ProtocolBuffer - * - * @syedbahm - * - */ - - -public class NormalizedNodeXmlConverterTest { - private static final Logger logger = LoggerFactory - .getLogger(NormalizedNodeXmlConverterTest.class); - public static final String NAMESPACE = - "urn:opendaylight:params:xml:ns:yang:controller:test"; - private static Date revision; - private ContainerNode expectedNode; - private ContainerSchemaNode containerNode; - private String xmlPath; - - static { - try { - revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-03-13"); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } - - public static DataSchemaNode getSchemaNode(final SchemaContext context, - final String moduleName, final String childNodeName) { - for (Module module : context.getModules()) { - if (module.getName().equals(moduleName)) { - DataSchemaNode found = - findChildNode(module.getChildNodes(), childNodeName); - Preconditions.checkState(found != null, "Unable to find %s", - childNodeName); - return found; - } - } - throw new IllegalStateException("Unable to find child node " - + childNodeName); - } - - static DataSchemaNode findChildNode( - final Collection children, final String name) { - List containers = Lists.newArrayList(); - - for (DataSchemaNode dataSchemaNode : children) { - if (dataSchemaNode.getQName().getLocalName().equals(name)) { - return dataSchemaNode; - } - if (dataSchemaNode instanceof DataNodeContainer) { - containers.add((DataNodeContainer) dataSchemaNode); - } else if (dataSchemaNode instanceof ChoiceNode) { - containers.addAll(((ChoiceNode) dataSchemaNode).getCases()); - } - } - - for (DataNodeContainer container : containers) { - DataSchemaNode retVal = findChildNode(container.getChildNodes(), name); - if (retVal != null) { - return retVal; - } - } - - return null; - } - - public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier( - final String localName) { - return new YangInstanceIdentifier.NodeIdentifier(QName.create( - URI.create(NAMESPACE), revision, localName)); - } - - public static YangInstanceIdentifier.AugmentationIdentifier getAugmentIdentifier( - final String... childNames) { - Set qn = Sets.newHashSet(); - - for (String childName : childNames) { - qn.add(getNodeIdentifier(childName).getNodeType()); - } - - return new YangInstanceIdentifier.AugmentationIdentifier(qn); - } - - - public static ContainerNode augmentChoiceExpectedNode() { - - DataContainerNodeBuilder b = - Builders.containerBuilder(); - b.withNodeIdentifier(getNodeIdentifier("container")); - - b.withChild(Builders - .choiceBuilder() - .withNodeIdentifier(getNodeIdentifier("ch2")) - .withChild( - Builders.leafBuilder() - .withNodeIdentifier(getNodeIdentifier("c2Leaf")).withValue("2") - .build()) - .withChild( - Builders - .choiceBuilder() - .withNodeIdentifier(getNodeIdentifier("c2DeepChoice")) - .withChild( - Builders - .leafBuilder() - .withNodeIdentifier( - getNodeIdentifier("c2DeepChoiceCase1Leaf2")) - .withValue("2").build()).build()).build()); - - b.withChild(Builders - .choiceBuilder() - .withNodeIdentifier(getNodeIdentifier("ch3")) - .withChild( - Builders.leafBuilder() - .withNodeIdentifier(getNodeIdentifier("c3Leaf")).withValue("3") - .build()).build()); - - b.withChild(Builders - .augmentationBuilder() - .withNodeIdentifier(getAugmentIdentifier("augLeaf")) - .withChild( - Builders.leafBuilder() - .withNodeIdentifier(getNodeIdentifier("augLeaf")) - .withValue("augment").build()).build()); - - b.withChild(Builders - .augmentationBuilder() - .withNodeIdentifier(getAugmentIdentifier("ch")) - .withChild( - Builders - .choiceBuilder() - .withNodeIdentifier(getNodeIdentifier("ch")) - .withChild( - Builders.leafBuilder() - .withNodeIdentifier(getNodeIdentifier("c1Leaf")) - .withValue("1").build()) - .withChild( - Builders - .augmentationBuilder() - .withNodeIdentifier( - getAugmentIdentifier("c1Leaf_AnotherAugment", - "deepChoice")) - .withChild( - Builders - .leafBuilder() - .withNodeIdentifier( - getNodeIdentifier("c1Leaf_AnotherAugment")) - .withValue("1").build()) - .withChild( - Builders - .choiceBuilder() - .withNodeIdentifier( - getNodeIdentifier("deepChoice")) - .withChild( - Builders - .leafBuilder() - .withNodeIdentifier( - getNodeIdentifier("deepLeafc1")) - .withValue("1").build()).build()) - .build()).build()).build()); - - return b.build(); - } - - - - public void init(final String yangPath, final String xmlPath, - final ContainerNode expectedNode) throws Exception { - SchemaContext schema = parseTestSchema(yangPath); - this.xmlPath = xmlPath; - this.containerNode = - (ContainerSchemaNode) getSchemaNode(schema, "test", "container"); - this.expectedNode = expectedNode; - } - - SchemaContext parseTestSchema(final String yangPath) throws Exception { - - YangParserImpl yangParserImpl = new YangParserImpl(); - InputStream stream = - NormalizedNodeXmlConverterTest.class.getResourceAsStream(yangPath); - ArrayList al = new ArrayList(); - al.add(stream); - Set modules = yangParserImpl.parseYangModelsFromStreams(al); - return yangParserImpl.resolveSchemaContext(modules); - - } - - - @Test - public void testConversionWithAugmentChoice() throws Exception { - init("/augment_choice.yang", "/augment_choice.xml", - augmentChoiceExpectedNode()); - Document doc = loadDocument(xmlPath); - - ContainerNode built = - DomToNormalizedNodeParserFactory - .getInstance(DomUtils.defaultValueCodecProvider()) - .getContainerNodeParser() - .parse(Collections.singletonList(doc.getDocumentElement()), - containerNode); - - if (expectedNode != null) { - junit.framework.Assert.assertEquals(expectedNode, built); - } - - logger.info("{}", built); - - Iterable els = - DomFromNormalizedNodeSerializerFactory - .getInstance(XmlDocumentUtils.getDocument(), - DomUtils.defaultValueCodecProvider()) - .getContainerNodeSerializer().serialize(containerNode, built); - - Element el = els.iterator().next(); - - XMLUnit.setIgnoreWhitespace(true); - XMLUnit.setIgnoreComments(true); - - System.out.println(toString(doc.getDocumentElement())); - System.out.println(toString(el)); - - new Diff(XMLUnit.buildControlDocument(toString(doc.getDocumentElement())), - XMLUnit.buildTestDocument(toString(el))).similar(); - } - - private static ContainerNode listLeafListWithAttributes() { - DataContainerNodeBuilder b = - Builders.containerBuilder(); - b.withNodeIdentifier(getNodeIdentifier("container")); - - CollectionNodeBuilder listBuilder = - Builders.mapBuilder().withNodeIdentifier(getNodeIdentifier("list")); - - Map predicates = Maps.newHashMap(); - predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L); - - DataContainerNodeBuilder list1Builder = - Builders.mapEntryBuilder().withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifierWithPredicates( - getNodeIdentifier("list").getNodeType(), predicates)); - NormalizedNodeBuilder> uint32InListBuilder = - Builders.leafBuilder().withNodeIdentifier( - getNodeIdentifier("uint32InList")); - - list1Builder.withChild(uint32InListBuilder.withValue(3L).build()); - - listBuilder.withChild(list1Builder.build()); - b.withChild(listBuilder.build()); - - NormalizedNodeBuilder> booleanBuilder = - Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean")); - booleanBuilder.withValue(false); - b.withChild(booleanBuilder.build()); - - ListNodeBuilder> leafListBuilder = - Builders.leafSetBuilder().withNodeIdentifier( - getNodeIdentifier("leafList")); - - NormalizedNodeBuilder> leafList1Builder = - Builders.leafSetEntryBuilder().withNodeIdentifier( - new YangInstanceIdentifier.NodeWithValue(getNodeIdentifier( - "leafList").getNodeType(), "a")); - - leafList1Builder.withValue("a"); - - leafListBuilder.withChild(leafList1Builder.build()); - b.withChild(leafListBuilder.build()); - - return b.build(); - } - - - @Test - public void testConversionWithAttributes() throws Exception { - init("/test.yang", "/simple_xml_with_attributes.xml", - listLeafListWithAttributes()); - Document doc = loadDocument(xmlPath); - - ContainerNode built = - DomToNormalizedNodeParserFactory - .getInstance(DomUtils.defaultValueCodecProvider()) - .getContainerNodeParser() - .parse(Collections.singletonList(doc.getDocumentElement()), - containerNode); - - if (expectedNode != null) { - junit.framework.Assert.assertEquals(expectedNode, built); - } - - logger.info("{}", built); - - Iterable els = - DomFromNormalizedNodeSerializerFactory - .getInstance(XmlDocumentUtils.getDocument(), - DomUtils.defaultValueCodecProvider()) - .getContainerNodeSerializer().serialize(containerNode, built); - - Element el = els.iterator().next(); - - XMLUnit.setIgnoreWhitespace(true); - XMLUnit.setIgnoreComments(true); - - System.out.println(toString(doc.getDocumentElement())); - System.out.println(toString(el)); - - new Diff(XMLUnit.buildControlDocument(toString(doc.getDocumentElement())), - XMLUnit.buildTestDocument(toString(el))).similar(); - } - - - private Document loadDocument(final String xmlPath) throws Exception { - InputStream resourceAsStream = - NormalizedNodeXmlConverterTest.class.getResourceAsStream(xmlPath); - - Document currentConfigElement = readXmlToDocument(resourceAsStream); - Preconditions.checkNotNull(currentConfigElement); - return currentConfigElement; - } - - private static final DocumentBuilderFactory BUILDERFACTORY; - - static { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - factory.setCoalescing(true); - factory.setIgnoringElementContentWhitespace(true); - factory.setIgnoringComments(true); - BUILDERFACTORY = factory; - } - - private Document readXmlToDocument(final InputStream xmlContent) - throws IOException, SAXException { - DocumentBuilder dBuilder; - try { - dBuilder = BUILDERFACTORY.newDocumentBuilder(); - } catch (ParserConfigurationException e) { - throw new RuntimeException("Failed to parse XML document", e); - } - Document doc = dBuilder.parse(xmlContent); - - doc.getDocumentElement().normalize(); - return doc; - } - - public static String toString(final Element xml) { - try { - Transformer transformer = - TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - - StreamResult result = new StreamResult(new StringWriter()); - DOMSource source = new DOMSource(xml); - transformer.transform(source, result); - - return result.getWriter().toString(); - } catch (IllegalArgumentException | TransformerFactoryConfigurationError - | TransformerException e) { - throw new RuntimeException("Unable to serialize xml element " + xml, e); - } - } - - @Test - public void testConversionToNormalizedXml() throws Exception { - SimpleNormalizedNodeMessage.NormalizedNodeXml nnXml = - EncoderDecoderUtil.encode(parseTestSchema("/augment_choice.yang"), - augmentChoiceExpectedNode()); - Document expectedDoc = loadDocument("/augment_choice.xml"); - Document convertedDoc = - EncoderDecoderUtil.factory.newDocumentBuilder().parse( - new ByteArrayInputStream(nnXml.getXmlString().getBytes("utf-8"))); - System.out.println(toString(convertedDoc.getDocumentElement())); - XMLUnit.setIgnoreWhitespace(true); - XMLUnit.setIgnoreComments(true); - new Diff(XMLUnit.buildControlDocument(toString(expectedDoc - .getDocumentElement())), - XMLUnit.buildTestDocument(toString(convertedDoc.getDocumentElement()))) - .similar(); - System.out.println(toString(expectedDoc.getDocumentElement())); - - } - - - @Test - public void testConversionFromXmlToNormalizedNode() throws Exception { - SimpleNormalizedNodeMessage.NormalizedNodeXml nnXml = - EncoderDecoderUtil.encode(parseTestSchema("/test.yang"), - listLeafListWithAttributes()); - Document expectedDoc = loadDocument("/simple_xml_with_attributes.xml"); - Document convertedDoc = - EncoderDecoderUtil.factory.newDocumentBuilder().parse( - new ByteArrayInputStream(nnXml.getXmlString().getBytes("utf-8"))); - System.out.println(toString(convertedDoc.getDocumentElement())); - XMLUnit.setIgnoreWhitespace(true); - XMLUnit.setIgnoreComments(true); - new Diff(XMLUnit.buildControlDocument(toString(expectedDoc - .getDocumentElement())), - XMLUnit.buildTestDocument(toString(convertedDoc.getDocumentElement()))) - .similar(); - System.out.println(toString(expectedDoc.getDocumentElement())); - - // now we will try to convert xml back to normalize node. - ContainerNode cn = - (ContainerNode) EncoderDecoderUtil.decode( - parseTestSchema("/test.yang"), nnXml); - junit.framework.Assert.assertEquals(listLeafListWithAttributes(), cn); - - } - -}