Merge "Updater toaster to use datastore"
authorTony Tkacik <ttkacik@cisco.com>
Tue, 1 Apr 2014 11:07:44 +0000 (11:07 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Tue, 1 Apr 2014 11:07:44 +0000 (11:07 +0000)
30 files changed:
opendaylight/md-sal/sal-dom-broker/pom.xml
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/DataAndMetadataSnapshot.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/ModificationApplyOperation.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/MutableDataTree.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/SchemaAwareApplyOperation.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/SchemaAwareApplyOperationRoot.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ModificationType.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/NodeModification.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/StoreMetadataNode.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/StoreNodeCompositeBuilder.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/StoreTreeNode.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/TreeNodeUtils.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/ModificationMetadataTreeTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/TestModel.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/test/resources/odl-datastore-test.yang [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlDst.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlSrc.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlType.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlan.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlanPriority.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/InPort.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/Match.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/MatchField.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwDst.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwProtocol.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwSrc.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwTos.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpDst.java [new file with mode: 0644]
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpSrc.java [new file with mode: 0644]
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchExtensibleTest.java [new file with mode: 0644]

index d192bea54036ff62d3680c8561e816b330fbebbb..e3e5043e91bdfc16015f4e29f8596e461e257714 100644 (file)
   </scm>
 
     <dependencies>
+    <dependency>
+        <groupId>junit</groupId>
+        <artifactId>junit</artifactId>
+    </dependency>
         <dependency>
             <groupId>org.opendaylight.controller</groupId>
             <artifactId>sal-core-api</artifactId>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-api</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-simple</artifactId>
+            <version>${slf4j.version}</version>
+            <scope>test</scope>
+        </dependency>
         <dependency>
             <groupId>com.google.guava</groupId>
             <artifactId>guava</artifactId>
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/DataAndMetadataSnapshot.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/DataAndMetadataSnapshot.java
new file mode 100644 (file)
index 0000000..52f0051
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * 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.md.sal.dom.store.impl;
+
+import org.opendaylight.controller.md.sal.dom.store.impl.tree.StoreMetadataNode;
+import org.opendaylight.controller.md.sal.dom.store.impl.tree.TreeNodeUtils;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+import com.google.common.base.Optional;
+
+class DataAndMetadataSnapshot {
+
+    private final StoreMetadataNode metadataTree;
+    private final Optional<SchemaContext> schemaContext;
+
+
+
+
+    private DataAndMetadataSnapshot(final StoreMetadataNode metadataTree, final Optional<SchemaContext> schemaCtx) {
+        this.metadataTree = metadataTree;
+        this.schemaContext = schemaCtx;
+    }
+
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    public static DataAndMetadataSnapshot createEmpty(final NodeIdentifier rootNode) {
+        NormalizedNode<?, ?> data = Builders.containerBuilder().withNodeIdentifier(rootNode).build();
+        StoreMetadataNode metadata = StoreMetadataNode.builder()
+                .setData(data)
+                .build();
+        return new DataAndMetadataSnapshot(metadata,Optional.<SchemaContext>absent());
+    }
+
+    public static DataAndMetadataSnapshot createEmpty(final SchemaContext ctx) {
+        NodeIdentifier rootNodeIdentifier = new NodeIdentifier(ctx.getQName());
+        NormalizedNode<?, ?> data = Builders.containerBuilder().withNodeIdentifier(rootNodeIdentifier).build();
+        StoreMetadataNode metadata = StoreMetadataNode.builder()
+                .setData(data)
+                .build();
+        return new DataAndMetadataSnapshot(metadata, Optional.of(ctx));
+    }
+
+    public Optional<SchemaContext> getSchemaContext() {
+        return schemaContext;
+    }
+
+    public NormalizedNode<?, ?> getDataTree() {
+        return metadataTree.getData();
+    }
+
+    public StoreMetadataNode getMetadataTree() {
+        return metadataTree;
+    }
+
+    public Optional<StoreMetadataNode> read(final InstanceIdentifier path) {
+        return TreeNodeUtils.findNode(metadataTree, path);
+    }
+
+    public static class Builder {
+        private NormalizedNode<?, ?> dataTree;
+        private StoreMetadataNode metadataTree;
+        private SchemaContext schemaContext;
+
+        public NormalizedNode<?, ?> getDataTree() {
+            return dataTree;
+        }
+
+        public Builder setMetadataTree(final StoreMetadataNode metadataTree) {
+            this.metadataTree = metadataTree;
+            return this;
+        }
+
+        public Builder setSchemaContext(final SchemaContext schemaContext) {
+            this.schemaContext = schemaContext;
+            return this;
+        }
+
+        public DataAndMetadataSnapshot build() {
+            return new DataAndMetadataSnapshot(metadataTree, Optional.fromNullable(schemaContext));
+        }
+
+    }
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/ModificationApplyOperation.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/ModificationApplyOperation.java
new file mode 100644 (file)
index 0000000..3b9557c
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * 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.md.sal.dom.store.impl;
+
+import org.opendaylight.controller.md.sal.dom.store.impl.tree.NodeModification;
+import org.opendaylight.controller.md.sal.dom.store.impl.tree.StoreMetadataNode;
+import org.opendaylight.controller.md.sal.dom.store.impl.tree.StoreTreeNode;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+
+import com.google.common.base.Optional;
+
+/**
+ *
+ * Operation responsible for applying {@link NodeModification} on tree.
+ *
+ * Operation is composite - operation on top level node consists of
+ * suboperations on child nodes. This allows to walk operation hierarchy and
+ * invoke suboperations independently.
+ *
+ * <b>Implementation notes</b>
+ * <ul>
+ * <li>
+ * Implementations MUST expose all nested suboperations which operates on child
+ * nodes expose via {@link #getChild(PathArgument)} method.
+ * <li>Same suboperations SHOULD be used when invoked via
+ * {@link #apply(NodeModification, Optional)} if applicable.
+ *
+ *
+ * Hierarchical composite operation which is responsible for applying
+ * modification on particular subtree and creating updated subtree
+ *
+ *
+ */
+public interface ModificationApplyOperation extends StoreTreeNode<ModificationApplyOperation> {
+
+    /**
+     *
+     * Implementation of this operation must be stateless and must not change
+     * state of this object.
+     *
+     * @param modification
+     *            NodeModification to be applied
+     * @param storeMeta
+     *            Store Metadata Node on which NodeModification should be
+     *            applied
+     * @throws IllegalArgumentException
+     *             If it is not possible to apply Operation on provided Metadata
+     *             node
+     * @return new {@link StoreMetadataNode} if operation resulted in updating
+     *         node, {@link Optional#absent()} if {@link NodeModification}
+     *         resulted in deletion of this node.
+     */
+    Optional<StoreMetadataNode> apply(NodeModification modification, Optional<StoreMetadataNode> storeMeta);
+
+    /**
+     * Returns a suboperation for specified tree node
+     *
+     * @return Reference to suboperation for specified tree node, {@link Optional#absent()}
+     *    if suboperation is not supported for specified tree node.
+     */
+    @Override
+    public Optional<ModificationApplyOperation> getChild(PathArgument child);
+
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/MutableDataTree.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/MutableDataTree.java
new file mode 100644 (file)
index 0000000..ddf65b6
--- /dev/null
@@ -0,0 +1,112 @@
+/*
+ * 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.md.sal.dom.store.impl;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkState;
+
+import java.util.Map.Entry;
+
+import org.opendaylight.controller.md.sal.dom.store.impl.tree.NodeModification;
+import org.opendaylight.controller.md.sal.dom.store.impl.tree.StoreMetadataNode;
+import org.opendaylight.controller.md.sal.dom.store.impl.tree.TreeNodeUtils;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Optional;
+
+class MutableDataTree {
+
+    private static final Logger log = LoggerFactory.getLogger(MutableDataTree.class);
+
+    final DataAndMetadataSnapshot snapshot;
+    final NodeModification rootModification;
+    final ModificationApplyOperation strategyTree;
+
+    private  boolean sealed = false;
+
+    private MutableDataTree(final DataAndMetadataSnapshot snapshot, final ModificationApplyOperation strategyTree) {
+        this.snapshot = snapshot;
+        this.strategyTree = strategyTree;
+        this.rootModification = NodeModification.createUnmodified(snapshot.getMetadataTree());
+    }
+
+    public void write(final InstanceIdentifier path, final NormalizedNode<?, ?> value) {
+        checkSealed();
+        resolveModificationFor(path).write(value);
+    }
+
+    public void delete(final InstanceIdentifier path) {
+        checkSealed();
+        resolveModificationFor(path).delete();
+    }
+
+    public Optional<NormalizedNode<?, ?>> read(final InstanceIdentifier path) {
+        Entry<InstanceIdentifier, NodeModification> modification = TreeNodeUtils.findClosest(rootModification, path);
+        return getModifiedVersion(path, modification);
+    }
+
+    private Optional<NormalizedNode<?, ?>> getModifiedVersion(final InstanceIdentifier path, final Entry<InstanceIdentifier, NodeModification> modification) {
+        Optional<StoreMetadataNode> result = resolveSnapshot(modification);
+        if(result.isPresent()) {
+            NormalizedNode<?, ?> data = result.get().getData();
+            return NormalizedNodeUtils.findNode(modification.getKey(),data, path);
+        }
+        return Optional.absent();
+
+    }
+
+    private Optional<StoreMetadataNode> resolveSnapshot(final Entry<InstanceIdentifier, NodeModification> keyModification) {
+        InstanceIdentifier path = keyModification.getKey();
+        NodeModification modification = keyModification.getValue();
+        return resolveSnapshot(path,modification);
+    }
+
+    private Optional<StoreMetadataNode> resolveSnapshot(final InstanceIdentifier path, final NodeModification modification) {
+        try {
+            return resolveModificationStrategy(path).apply(modification,modification.getOriginal());
+        } catch (Exception e) {
+            log.error("Could not create snapshot for {},",e);
+            throw e;
+        }
+    }
+
+    private ModificationApplyOperation resolveModificationStrategy(final InstanceIdentifier path) {
+        log.trace("Resolving modification apply strategy for {}",path);
+        Optional<ModificationApplyOperation> strategy = TreeNodeUtils.findNode(strategyTree, path);
+        checkArgument(strategy.isPresent(),"Provided path %s is not supported by data store. No schema available for it.",path);
+        return strategy.get();
+    }
+
+    private NodeModification resolveModificationFor(final InstanceIdentifier path) {
+        NodeModification modification = rootModification;
+        // We ensure strategy is present.
+        resolveModificationStrategy(path);
+        for (PathArgument pathArg : path.getPath()) {
+            modification = modification.modifyChild(pathArg);
+        }
+        return modification;
+    }
+
+    public static MutableDataTree from(final DataAndMetadataSnapshot snapshot, final ModificationApplyOperation resolver) {
+        return new MutableDataTree(snapshot, resolver);
+    }
+
+    public void seal() {
+        sealed = true;
+        rootModification.seal();
+    }
+
+    private void checkSealed() {
+        checkState(!sealed , "Data Tree is sealed. No further modifications allowed.");
+    }
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/SchemaAwareApplyOperation.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/SchemaAwareApplyOperation.java
new file mode 100644 (file)
index 0000000..114595f
--- /dev/null
@@ -0,0 +1,343 @@
+package org.opendaylight.controller.md.sal.dom.store.impl;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+import java.util.Set;
+
+import org.opendaylight.controller.md.sal.dom.store.impl.tree.NodeModification;
+import org.opendaylight.controller.md.sal.dom.store.impl.tree.StoreMetadataNode;
+import org.opendaylight.controller.md.sal.dom.store.impl.tree.StoreNodeCompositeBuilder;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder;
+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.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 com.google.common.base.Optional;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSet.Builder;
+import com.google.common.primitives.UnsignedLong;
+
+public abstract class SchemaAwareApplyOperation implements ModificationApplyOperation {
+
+    public static SchemaAwareApplyOperation from(final DataSchemaNode schemaNode) {
+        if (schemaNode instanceof ContainerSchemaNode) {
+            return new ContainerModificationStrategy((ContainerSchemaNode) schemaNode);
+        } else if (schemaNode instanceof ListSchemaNode) {
+            return new ListMapModificationStrategy((ListSchemaNode) schemaNode);
+        } else if (schemaNode instanceof ChoiceNode) {
+            return new ChoiceModificationStrategy((ChoiceNode) schemaNode);
+        } else if (schemaNode instanceof LeafListSchemaNode) {
+            return new LeafSetEntryModificationStrategy((LeafListSchemaNode) schemaNode);
+        } else if (schemaNode instanceof LeafSchemaNode) {
+            return new LeafModificationStrategy((LeafSchemaNode) schemaNode);
+        }
+        throw new IllegalArgumentException("Not supported schema node type for " + schemaNode.getClass());
+    }
+
+    @Override
+    public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
+        throw new IllegalArgumentException();
+    }
+
+    protected final ModificationApplyOperation resolveChildOperation(final PathArgument child) {
+        Optional<ModificationApplyOperation> potential = getChild(child);
+        checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
+        return potential.get();
+    }
+
+    @Override
+    public final Optional<StoreMetadataNode> apply(final NodeModification modification,
+            final Optional<StoreMetadataNode> currentMeta) {
+        switch (modification.getModificationType()) {
+        case DELETE:
+            return Optional.absent();
+        case SUBTREE_MODIFIED:
+            return Optional.of(applySubtreeChange(modification, currentMeta.get()));
+        case WRITE:
+            return Optional.of(applyWrite(modification, currentMeta));
+        case UNMODIFIED:
+            return currentMeta;
+        default:
+            throw new IllegalArgumentException("Provided modification type is not supported.");
+        }
+    }
+
+    protected abstract StoreMetadataNode applyWrite(NodeModification modification,
+            Optional<StoreMetadataNode> currentMeta);
+
+    protected abstract StoreMetadataNode applySubtreeChange(NodeModification modification, StoreMetadataNode currentMeta);
+
+    public static abstract class ValueNodeModificationStrategy<T extends DataSchemaNode> extends
+            SchemaAwareApplyOperation {
+
+        private final T schema;
+
+        protected ValueNodeModificationStrategy(final T schema) {
+            super();
+            this.schema = schema;
+        }
+
+        @Override
+        public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
+            throw new UnsupportedOperationException("Node " + schema.getPath()
+                    + "is leaf type node. Child nodes not allowed");
+        }
+
+        @Override
+        protected StoreMetadataNode applySubtreeChange(final NodeModification modification, final StoreMetadataNode currentMeta) {
+            throw new UnsupportedOperationException("Node " + schema.getPath()
+                    + "is leaf type node. Subtree change is not allowed.");
+        }
+
+        @Override
+        protected StoreMetadataNode applyWrite(final NodeModification modification, final Optional<StoreMetadataNode> currentMeta) {
+            return StoreMetadataNode.builder()
+            // FIXME Add .increaseNodeVersion()
+                    .setData(modification.getWritenValue()).build();
+        }
+
+    }
+
+    public static class LeafSetEntryModificationStrategy extends ValueNodeModificationStrategy<LeafListSchemaNode> {
+
+        protected LeafSetEntryModificationStrategy(final LeafListSchemaNode schema) {
+            super(schema);
+        }
+    }
+
+    public static class LeafModificationStrategy extends ValueNodeModificationStrategy<LeafSchemaNode> {
+
+        protected LeafModificationStrategy(final LeafSchemaNode schema) {
+            super(schema);
+        }
+    }
+
+    public static abstract class NormalizedNodeContainerModificationStrategy extends SchemaAwareApplyOperation {
+
+        @Override
+        protected StoreMetadataNode applyWrite(final NodeModification modification, final Optional<StoreMetadataNode> currentMeta) {
+            //
+            NormalizedNode<?, ?> newValue = modification.getWritenValue();
+
+            StoreMetadataNode newValueMeta = StoreMetadataNode.createRecursivelly(newValue, UnsignedLong.valueOf(0));
+
+            if(!modification.hasAdditionalModifications()) {
+                return newValueMeta;
+            }
+            StoreNodeCompositeBuilder builder = StoreNodeCompositeBuilder.from(newValueMeta,
+                    createBuilder(modification.getIdentifier()));
+
+            Set<PathArgument> processedPreexisting = applyPreexistingChildren(modification, newValueMeta.getChildren(), builder);
+            applyNewChildren(modification, processedPreexisting, builder);
+
+            return builder.build();
+
+        }
+
+        @Override
+        @SuppressWarnings("rawtypes")
+        public StoreMetadataNode applySubtreeChange(final NodeModification modification, final StoreMetadataNode currentMeta) {
+
+            StoreNodeCompositeBuilder builder = StoreNodeCompositeBuilder.from(currentMeta,
+                    createBuilder(modification.getIdentifier()));
+            builder.setIdentifier(modification.getIdentifier());
+
+            // We process preexisting nodes
+            Set<PathArgument> processedPreexisting = applyPreexistingChildren(modification,
+                    currentMeta.getChildren(), builder);
+            applyNewChildren(modification, processedPreexisting, builder);
+            return builder.build();
+        }
+
+        private void applyNewChildren(final NodeModification modification, final Set<PathArgument> ignore,
+                final StoreNodeCompositeBuilder builder) {
+            for (NodeModification childModification : modification.getModifications()) {
+                PathArgument childIdentifier = childModification.getIdentifier();
+                // We skip allready processed modifications
+                if (ignore.contains(childIdentifier)) {
+                    continue;
+                }
+                Optional<StoreMetadataNode> childResult = resolveChildOperation(childIdentifier) //
+                        .apply(childModification, Optional.<StoreMetadataNode> absent());
+                if (childResult.isPresent()) {
+                    builder.add(childResult.get());
+                }
+            }
+        }
+
+        private Set<PathArgument> applyPreexistingChildren(final NodeModification modification,
+                final Iterable<StoreMetadataNode> children, final StoreNodeCompositeBuilder nodeBuilder) {
+            Builder<PathArgument> processedModifications = ImmutableSet.<PathArgument> builder();
+            for (StoreMetadataNode childMeta : children) {
+                PathArgument childIdentifier = childMeta.getIdentifier();
+                // We retrieve Child modification metadata
+                Optional<NodeModification> childModification = modification.getChild(childIdentifier);
+                // Node is modified
+                if (childModification.isPresent()) {
+                    processedModifications.add(childIdentifier);
+                    Optional<StoreMetadataNode> change = resolveChildOperation(childIdentifier) //
+                            .apply(childModification.get(), Optional.of(childMeta));
+                } else {
+                    // Child is unmodified - reuse existing metadata and data
+                    // snapshot
+                    nodeBuilder.add(childMeta);
+                }
+            }
+            return processedModifications.build();
+        }
+
+        @SuppressWarnings("rawtypes")
+        protected abstract NormalizedNodeContainerBuilder createBuilder(PathArgument identifier);
+    }
+
+    public static abstract class DataNodeContainerModificationStrategy<T extends DataNodeContainer> extends
+            NormalizedNodeContainerModificationStrategy {
+
+        private final T schema;
+
+        protected DataNodeContainerModificationStrategy(final T schema) {
+            super();
+            this.schema = schema;
+        }
+
+        protected T getSchema() {
+            return schema;
+        }
+
+        @Override
+        public Optional<ModificationApplyOperation> getChild(final PathArgument identifier) {
+            DataSchemaNode child = schema.getDataChildByName(identifier.getNodeType());
+            if (child == null || child.isAugmenting()) {
+                return Optional.absent();
+            }
+            return Optional.<ModificationApplyOperation> of(from(child));
+        }
+
+        @Override
+        @SuppressWarnings("rawtypes")
+        protected abstract DataContainerNodeBuilder createBuilder(PathArgument identifier);
+
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + " [" + schema + "]";
+        }
+
+    }
+
+    public static class ContainerModificationStrategy extends
+            DataNodeContainerModificationStrategy<ContainerSchemaNode> {
+
+        public ContainerModificationStrategy(final ContainerSchemaNode schemaNode) {
+            super(schemaNode);
+        }
+
+        @Override
+        @SuppressWarnings("rawtypes")
+        protected DataContainerNodeBuilder createBuilder(final PathArgument identifier) {
+            // TODO Auto-generated method stub
+            checkArgument(identifier instanceof NodeIdentifier);
+            return ImmutableContainerNodeBuilder.create().withNodeIdentifier((NodeIdentifier) identifier);
+        }
+
+    }
+
+    public static class ChoiceModificationStrategy extends NormalizedNodeContainerModificationStrategy {
+
+        private final ChoiceNode schema;
+
+        public ChoiceModificationStrategy(final ChoiceNode schemaNode) {
+            this.schema = schemaNode;
+        }
+
+        @Override
+        @SuppressWarnings("rawtypes")
+        protected DataContainerNodeBuilder createBuilder(final PathArgument identifier) {
+            checkArgument(identifier instanceof NodeIdentifier);
+            return ImmutableContainerNodeBuilder.create().withNodeIdentifier((NodeIdentifier) identifier);
+        }
+
+    }
+
+    public static class ListEntryModificationStrategy extends DataNodeContainerModificationStrategy<ListSchemaNode> {
+
+        protected ListEntryModificationStrategy(final ListSchemaNode schema) {
+            super(schema);
+        }
+
+        @Override
+        @SuppressWarnings("rawtypes")
+        protected final DataContainerNodeBuilder createBuilder(final PathArgument identifier) {
+            return ImmutableMapEntryNodeBuilder.create().withNodeIdentifier((NodeIdentifierWithPredicates) identifier);
+        }
+
+    }
+
+    public static class LeafSetModificationStrategy extends NormalizedNodeContainerModificationStrategy {
+
+        private final Optional<ModificationApplyOperation> entryStrategy;
+
+        protected LeafSetModificationStrategy(final LeafListSchemaNode schema) {
+            entryStrategy = Optional.<ModificationApplyOperation> of(new LeafSetEntryModificationStrategy(schema));
+        }
+
+        @Override
+        protected NormalizedNodeContainerBuilder createBuilder(final PathArgument identifier) {
+            return ImmutableLeafSetNodeBuilder.create().withNodeIdentifier((NodeIdentifier) identifier);
+        }
+
+        @Override
+        public Optional<ModificationApplyOperation> getChild(final PathArgument identifier) {
+            if (identifier instanceof NodeWithValue) {
+                return entryStrategy;
+            }
+            return Optional.absent();
+        }
+
+    }
+
+    public static class ListMapModificationStrategy extends NormalizedNodeContainerModificationStrategy {
+
+        private final Optional<ModificationApplyOperation> entryStrategy;
+
+        protected ListMapModificationStrategy(final ListSchemaNode schema) {
+            entryStrategy = Optional.<ModificationApplyOperation> of(new ListEntryModificationStrategy(schema));
+        }
+
+        @Override
+        protected NormalizedNodeContainerBuilder createBuilder(final PathArgument identifier) {
+            return ImmutableMapNodeBuilder.create().withNodeIdentifier((NodeIdentifier) identifier);
+        }
+
+        @Override
+        public Optional<ModificationApplyOperation> getChild(final PathArgument identifier) {
+            if (identifier instanceof NodeIdentifierWithPredicates) {
+                return entryStrategy;
+            }
+            return Optional.absent();
+        }
+
+        @Override
+        public String toString() {
+            return "ListMapModificationStrategy [entry=" + entryStrategy + "]";
+        }
+    }
+
+    public void verifyIdentifier(final PathArgument identifier) {
+
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/SchemaAwareApplyOperationRoot.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/SchemaAwareApplyOperationRoot.java
new file mode 100644 (file)
index 0000000..bca5069
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * 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.md.sal.dom.store.impl;
+
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class SchemaAwareApplyOperationRoot extends SchemaAwareApplyOperation.DataNodeContainerModificationStrategy<ContainerSchemaNode> {
+
+    private final SchemaContext context;
+
+    public SchemaAwareApplyOperationRoot(final SchemaContext context) {
+        super(context);
+        this.context = context;
+    }
+
+    @Override
+    protected DataContainerNodeBuilder createBuilder(final PathArgument identifier) {
+        return ImmutableContainerNodeBuilder.create().withNodeIdentifier((NodeIdentifier) identifier);
+    }
+
+    public SchemaContext getContext() {
+        return context;
+    }
+
+    @Override
+    public String toString() {
+        return "SchemaAwareApplyOperationRoot [context=" + context + "]";
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ModificationType.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ModificationType.java
new file mode 100644 (file)
index 0000000..199d902
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * 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.md.sal.dom.store.impl.tree;
+
+public enum ModificationType {
+
+    /**
+     *
+     * Node is unmodified
+     *
+     *
+     */
+    UNMODIFIED,
+    /**
+     *
+     * Child of tree node was modified
+     *
+     */
+    SUBTREE_MODIFIED,
+    /**
+     * Tree node was replaced with new value / subtree
+     *
+     */
+    WRITE,
+    /**
+     *
+     * Tree node is to be deleted.
+     *
+     */
+    DELETE
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/NodeModification.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/NodeModification.java
new file mode 100644 (file)
index 0000000..764afcb
--- /dev/null
@@ -0,0 +1,198 @@
+/*
+ * 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.md.sal.dom.store.impl.tree;
+
+import static com.google.common.base.Preconditions.checkState;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import org.opendaylight.yangtools.concepts.Identifiable;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+import com.google.common.base.Optional;
+
+/**
+ * Node Modification Node and Tree
+ *
+ * Tree which structurally resembles data tree and captures client modifications
+ * to the data store tree.
+ *
+ * This tree is lazily created and populated via {@link #modifyChild(PathArgument)}
+ * and {@link StoreMetadataNode} which represents original state {@link #getOriginal()}.
+ *
+ */
+public class NodeModification implements StoreTreeNode<NodeModification>, Identifiable<PathArgument> {
+
+    private final PathArgument identifier;
+    private ModificationType modificationType = ModificationType.UNMODIFIED;
+
+
+    private final Optional<StoreMetadataNode> original;
+
+    private NormalizedNode<?, ?> value;
+
+    private StoreMetadataNode snapshotCache;
+
+    private final Map<PathArgument, NodeModification> childModification;
+
+    private boolean sealed = false;
+
+    protected NodeModification(final PathArgument identifier, final Optional<StoreMetadataNode> original) {
+        this.identifier = identifier;
+        this.original = original;
+        childModification = new LinkedHashMap<>();
+    }
+
+    /**
+     *
+     *
+     * @return
+     */
+    public NormalizedNode<?, ?> getWritenValue() {
+        return value;
+    }
+
+    @Override
+    public PathArgument getIdentifier() {
+        return identifier;
+    }
+
+    /**
+     *
+     * Returns original store metadata
+     * @return original store metadata
+     */
+    public final Optional<StoreMetadataNode> getOriginal() {
+        return original;
+    }
+
+    /**
+     * Returns modification type
+     *
+     * @return modification type
+     */
+    public final ModificationType getModificationType() {
+        return modificationType;
+    }
+
+    /**
+     *
+     * Returns child modification if child was modified
+     *
+     * @return Child modification if direct child or it's subtree
+     *  was modified.
+     *
+     */
+    @Override
+    public Optional<NodeModification> getChild(final PathArgument child) {
+        return Optional.<NodeModification> fromNullable(childModification.get(child));
+    }
+
+    /**
+     *
+     * Returns child modification if child was modified, creates {@link NodeModification}
+     * for child otherwise.
+     *
+     * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
+     * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}
+     *
+     * @param child
+     * @return {@link NodeModification} for specified child, with {@link #getOriginal()}
+     *  containing child metadata if child was present in original data.
+     */
+    public synchronized NodeModification modifyChild(final PathArgument child) {
+        checkSealed();
+        if(modificationType == ModificationType.UNMODIFIED) {
+            updateModificationType(ModificationType.SUBTREE_MODIFIED);
+        }
+        final NodeModification potential = childModification.get(child);
+        if (potential != null) {
+            return potential;
+        }
+        Optional<StoreMetadataNode> currentMetadata = Optional.absent();
+        if(original.isPresent()) {
+            currentMetadata = original.get().getChild(child);
+        }
+        NodeModification newlyCreated = new NodeModification(child,currentMetadata);
+        childModification.put(child, newlyCreated);
+        return newlyCreated;
+    }
+
+    /**
+     *
+     * Returns all recorded direct child modification
+     *
+     * @return all recorded direct child modifications
+     */
+    public Iterable<NodeModification> getModifications() {
+        return childModification.values();
+    }
+
+
+    /**
+     *
+     * Records a delete for associated node.
+     *
+     */
+    public synchronized void delete() {
+        checkSealed();
+        updateModificationType(ModificationType.DELETE);
+        childModification.clear();
+        this.value = null;
+    }
+
+    /**
+     *
+     * Records a write for associated node.
+     *
+     * @param value
+     */
+    public synchronized void write(final NormalizedNode<?, ?> value) {
+        checkSealed();
+        updateModificationType(ModificationType.WRITE);
+        childModification.clear();
+        this.value = value;
+    }
+
+    private void checkSealed() {
+        checkState(!sealed, "Node Modification is sealed. No further changes allowed.");
+    }
+
+    public synchronized void seal() {
+        sealed = true;
+        for(NodeModification child : childModification.values()) {
+            child.seal();
+        }
+    }
+
+    private void clearSnapshot() {
+        snapshotCache = null;
+    }
+
+    public boolean hasAdditionalModifications() {
+        return !childModification.isEmpty();
+    }
+
+    public void updateModificationType(final ModificationType type) {
+        modificationType = type;
+        clearSnapshot();
+    }
+
+    @Override
+    public String toString() {
+        return "NodeModification [identifier=" + identifier + ", modificationType="
+                + modificationType + ", value=" + value + ", childModification=" + childModification + "]";
+    }
+
+    public static NodeModification createUnmodified(final StoreMetadataNode metadataTree) {
+        return new NodeModification(metadataTree.getIdentifier(), Optional.of(metadataTree));
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/StoreMetadataNode.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/StoreMetadataNode.java
new file mode 100644 (file)
index 0000000..974f817
--- /dev/null
@@ -0,0 +1,150 @@
+/*
+ * 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.md.sal.dom.store.impl.tree;
+
+import static com.google.common.base.Preconditions.checkState;
+
+import java.util.Map;
+
+import org.opendaylight.yangtools.concepts.Identifiable;
+import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.primitives.UnsignedLong;
+
+public class StoreMetadataNode implements Immutable, Identifiable<PathArgument>, StoreTreeNode<StoreMetadataNode> {
+
+    private final UnsignedLong nodeVersion;
+    private final UnsignedLong subtreeVersion;
+    private final NormalizedNode<?, ?> data;
+
+    private final Map<PathArgument, StoreMetadataNode> children;
+
+    protected StoreMetadataNode(final NormalizedNode<?, ?> data, final UnsignedLong nodeVersion, final UnsignedLong subtreeVersion,
+            final Map<PathArgument, StoreMetadataNode> children) {
+        this.nodeVersion = nodeVersion;
+        this.subtreeVersion = subtreeVersion;
+        this.data = data;
+        this.children = ImmutableMap.copyOf(children);
+
+    }
+
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    public UnsignedLong getNodeVersion() {
+        return this.nodeVersion;
+    }
+
+    @Override
+    public PathArgument getIdentifier() {
+        return data.getIdentifier();
+    }
+
+    public UnsignedLong getSubtreeVersion() {
+        return subtreeVersion;
+    }
+
+    public NormalizedNode<?, ?> getData() {
+        return this.data;
+    }
+
+    public Iterable<StoreMetadataNode> getChildren() {
+        return children.values();
+    }
+
+    @Override
+    public Optional<StoreMetadataNode> getChild(final PathArgument key) {
+        return Optional.fromNullable(children.get(key));
+    }
+
+    @Override
+    public String toString() {
+        return "StoreMetadataNode [identifier=" + getIdentifier() + ", nodeVersion=" + nodeVersion + "]";
+    }
+
+    public static Optional<UnsignedLong> getVersion(final Optional<StoreMetadataNode> currentMetadata) {
+        if (currentMetadata.isPresent()) {
+            return Optional.of(currentMetadata.get().getNodeVersion());
+        }
+        return Optional.absent();
+    }
+
+    public static Optional<StoreMetadataNode> getChild(final Optional<StoreMetadataNode> parent, final PathArgument child) {
+        if (parent.isPresent()) {
+            return parent.get().getChild(child);
+        }
+        return Optional.absent();
+    }
+
+    public static final StoreMetadataNode createRecursivelly(final NormalizedNode<?, ?> node, final UnsignedLong version) {
+        Builder builder = builder() //
+                .setNodeVersion(version) //
+                .setSubtreeVersion(version) //
+                .setData(node);
+        if(node instanceof NormalizedNodeContainer<?, ?, ?>) {
+
+            @SuppressWarnings("unchecked")
+            NormalizedNodeContainer<?, ?, NormalizedNode<?, ?>> nodeContainer = (NormalizedNodeContainer<?, ?, NormalizedNode<?, ?>>) node;
+            for(NormalizedNode<?, ?> subNode : nodeContainer.getValue()) {
+                builder.add(createRecursivelly(subNode, version));
+            }
+        }
+        return builder.build();
+    }
+
+    public static class Builder {
+
+        private Builder() {
+
+        }
+
+        UnsignedLong nodeVersion = UnsignedLong.valueOf(0);
+        UnsignedLong subtreeVersion = UnsignedLong.valueOf(0);
+        NormalizedNode<?, ?> data;
+
+        final ImmutableMap.Builder<PathArgument, StoreMetadataNode> children = ImmutableMap.builder();
+
+        public UnsignedLong getVersion() {
+            return nodeVersion;
+
+        }
+
+        public Builder setNodeVersion(final UnsignedLong version) {
+            this.nodeVersion = version;
+            return this;
+        }
+
+        public Builder setSubtreeVersion(final UnsignedLong version) {
+            this.subtreeVersion = version;
+            return this;
+        }
+
+        public Builder setData(final NormalizedNode<?,?> data) {
+            this.data = data;
+            return this;
+        }
+
+        public Builder add(final StoreMetadataNode node) {
+            children.put(node.getIdentifier(), node);
+            return this;
+        }
+
+        public StoreMetadataNode build() {
+            checkState(data != null,"Data node should not be null.");
+            checkState(subtreeVersion.compareTo(nodeVersion) >= 0, "Subtree version must be equals or greater than node version.");
+            return new StoreMetadataNode(data, nodeVersion, subtreeVersion, children.build());
+        }
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/StoreNodeCompositeBuilder.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/StoreNodeCompositeBuilder.java
new file mode 100644 (file)
index 0000000..d1583ca
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * 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.md.sal.dom.store.impl.tree;
+
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
+
+/**
+ *
+ * Helper builder
+ *
+ *
+ */
+@SuppressWarnings("rawtypes")
+public class StoreNodeCompositeBuilder {
+
+    private final StoreMetadataNode.Builder metadata;
+
+    private final NormalizedNodeContainerBuilder data;
+
+
+    private StoreNodeCompositeBuilder(final NormalizedNodeContainerBuilder nodeBuilder) {
+        this.metadata = StoreMetadataNode.builder();
+        this.data = nodeBuilder;
+    }
+
+    @SuppressWarnings("unchecked")
+    public StoreNodeCompositeBuilder add(final StoreMetadataNode node) {
+        metadata.add(node);
+        data.addChild(node.getData());
+        return this;
+    }
+
+
+    public StoreMetadataNode build() {
+        return metadata.setData(data.build()).build();
+    }
+
+
+    public static StoreNodeCompositeBuilder from(final NormalizedNodeContainerBuilder nodeBuilder) {
+        return new StoreNodeCompositeBuilder(nodeBuilder);
+    }
+
+    public static StoreNodeCompositeBuilder from(final StoreMetadataNode previous, final NormalizedNodeContainerBuilder nodeBuilder) {
+
+        return new StoreNodeCompositeBuilder(nodeBuilder);
+    }
+
+    public StoreNodeCompositeBuilder setIdentifier(final PathArgument identifier) {
+        data.withNodeIdentifier(identifier);
+        return this;
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/StoreTreeNode.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/StoreTreeNode.java
new file mode 100644 (file)
index 0000000..52beaa7
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * 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.md.sal.dom.store.impl.tree;
+
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+
+import com.google.common.base.Optional;
+/**
+ *
+ * Tree node which contains references to it's leafs
+ *
+ * @param <C> Final node type
+ */
+public interface StoreTreeNode<C extends StoreTreeNode<C>> {
+
+    /**
+     *
+     * Returns direct child of the node
+     *
+     * @param child Identifier of child
+     * @return Optional with node if the child is existing, {@link Optional#absent()} otherwise.
+     */
+    Optional<C> getChild(PathArgument child);
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/TreeNodeUtils.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/TreeNodeUtils.java
new file mode 100644 (file)
index 0000000..67cfde2
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * 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.md.sal.dom.store.impl.tree;
+
+import java.util.AbstractMap.SimpleEntry;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+
+import com.google.common.base.Optional;
+
+public class TreeNodeUtils {
+
+    /**
+     * Finds a node in tree
+     *
+     * @param tree Data Tree
+     * @param path Path to the node
+     * @return Optional with node if the node is present in tree, {@link Optional#absent()} otherwise.
+     *
+     */
+    public static <T extends StoreTreeNode<T>> Optional<T> findNode(final T tree, final InstanceIdentifier path) {
+        Optional<T> current = Optional.<T> of(tree);
+        Iterator<PathArgument> pathIter = path.getPath().iterator();
+        while (current.isPresent() && pathIter.hasNext()) {
+            current = current.get().getChild(pathIter.next());
+        }
+        return current;
+    }
+
+    /**
+     * Finds a node or closest parent in  the tree
+     *
+     * @param tree Data Tree
+     * @param path Path to the node
+     * @return Map.Entry Entry with key which is path to closest parent and value is parent node.
+     *
+     */
+    public static <T extends StoreTreeNode<T>> Map.Entry<InstanceIdentifier, T> findClosest(final T tree, final InstanceIdentifier path) {
+        Optional<T> parent = Optional.<T>of(tree);
+        Optional<T> current = Optional.<T> of(tree);
+
+        int nesting = 0;
+        Iterator<PathArgument> pathIter = path.getPath().iterator();
+        while (current.isPresent() && pathIter.hasNext()) {
+            parent = current;
+            current = current.get().getChild(pathIter.next());
+            nesting++;
+        }
+        if(current.isPresent()) {
+            final InstanceIdentifier currentPath = new InstanceIdentifier(path.getPath().subList(0, nesting));
+            return new SimpleEntry<InstanceIdentifier,T>(currentPath,current.get());
+        }
+        // Nesting minus one is safe, since current is allways present when nesting = 0
+        // so this prat of code is never triggered, in cases nesting == 0;
+        final InstanceIdentifier parentPath = new InstanceIdentifier(path.getPath().subList(0, nesting - 1));
+        return new SimpleEntry<InstanceIdentifier,T>(parentPath,parent.get());
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/ModificationMetadataTreeTest.java b/opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/ModificationMetadataTreeTest.java
new file mode 100644 (file)
index 0000000..7610a78
--- /dev/null
@@ -0,0 +1,255 @@
+package org.opendaylight.controller.md.sal.dom.store.impl;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.ID_QNAME;
+import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.INNER_LIST_QNAME;
+import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.NAME_QNAME;
+import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.OUTER_LIST_PATH;
+import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.OUTER_LIST_QNAME;
+import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.TEST_PATH;
+import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.TEST_QNAME;
+import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.VALUE_QNAME;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntry;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntryBuilder;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapNodeBuilder;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.dom.store.impl.tree.StoreMetadataNode;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+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.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+import com.google.common.base.Optional;
+import com.google.common.primitives.UnsignedLong;
+
+/**
+ *
+ * Schema structure of document is
+ *
+ * <pre>
+ * container root { 
+ *      list list-a {
+ *              key leaf-a;
+ *              leaf leaf-a;
+ *              choice choice-a {
+ *                      case one {
+ *                              leaf one;
+ *                      }
+ *                      case two-three {
+ *                              leaf two;
+ *                              leaf three;
+ *                      }
+ *              }
+ *              list list-b {
+ *                      key leaf-b;
+ *                      leaf leaf-b;
+ *              }
+ *      }
+ * }
+ * </pre>
+ *
+ */
+public class ModificationMetadataTreeTest {
+
+    private static final Short ONE_ID = 1;
+    private static final Short TWO_ID = 2;
+    private static final String TWO_ONE_NAME = "one";
+    private static final String TWO_TWO_NAME = "two";
+
+    private static final InstanceIdentifier OUTER_LIST_1_PATH = InstanceIdentifier.builder(OUTER_LIST_PATH)
+            .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, ONE_ID) //
+            .build();
+
+    private static final InstanceIdentifier OUTER_LIST_2_PATH = InstanceIdentifier.builder(OUTER_LIST_PATH)
+            .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
+            .build();
+
+    private static final InstanceIdentifier TWO_TWO_PATH = InstanceIdentifier.builder(OUTER_LIST_2_PATH)
+            .node(INNER_LIST_QNAME) //
+            .nodeWithKey(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME) //
+            .build();
+
+    private static final InstanceIdentifier TWO_TWO_VALUE_PATH = InstanceIdentifier.builder(TWO_TWO_PATH)
+            .node(VALUE_QNAME) //
+            .build();
+
+    private static final MapEntryNode BAR_NODE = mapEntryBuilder(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
+            .withChild(mapNodeBuilder(INNER_LIST_QNAME) //
+                    .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_ONE_NAME)) //
+                    .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME)) //
+                    .build()) //
+            .build();
+
+    private SchemaContext schemaContext;
+
+    @Before
+    public void prepare() {
+        schemaContext = TestModel.createTestContext();
+        assertNotNull("Schema context must not be null.", schemaContext);
+    }
+
+    /**
+     * Returns a test document
+     *
+     * <pre>
+     * test
+     *     outer-list
+     *          id 1
+     *     outer-list
+     *          id 2
+     *          inner-list
+     *                  name "one"
+     *          inner-list
+     *                  name "two"
+     *
+     * </pre>
+     *
+     * @return
+     */
+    public NormalizedNode<?, ?> createDocumentOne() {
+        return ImmutableContainerNodeBuilder
+                .create()
+                .withNodeIdentifier(new NodeIdentifier(schemaContext.getQName()))
+                .withChild(createTestContainer()).build();
+
+    }
+
+    private ContainerNode createTestContainer() {
+        return ImmutableContainerNodeBuilder
+                .create()
+                .withNodeIdentifier(new NodeIdentifier(TEST_QNAME))
+                .withChild(
+                        mapNodeBuilder(OUTER_LIST_QNAME)
+                                .withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID))
+                                .withChild(BAR_NODE).build()).build();
+    }
+
+    private StoreMetadataNode createDocumentOneMetadata() {
+        UnsignedLong version = UnsignedLong.valueOf(0);
+        return StoreMetadataNode.createRecursivelly(createDocumentOne(), version);
+    }
+
+    @Test
+    public void basicReadWrites() {
+        MutableDataTree modificationTree = MutableDataTree.from(
+                DataAndMetadataSnapshot.builder() //
+                        .setMetadataTree(createDocumentOneMetadata()) //
+                        .setSchemaContext(schemaContext) //
+                        .build(), new SchemaAwareApplyOperationRoot(schemaContext));
+        Optional<NormalizedNode<?, ?>> originalBarNode = modificationTree.read(OUTER_LIST_2_PATH);
+        assertTrue(originalBarNode.isPresent());
+        assertSame(BAR_NODE, originalBarNode.get());
+
+        // writes node to /outer-list/1/inner_list/two/value
+        modificationTree.write(TWO_TWO_VALUE_PATH, ImmutableNodes.leafNode(VALUE_QNAME, "test"));
+
+        // reads node to /outer-list/1/inner_list/two/value
+        // and checks if node is already present
+        Optional<NormalizedNode<?, ?>> barTwoCModified = modificationTree.read(TWO_TWO_VALUE_PATH);
+        assertTrue(barTwoCModified.isPresent());
+        assertEquals(ImmutableNodes.leafNode(VALUE_QNAME, "test"), barTwoCModified.get());
+
+        // delete node to /outer-list/1/inner_list/two/value
+        modificationTree.delete(TWO_TWO_VALUE_PATH);
+        Optional<NormalizedNode<?, ?>> barTwoCAfterDelete = modificationTree.read(TWO_TWO_VALUE_PATH);
+        assertFalse(barTwoCAfterDelete.isPresent());
+    }
+
+
+    public MutableDataTree createEmptyModificationTree() {
+        /**
+         * Creates empty Snapshot with associated schema context.
+         */
+        DataAndMetadataSnapshot emptySnapshot = DataAndMetadataSnapshot.createEmpty(schemaContext);
+
+        /**
+         *
+         * Creates Mutable Data Tree based on provided snapshot and schema
+         * context.
+         *
+         */
+        MutableDataTree modificationTree = MutableDataTree.from(emptySnapshot, new SchemaAwareApplyOperationRoot(
+                schemaContext));
+        return modificationTree;
+    }
+
+    @Test
+    public void createFromEmptyState() {
+
+        MutableDataTree modificationTree = createEmptyModificationTree();
+        /**
+         * Writes empty container node to /test
+         *
+         */
+        modificationTree.write(TEST_PATH, ImmutableNodes.containerNode(TEST_QNAME));
+
+        /**
+         * Writes empty list node to /test/outer-list
+         */
+        modificationTree.write(OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(OUTER_LIST_QNAME).build());
+
+        /**
+         * Reads list node from /test/outer-list
+         */
+        Optional<NormalizedNode<?, ?>> potentialOuterList = modificationTree.read(OUTER_LIST_PATH);
+        assertTrue(potentialOuterList.isPresent());
+
+        /**
+         * Reads container node from /test and verifies that it contains test
+         * node
+         */
+        Optional<NormalizedNode<?, ?>> potentialTest = modificationTree.read(TEST_PATH);
+        ContainerNode containerTest = assertPresentAndType(potentialTest, ContainerNode.class);
+
+        /**
+         *
+         * Gets list from returned snapshot of /test and verifies it contains
+         * outer-list
+         *
+         */
+        assertPresentAndType(containerTest.getChild(new NodeIdentifier(OUTER_LIST_QNAME)), MapNode.class);
+
+    }
+
+    @Test
+    public void writeSubtreeReadChildren() {
+        MutableDataTree modificationTree = createEmptyModificationTree();
+        modificationTree.write(TEST_PATH, createTestContainer());
+        Optional<NormalizedNode<?, ?>> potential = modificationTree.read(TWO_TWO_PATH);
+        MapEntryNode node = assertPresentAndType(potential, MapEntryNode.class);
+    }
+
+    @Test
+    public void writeSubtreeDeleteChildren() {
+        MutableDataTree modificationTree = createEmptyModificationTree();
+        modificationTree.write(TEST_PATH, createTestContainer());
+
+        // We verify data are present
+        Optional<NormalizedNode<?, ?>> potentialBeforeDelete = modificationTree.read(TWO_TWO_PATH);
+        MapEntryNode node = assertPresentAndType(potentialBeforeDelete, MapEntryNode.class);
+
+        modificationTree.delete(TWO_TWO_PATH);
+        Optional<NormalizedNode<?, ?>> potentialAfterDelete = modificationTree.read(TWO_TWO_PATH);
+        assertFalse(potentialAfterDelete.isPresent());
+
+    }
+
+    private static <T> T assertPresentAndType(final Optional<?> potential, final Class<T> type) {
+        assertNotNull(potential);
+        assertTrue(potential.isPresent());
+        assertTrue(type.isInstance(potential.get()));
+        return type.cast(potential.get());
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/TestModel.java b/opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/TestModel.java
new file mode 100644 (file)
index 0000000..cab7e57
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * 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.md.sal.dom.store.impl;
+
+import java.io.InputStream;
+import java.util.Collections;
+import java.util.Set;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
+
+public class TestModel {
+
+    public static final QName TEST_QNAME = QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test", "2014-03-13",
+            "test");
+    public static final QName OUTER_LIST_QNAME = QName.create(TEST_QNAME, "outer-list");
+    public static final QName INNER_LIST_QNAME = QName.create(TEST_QNAME, "inner-list");
+    public static final QName OUTER_CHOICE_QNAME = QName.create(TEST_QNAME, "outer-choice");
+    public static final QName ID_QNAME = QName.create(TEST_QNAME, "id");
+    public static final QName NAME_QNAME = QName.create(TEST_QNAME, "name");
+    public static final QName VALUE_QNAME = QName.create(TEST_QNAME, "value");
+    private static final String DATASTORE_TEST_YANG = "/odl-datastore-test.yang";
+
+    public static final InstanceIdentifier TEST_PATH = InstanceIdentifier.of(TEST_QNAME);
+    public static final InstanceIdentifier OUTER_LIST_PATH = InstanceIdentifier.builder(TEST_PATH).node(OUTER_LIST_QNAME).build();
+
+
+    public static final InputStream getDatastoreTestInputStream() {
+        return getInputStream(DATASTORE_TEST_YANG);
+    }
+
+    private static InputStream getInputStream(final String resourceName) {
+        return TestModel.class.getResourceAsStream(DATASTORE_TEST_YANG);
+    }
+
+    public static SchemaContext createTestContext() {
+        YangParserImpl parser = new YangParserImpl();
+        Set<Module> modules = parser.parseYangModelsFromStreams(Collections.singletonList(getDatastoreTestInputStream()));
+        return parser.resolveSchemaContext(modules);
+    }
+}
diff --git a/opendaylight/md-sal/sal-dom-broker/src/test/resources/odl-datastore-test.yang b/opendaylight/md-sal/sal-dom-broker/src/test/resources/odl-datastore-test.yang
new file mode 100644 (file)
index 0000000..17541fe
--- /dev/null
@@ -0,0 +1,42 @@
+module odl-datastore-test {
+    yang-version 1;
+    namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test";
+    prefix "store-test";
+    
+    revision "2014-03-13" {
+        description "Initial revision.";
+    }
+
+    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;
+                leaf name {
+                    type string;
+                }
+                leaf value {
+                    type string;
+                }
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlDst.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlDst.java
new file mode 100644 (file)
index 0000000..381de8e
--- /dev/null
@@ -0,0 +1,106 @@
+package org.opendaylight.controller.sal.match.extensible;
+
+import java.util.Arrays;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.opendaylight.controller.sal.utils.HexEncode;
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class DlDst extends MatchField<byte[]> {
+    private static final long serialVersionUID = 1L;
+    public static final String TYPE = "DL_DST";
+    private byte[] address;
+
+    /**
+     * Creates a Match field for the destination data layer address
+     *
+     * @param address
+     *            the data layer address. The constructor makes a copy of it
+     */
+    public DlDst(byte[] address) {
+        super(TYPE);
+        if (address != null) {
+            this.address = Arrays.copyOf(address, address.length);
+        }
+    }
+
+    // To satisfy JAXB
+    public DlDst() {
+        super(TYPE);
+    }
+
+    @Override
+    public byte[] getValue() {
+        return Arrays.copyOf(address, address.length);
+    }
+
+    @Override
+    @XmlElement(name = "value")
+    protected String getValueString() {
+        return HexEncode.bytesToHexStringFormat(address);
+    }
+
+    @Override
+    public byte[] getMask() {
+        return null;
+    }
+
+    @Override
+    protected String getMaskString() {
+        return null;
+    }
+
+    @Override
+    public boolean isValid() {
+        return address != null && address.length == NetUtils.MACAddrLengthInBytes;
+    }
+
+    @Override
+    public boolean hasReverse() {
+        return true;
+    }
+
+    @Override
+    public DlSrc getReverse() {
+        return new DlSrc(address);
+    }
+
+    @Override
+    public DlDst clone() {
+        return new DlDst(address);
+    }
+
+    @Override
+    public boolean isV6() {
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + Arrays.hashCode(address);
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof DlDst)) {
+            return false;
+        }
+        DlDst other = (DlDst) obj;
+        return Arrays.equals(address, other.address);
+    }
+}
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlSrc.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlSrc.java
new file mode 100644 (file)
index 0000000..962c4d3
--- /dev/null
@@ -0,0 +1,106 @@
+package org.opendaylight.controller.sal.match.extensible;
+
+import java.util.Arrays;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.opendaylight.controller.sal.utils.HexEncode;
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class DlSrc extends MatchField<byte[]> {
+    private static final long serialVersionUID = 1L;
+    public static final String TYPE = "DL_SRC";
+    private byte[] address;
+
+    /**
+     * Creates a Match field for the source datalayer address
+     *
+     * @param address
+     *            the datalayer address. The constructor makes a copy of it
+     */
+    public DlSrc(byte[] address) {
+        super(TYPE);
+        if (address != null) {
+            this.address = Arrays.copyOf(address, address.length);
+        }
+    }
+
+    // To satisfy JAXB
+    private DlSrc() {
+        super(TYPE);
+    }
+
+    @Override
+    public byte[] getValue() {
+        return Arrays.copyOf(address, address.length);
+    }
+
+    @Override
+    @XmlElement(name = "value")
+    protected String getValueString() {
+        return HexEncode.bytesToHexStringFormat(address);
+    }
+
+    @Override
+    public byte[] getMask() {
+        return null;
+    }
+
+    @Override
+    protected String getMaskString() {
+        return null;
+    }
+
+    @Override
+    public boolean isValid() {
+        return address != null && address.length == NetUtils.MACAddrLengthInBytes;
+    }
+
+    @Override
+    public boolean hasReverse() {
+        return true;
+    }
+
+    @Override
+    public DlDst getReverse() {
+        return new DlDst(address);
+    }
+
+    @Override
+    public DlSrc clone() {
+        return new DlSrc(address);
+    }
+
+    @Override
+    public boolean isV6() {
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + Arrays.hashCode(address);
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof DlSrc)) {
+            return false;
+        }
+        DlSrc other = (DlSrc) obj;
+        return Arrays.equals(address, other.address);
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlType.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlType.java
new file mode 100644 (file)
index 0000000..468703d
--- /dev/null
@@ -0,0 +1,105 @@
+package org.opendaylight.controller.sal.match.extensible;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.opendaylight.controller.sal.utils.EtherTypes;
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class DlType extends MatchField<Short> {
+    private static final long serialVersionUID = 1L;
+    public static final String TYPE = "DL_TYPE";
+    private short ethertype;
+
+    /**
+     * Creates a Match field for the data layer type
+     *
+     * @param address
+     *            the data layer type
+     */
+    public DlType(short ethertype) {
+        super(TYPE);
+        this.ethertype = ethertype;
+    }
+
+    // To satisfy JAXB
+    private DlType() {
+        super(TYPE);
+    }
+
+    @Override
+    public Short getValue() {
+        return ethertype;
+    }
+
+    @Override
+    @XmlElement(name = "value")
+    protected String getValueString() {
+        return String.format("0X%s", Integer.toHexString(NetUtils.getUnsignedShort(ethertype)));
+    }
+
+    @Override
+    public Short getMask() {
+        return null;
+    }
+
+    @Override
+    protected String getMaskString() {
+        return null;
+    }
+
+    @Override
+    public boolean isValid() {
+        return true;
+    }
+
+    @Override
+    public boolean hasReverse() {
+        return false;
+    }
+
+    @Override
+    public DlType getReverse() {
+        return this.clone();
+    }
+
+    @Override
+    public DlType clone() {
+        return new DlType(ethertype);
+    }
+
+    @Override
+    public boolean isV6() {
+        return this.ethertype == EtherTypes.IPv6.shortValue();
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ethertype;
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof DlType)) {
+            return false;
+        }
+        DlType other = (DlType) obj;
+        if (ethertype != other.ethertype) {
+            return false;
+        }
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlan.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlan.java
new file mode 100644 (file)
index 0000000..30657a9
--- /dev/null
@@ -0,0 +1,104 @@
+package org.opendaylight.controller.sal.match.extensible;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class DlVlan extends MatchField<Short> {
+    private static final long serialVersionUID = 1L;
+    public static final String TYPE = "DL_VLAN";
+    private static final short MAX = 4095;
+    private short vlan;
+
+    /**
+     * Creates a Match field for the data layer type
+     *
+     * @param address
+     *            the data layer type
+     */
+    public DlVlan(short vlan) {
+        super(TYPE);
+        this.vlan = vlan;
+    }
+
+    // To satisfy JAXB
+    private DlVlan() {
+        super(TYPE);
+    }
+
+    @Override
+    public Short getValue() {
+        return vlan;
+    }
+
+    @Override
+    @XmlElement(name = "value")
+    protected String getValueString() {
+        return String.valueOf(vlan);
+    }
+
+    @Override
+    public Short getMask() {
+        return null;
+    }
+
+    @Override
+    protected String getMaskString() {
+        return null;
+    }
+
+    @Override
+    public boolean isValid() {
+        return vlan >= 0 && vlan <= MAX;
+    }
+
+    @Override
+    public DlVlan getReverse() {
+        return this.clone();
+    }
+
+    @Override
+    public boolean hasReverse() {
+        return false;
+    }
+
+    @Override
+    public DlVlan clone() {
+        return new DlVlan(vlan);
+    }
+
+    @Override
+    public boolean isV6() {
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + vlan;
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof DlVlan)) {
+            return false;
+        }
+        DlVlan other = (DlVlan) obj;
+        if (vlan != other.vlan) {
+            return false;
+        }
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlanPriority.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlanPriority.java
new file mode 100644 (file)
index 0000000..58dd563
--- /dev/null
@@ -0,0 +1,105 @@
+package org.opendaylight.controller.sal.match.extensible;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class DlVlanPriority extends MatchField<Byte> {
+    private static final long serialVersionUID = 1L;
+    public static final String TYPE = "DL_VLAN_PR";
+    private static final byte MAX = 7;
+    private byte vlanPriority;
+
+    /**
+     * Creates a Match field for the data layer type
+     *
+     * @param address
+     *            the data layer type
+     */
+    public DlVlanPriority(byte vlanPriority) {
+        super(TYPE);
+        this.vlanPriority = vlanPriority;
+    }
+
+    // To satisfy JAXB
+    private DlVlanPriority() {
+        super(TYPE);
+    }
+
+    @Override
+    public Byte getValue() {
+        return vlanPriority;
+    }
+
+    @Override
+    @XmlElement(name = "mask")
+    protected String getValueString() {
+        return String.format("0X%s", Integer.toHexString(NetUtils.getUnsignedByte(vlanPriority)));
+    }
+
+    @Override
+    public Byte getMask() {
+        return null;
+    }
+
+    @Override
+    protected String getMaskString() {
+        return null;
+    }
+
+    @Override
+    public boolean isValid() {
+        return vlanPriority >= 0 && vlanPriority <= MAX;
+    }
+
+    @Override
+    public boolean hasReverse() {
+        return false;
+    }
+
+    @Override
+    public DlVlanPriority getReverse() {
+        return this.clone();
+    }
+
+    @Override
+    public DlVlanPriority clone() {
+        return new DlVlanPriority(vlanPriority);
+    }
+
+    @Override
+    public boolean isV6() {
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + vlanPriority;
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof DlVlanPriority)) {
+            return false;
+        }
+        DlVlanPriority other = (DlVlanPriority) obj;
+        if (vlanPriority != other.vlanPriority) {
+            return false;
+        }
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/InPort.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/InPort.java
new file mode 100644 (file)
index 0000000..2b5eb5b
--- /dev/null
@@ -0,0 +1,108 @@
+package org.opendaylight.controller.sal.match.extensible;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.opendaylight.controller.sal.core.NodeConnector;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class InPort extends MatchField<NodeConnector> {
+    private static final long serialVersionUID = 1L;
+    public static final String TYPE = "IN_PORT";
+    private NodeConnector port;
+
+    /**
+     * Creates a Match field for the input port
+     *
+     * @param port
+     *            the input port
+     */
+    public InPort(NodeConnector port) {
+        super(TYPE);
+        this.port = port;
+    }
+
+    // To satisfy JAXB
+    private InPort() {
+        super(TYPE);
+    }
+
+    @Override
+    public NodeConnector getValue() {
+        return port;
+    }
+
+    @Override
+    @XmlElement(name = "value")
+    protected String getValueString() {
+        return port.toString();
+    }
+
+    @Override
+    public NodeConnector getMask() {
+        return null;
+    }
+
+    @Override
+    protected String getMaskString() {
+        return null;
+    }
+
+    @Override
+    public boolean isValid() {
+        return true;
+    }
+
+    @Override
+    public boolean hasReverse() {
+        return false;
+    }
+
+    @Override
+    public InPort getReverse() {
+        return this.clone();
+    }
+
+    @Override
+    public InPort clone() {
+        return new InPort(port);
+    }
+
+    @Override
+    public boolean isV6() {
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((port == null) ? 0 : port.hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof InPort)) {
+            return false;
+        }
+        InPort other = (InPort) obj;
+        if (port == null) {
+            if (other.port != null) {
+                return false;
+            }
+        } else if (!port.equals(other.port)) {
+            return false;
+        }
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/Match.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/Match.java
new file mode 100644 (file)
index 0000000..b065444
--- /dev/null
@@ -0,0 +1,422 @@
+
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.sal.match.extensible;
+
+import java.io.Serializable;
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+/**
+ * Represents the generic match criteria for a network frame/packet/message
+ * It contains a collection of individual field match
+ *
+ */
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class Match implements Cloneable, Serializable {
+        private static final long serialVersionUID = 1L;
+    private Map<String, MatchField<?>> fields;
+
+    public Match() {
+        fields = new HashMap<String, MatchField<?>>();
+    }
+
+    public Match(Match match) {
+        fields = new HashMap<String, MatchField<?>>(match.fields);
+    }
+
+    /**
+     * Generic setter for frame/packet/message's header field against which to match
+     *
+     * @param field the fields parameters as MAtchField object
+     */
+    public void setField(MatchField<?> field) {
+        if (field.isValid()) {
+            fields.put(field.getType(), field);
+        }
+    }
+
+    /**
+     * Generic method to clear a field from the match
+     */
+    public void clearField(String type) {
+        fields.remove(type);
+    }
+
+    /**
+     * Generic getter for fields against which the match is programmed
+     *
+     * @param type  frame/packet/message's header field type
+     * @return
+     */
+    public MatchField<?> getField(String type) {
+        return fields.get(type);
+    }
+
+    /**
+     * Returns the list of MatchType fields the match is set for
+     *
+     * @return List of individual MatchType fields.
+     */
+    public List<String> getMatchesList() {
+        return new ArrayList<String>(fields.keySet());
+    }
+
+    /**
+     * Returns the list of MatchFields the match is set for
+     *
+     * @return List of individual MatchField values.
+     */
+    @XmlElement(name="matchField")
+    public List<MatchField<?>> getMatchFields() {
+        return new ArrayList<MatchField<?>>(fields.values());
+    }
+
+    /**
+     * Returns whether this match is for an IPv6 flow
+     */
+    public boolean isIPv6() {
+        if (isPresent(DlType.TYPE)) {
+            for (MatchField<?> field : fields.values()) {
+                if (!field.isV6()) {
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Returns whether this match is for an IPv4 flow
+     */
+    public boolean isIPv4() {
+        return !isIPv6();
+    }
+
+    /**
+     * Returns whether for the specified field type the match is to be considered "any"
+     * Equivalent to say this match does not care about the value of the specified field
+     *
+     * @param type
+     * @return
+     */
+    public boolean isAny(String type) {
+        return !fields.containsKey(type);
+    }
+
+    /**
+     * Returns whether a match for the specified field type is configured
+     *
+     * @param type
+     * @return
+     */
+    public boolean isPresent(String type) {
+        return (fields.get(type) != null);
+    }
+
+    public boolean isEmpty() {
+        return fields.isEmpty();
+    }
+
+    @Override
+    public Match clone() {
+        Match cloned = null;
+        try {
+            cloned = (Match) super.clone();
+            cloned.fields = new HashMap<String, MatchField<?>>();
+            for (Entry<String, MatchField<?>> entry : this.fields.entrySet()) {
+                cloned.fields.put(entry.getKey(), entry.getValue().clone());
+            }
+        } catch (CloneNotSupportedException e) {
+            throw new RuntimeException(e);
+        }
+        return cloned;
+    }
+
+    /**
+     * Returns a reversed version of this match
+     * For example, in the reversed version the network source and destination
+     * addresses will be exchanged. Non symmetric match field will not be
+     * copied over into the reversed match version, like input port.
+     *
+     * @return
+     */
+    public Match reverse() {
+        Match reverse = new Match();
+        for (MatchField<?> field : fields.values()) {
+            reverse.setField(field.hasReverse()? field.getReverse() : field.clone());
+        }
+
+        // Reset asymmetric fields
+        reverse.clearField(InPort.TYPE);
+
+        return reverse;
+    }
+
+    /**
+     * Check whether the current match conflicts with the passed filter match
+     * This match conflicts with the filter if for at least a MatchType defined
+     * in the filter match, the respective MatchFields differ or are not
+     * compatible
+     *
+     * In other words the function returns true if the set of packets described
+     * by one match and the set of packets described by the other match are
+     * disjoint. Equivalently, if the intersection of the two sets of packets
+     * described by the two org.opendaylight.controller.sal.matches is an empty.
+     *
+     * For example, Let's suppose the filter has the following MatchFields:
+     * DL_TYPE = 0x800
+     * NW_DST = 172.20.30.110/24
+     *
+     * while this match has the following MatchFields:
+     * DL_TYPE = 0x800
+     * NW_DST = 172.20.30.45/24
+     * TP_DST = 80
+     *
+     * Then the function would return false as the two Match are not
+     * conflicting.
+     *
+     * Note: the mask value is taken into account only for MatchType.NW_SRC and
+     * MatchType.NW_DST
+     *
+     * @param match
+     *            the Match describing the filter
+     * @return true if the set of packets described by one match and the set of
+     *         packets described by the other match are disjoint, false
+     *         otherwise
+     */
+    public boolean conflictWithFilter(Match filter) {
+        return !this.intersetcs(filter);
+    }
+
+    /**
+     * Merge the current Match fields with the fields of the filter Match. A
+     * check is first run to see if this Match is compatible with the filter
+     * Match. If it is not, the merge is not attempted.
+     *
+     * The result is the match object representing the intersection of the set
+     * of packets described by this match with the set of packets described by
+     * the filter match. If the intersection of the two sets is empty, the
+     * return match will be null.
+     *
+     * @param filter
+     *            the match with which attempting the merge
+     * @return a new Match object describing the set of packets represented by
+     *         the intersection of this and the filter org.opendaylight.controller.sal.matches. null if the
+     *         intersection is empty.
+     */
+    public Match mergeWithFilter(Match filter) {
+        return this.getIntersection(filter);
+    }
+
+    /**
+     * Return the match representing the intersection of the set of packets
+     * described by this match with the set of packets described by the other
+     * match. Such as m.getIntersection(m) == m, m.getIntersection(u) == m and
+     * m.getIntersection(o) == o where u is an empty match (universal set, all
+     * packets) and o is the null match (empty set).
+     *
+     * @param other
+     *            the match with which computing the intersection
+     * @return a new Match object representing the intersection of the set of
+     *         packets described by this match with the set of packets described
+     *         by the other match. null when the intersection is the empty set.
+     */
+    public Match getIntersection(Match other) {
+        // If no intersection, return the empty set
+        if (!this.intersetcs(other)) {
+            return null;
+        }
+        // Check if any of the two is the universal match
+        if (this.isEmpty()) {
+            return other.clone();
+        }
+        if (other.isEmpty()) {
+            return this.clone();
+        }
+        // Get all the match types for both filters
+        Set<String> allTypes = new HashSet<String>(this.fields.keySet());
+        allTypes.addAll(new HashSet<String>(other.fields.keySet()));
+        // Derive the intersection
+        Match intersection = new Match();
+        for (String type : allTypes) {
+            if (this.isAny(type) && other.isAny(type)) {
+                continue;
+            }
+            if (this.isAny(type)) {
+                intersection.setField(other.getField(type).clone());
+                continue;
+            } else if (other.isAny(type)) {
+                intersection.setField(this.getField(type).clone());
+                continue;
+            }
+            // Either they are equal or it is about IP address
+            switch (type) {
+            // When it is about IP address, take the wider prefix address
+            // between the twos
+            case NwSrc.TYPE:
+            case NwDst.TYPE:
+                MatchField<?> thisField = this.getField(type);
+                MatchField<?> otherField = other.getField(type);
+                InetAddress thisAddress = (InetAddress) thisField.getValue();
+                InetAddress otherAddress = (InetAddress) otherField.getValue();
+                InetAddress thisMask = (InetAddress) thisField.getMask();
+                InetAddress otherMask = (InetAddress) otherField.getMask();
+
+                int thisMaskLen = (thisMask == null) ? ((thisAddress instanceof Inet4Address) ? 32 : 128) : NetUtils
+                        .getSubnetMaskLength(thisMask);
+                int otherMaskLen = (otherMask == null) ? ((otherAddress instanceof Inet4Address) ? 32 : 128) : NetUtils
+                        .getSubnetMaskLength(otherMask);
+
+                InetAddress subnetPrefix = null;
+                InetAddress subnetMask = null;
+                if (thisMaskLen < otherMaskLen) {
+                    subnetPrefix = NetUtils.getSubnetPrefix(otherAddress, otherMaskLen);
+                    subnetMask = otherMask;
+                } else {
+                    subnetPrefix = NetUtils.getSubnetPrefix(thisAddress, thisMaskLen);
+                    subnetMask = thisMask;
+                }
+                MatchField<?> field = (type.equals(NwSrc.TYPE)) ? new NwSrc(subnetPrefix, subnetMask) : new NwDst(
+                        subnetPrefix, subnetMask);
+                intersection.setField(field);
+                break;
+            default:
+                // this and other match field are equal for this type, pick this
+                // match field
+                intersection.setField(this.getField(type).clone());
+            }
+        }
+        return intersection;
+    }
+
+    /**
+     * Checks whether the intersection of the set of packets described by this
+     * match with the set of packets described by the other match is non empty
+     *
+     * For example, if this match is: DL_SRC = 00:cc:bb:aa:11:22
+     *
+     * and the other match is: DL_TYPE = 0x800 NW_SRC = 1.2.3.4
+     *
+     * then their respective matching packets set intersection is non empty:
+     * DL_SRC = 00:cc:bb:aa:11:22 DL_TYPE = 0x800 NW_SRC = 1.2.3.4
+     *
+     * @param other
+     *            the other match with which testing the intersection
+     * @return true if the intersection of the respective matching packets sets
+     *         is non empty
+     */
+    public boolean intersetcs(Match other) {
+        // No intersection with the empty set
+        if (other == null) {
+            return false;
+        }
+        // Always intersection with the universal set
+        if (this.isEmpty() || other.isEmpty()) {
+            return true;
+        }
+
+        // Get all the match types for both filters
+        Set<String> allTypes = new HashSet<String>(this.fields.keySet());
+        allTypes.addAll(new HashSet<String>(other.fields.keySet()));
+
+        // Iterate through all the match types defined in the two filters
+        for (String type : allTypes) {
+            if (this.isAny(type) || other.isAny(type)) {
+                continue;
+            }
+
+            MatchField<?> thisField = this.getField(type);
+            MatchField<?> otherField = other.getField(type);
+
+            switch (type) {
+            case DlSrc.TYPE:
+            case DlDst.TYPE:
+                if (!Arrays.equals((byte[]) thisField.getValue(), (byte[]) otherField.getValue())) {
+                    return false;
+                }
+                break;
+            case NwSrc.TYPE:
+            case NwDst.TYPE:
+                InetAddress thisAddress = (InetAddress) thisField.getValue();
+                InetAddress otherAddress = (InetAddress) otherField.getValue();
+                // Validity check
+                if (thisAddress instanceof Inet4Address && otherAddress instanceof Inet6Address
+                        || thisAddress instanceof Inet6Address && otherAddress instanceof Inet4Address) {
+                    return false;
+                }
+                InetAddress thisMask = (InetAddress) thisField.getMask();
+                InetAddress otherMask = (InetAddress) otherField.getMask();
+                if (NetUtils.inetAddressConflict(thisAddress, otherAddress, thisMask, otherMask)
+                        && NetUtils.inetAddressConflict(otherAddress, thisAddress, otherMask, thisMask)) {
+                    return false;
+                }
+                break;
+            default:
+                if (!thisField.getValue().equals(otherField.getValue())) {
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((fields == null) ? 0 : fields.hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof Match)) {
+            return false;
+        }
+        Match other = (Match) obj;
+        if (fields == null) {
+            if (other.fields != null) {
+                return false;
+            }
+        } else if (!fields.equals(other.fields)) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        return "Match[" + fields.values() + "]";
+    }
+}
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/MatchField.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/MatchField.java
new file mode 100644 (file)
index 0000000..e7a5de3
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.sal.match.extensible;
+
+import java.io.Serializable;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * Represents the generic matching field object
+ */
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public abstract class MatchField<T> implements Cloneable, Serializable {
+    private static final long serialVersionUID = 1L;
+    private String type;
+
+    // To satisfy JAXB
+    @SuppressWarnings("unused")
+    private MatchField() {
+    }
+
+    public MatchField(String type) {
+        this.type = type;
+    }
+
+    @XmlElement(name = "type")
+    public String getType() {
+        return type;
+    }
+
+    /**
+     * Returns the value set for this match field
+     *
+     * @return
+     */
+    public abstract T getValue();
+
+    @XmlElement(name = "value")
+    protected abstract String getValueString();
+
+    /**
+     * Returns the mask value set for this field match A null mask means this is
+     * a full match
+     *
+     * @return
+     */
+    public abstract T getMask();
+
+    @XmlElement(name = "mask")
+    protected abstract String getMaskString();
+
+    /**
+     * Returns whether the field match configuration is valid or not
+     *
+     * @return true if valid, false otherwise
+     */
+    public abstract boolean isValid();
+
+    public abstract boolean hasReverse();
+
+    /**
+     * Returns the reverse match field. For example for a MatchField matching on
+     * source ip 1.1.1.1 it will return a MatchField matching on destination IP
+     * 1.1.1.1. For not reversable MatchField, a copy of this MatchField will be
+     * returned
+     *
+     * @return the correspondent reverse MatchField object or a copy of this
+     *         object if the field is not reversable
+     */
+    public abstract MatchField<T> getReverse();
+
+    /**
+     * Returns whether the match field is congruent with IPv6 frames
+     *
+     * @return true if congruent with IPv6 frames
+     */
+    public abstract boolean isV6();
+
+    @Override
+    public abstract MatchField<T> clone();
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((type == null) ? 0 : type.hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof MatchField)) {
+            return false;
+        }
+        MatchField<?> other = (MatchField<?>) obj;
+        if (type == null) {
+            if (other.type != null) {
+                return false;
+            }
+        } else if (!type.equals(other.type)) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        return (getMask() == null) ? String.format("%s(%s)", getType(), getValueString()) :
+            String.format("%s(%s,%s)", getType(), getValueString(), getMaskString());
+    }
+
+}
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwDst.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwDst.java
new file mode 100644 (file)
index 0000000..42b6ba6
--- /dev/null
@@ -0,0 +1,131 @@
+package org.opendaylight.controller.sal.match.extensible;
+
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class NwDst extends MatchField<InetAddress> {
+    private static final long serialVersionUID = 1L;
+    public static final String TYPE = "NW_DST";
+    private InetAddress address;
+    private InetAddress mask;
+
+    /**
+     * Creates a Match field for the network destination address
+     *
+     * @param address
+     *            the network address
+     * @param mask
+     *            the network mask
+     */
+    public NwDst(InetAddress address, InetAddress mask) {
+        super(TYPE);
+        this.address = address;
+        this.mask = mask;
+    }
+
+    // To satisfy JAXB
+    private NwDst() {
+        super(TYPE);
+    }
+
+    public NwDst(InetAddress address) {
+        super(TYPE);
+        this.address = address;
+        this.mask = null;
+    }
+
+    @Override
+    public InetAddress getValue() {
+        return address;
+    }
+
+    @Override
+    @XmlElement(name = "value")
+    protected String getValueString() {
+        return address.getHostAddress();
+    }
+
+    @Override
+    public InetAddress getMask() {
+        return mask;
+    }
+
+    @Override
+    @XmlElement(name = "mask")
+    protected String getMaskString() {
+        return (mask == null) ? "null" : mask.getHostAddress();
+    }
+
+    @Override
+    public boolean isValid() {
+        if (address != null) {
+            if (mask != null) {
+                return address instanceof Inet4Address && mask instanceof Inet4Address
+                        || address instanceof Inet6Address && mask instanceof Inet6Address;
+            }
+            return true;
+        }
+        return false;
+    }
+
+    @Override
+    public boolean hasReverse() {
+        return true;
+    }
+
+    @Override
+    public NwSrc getReverse() {
+        return new NwSrc(address, mask);
+    }
+
+    @Override
+    public NwDst clone() {
+        return new NwDst(address, mask);
+    }
+
+    @Override
+    public boolean isV6() {
+        return address instanceof Inet6Address;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((address == null) ? 0 : address.hashCode());
+        result = prime * result + ((mask == null) ? 0 : mask.hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof NwDst)) {
+            return false;
+        }
+        NwDst other = (NwDst) obj;
+        // Equality to be checked against prefix addresses
+        int thisMaskLen = (this.mask == null) ? ((this.address instanceof Inet4Address) ? 32 : 128) : NetUtils
+                .getSubnetMaskLength(this.mask);
+        int otherMaskLen = (other.mask == null) ? ((other.address instanceof Inet4Address) ? 32 : 128) : NetUtils
+                .getSubnetMaskLength(other.mask);
+
+        return NetUtils.getSubnetPrefix(address, thisMaskLen).equals(
+                NetUtils.getSubnetPrefix(other.address, otherMaskLen));
+    }
+}
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwProtocol.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwProtocol.java
new file mode 100644 (file)
index 0000000..c5b5315
--- /dev/null
@@ -0,0 +1,116 @@
+package org.opendaylight.controller.sal.match.extensible;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class NwProtocol extends MatchField<Byte> {
+    private static final long serialVersionUID = 1L;
+    public static final String TYPE = "NW_PROTO";
+    private static final short MAX = 255;
+    private byte protocol;
+
+    /**
+     * Creates a Match field for the network protocol
+     *
+     * @param protocol
+     *            the protocol number
+     */
+    public NwProtocol(byte protocol) {
+        super(TYPE);
+        this.protocol = protocol;
+    }
+
+    public NwProtocol(int protocol) {
+        super(TYPE);
+        this.protocol = (byte) protocol;
+    }
+
+    public NwProtocol(short protocol) {
+        super(TYPE);
+        this.protocol = (byte) protocol;
+    }
+
+    // To satisfy JAXB
+    private NwProtocol() {
+        super(TYPE);
+    }
+
+    @Override
+    public Byte getValue() {
+        return protocol;
+    }
+
+    @Override
+    @XmlElement(name = "value")
+    protected String getValueString() {
+        return String.format("0X%s", Integer.toHexString(NetUtils.getUnsignedByte(protocol)));
+    }
+
+    @Override
+    public Byte getMask() {
+        return null;
+    }
+
+    @Override
+    protected String getMaskString() {
+        return null;
+    }
+
+    @Override
+    public boolean isValid() {
+        int intProtocol = NetUtils.getUnsignedByte(protocol);
+        return intProtocol >= 0 && intProtocol <= MAX;
+    }
+
+    @Override
+    public boolean hasReverse() {
+        return false;
+    }
+
+    @Override
+    public NwProtocol getReverse() {
+        return this.clone();
+    }
+
+    @Override
+    public NwProtocol clone() {
+        return new NwProtocol(protocol);
+    }
+
+    @Override
+    public boolean isV6() {
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + protocol;
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof NwProtocol)) {
+            return false;
+        }
+        NwProtocol other = (NwProtocol) obj;
+        if (protocol != other.protocol) {
+            return false;
+        }
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwSrc.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwSrc.java
new file mode 100644 (file)
index 0000000..4da43f5
--- /dev/null
@@ -0,0 +1,131 @@
+package org.opendaylight.controller.sal.match.extensible;
+
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class NwSrc extends MatchField<InetAddress> {
+    private static final long serialVersionUID = 1L;
+    public static final String TYPE = "NW_SRC";
+    private InetAddress address;
+    private InetAddress mask;
+
+    /**
+     * Creates a Match field for the network source address
+     *
+     * @param address
+     *            the network address
+     * @param mask
+     *            the network mask
+     */
+    public NwSrc(InetAddress address, InetAddress mask) {
+        super(TYPE);
+        this.address = address;
+        this.mask = mask;
+    }
+
+    // To satisfy JAXB
+    private NwSrc() {
+        super(TYPE);
+    }
+
+    public NwSrc(InetAddress address) {
+        super(TYPE);
+        this.address = address;
+        this.mask = null;
+    }
+
+    @Override
+    public InetAddress getValue() {
+        return address;
+    }
+
+    @Override
+    @XmlElement(name = "value")
+    protected String getValueString() {
+        return address.toString();
+    }
+
+    @Override
+    public InetAddress getMask() {
+        return mask;
+    }
+
+    @Override
+    @XmlElement(name = "mask")
+    protected String getMaskString() {
+        return mask == null ? "null" : mask.toString();
+    }
+
+    @Override
+    public boolean isValid() {
+        if (address != null) {
+            if (mask != null) {
+                return address instanceof Inet4Address && mask instanceof Inet4Address
+                        || address instanceof Inet6Address && mask instanceof Inet6Address;
+            }
+            return true;
+        }
+        return false;
+    }
+
+    @Override
+    public boolean hasReverse() {
+        return true;
+    }
+
+    @Override
+    public NwDst getReverse() {
+        return new NwDst(address, mask);
+    }
+
+    @Override
+    public NwSrc clone() {
+        return new NwSrc(address, mask);
+    }
+
+    @Override
+    public boolean isV6() {
+        return address instanceof Inet6Address;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((address == null) ? 0 : address.hashCode());
+        result = prime * result + ((mask == null) ? 0 : mask.hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof NwSrc)) {
+            return false;
+        }
+        NwSrc other = (NwSrc) obj;
+        // Equality to be checked against prefix addresses
+        int thisMaskLen = (this.mask == null) ? ((this.address instanceof Inet4Address) ? 32 : 128) : NetUtils
+                .getSubnetMaskLength(this.mask);
+        int otherMaskLen = (other.mask == null) ? ((other.address instanceof Inet4Address) ? 32 : 128) : NetUtils
+                .getSubnetMaskLength(other.mask);
+
+        return NetUtils.getSubnetPrefix(address, thisMaskLen).equals(
+                NetUtils.getSubnetPrefix(other.address, otherMaskLen));
+    }
+}
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwTos.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwTos.java
new file mode 100644 (file)
index 0000000..ba5b562
--- /dev/null
@@ -0,0 +1,115 @@
+package org.opendaylight.controller.sal.match.extensible;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class NwTos extends MatchField<Byte> {
+    private static final long serialVersionUID = 1L;
+    public static final String TYPE = "NW_TOS";
+    private static final short MAX = 63;
+    private byte tos;
+
+    /**
+     * Creates a Match field for the network TOS
+     *
+     * @param address
+     *            the network TOS
+     */
+    public NwTos(byte tos) {
+        super(TYPE);
+        this.tos = tos;
+    }
+
+    public NwTos(int tos) {
+        super(TYPE);
+        this.tos = (byte) tos;
+    }
+
+    public NwTos(short tos) {
+        super(TYPE);
+        this.tos = (byte) tos;
+    }
+
+    // To satisfy JAXB
+    private NwTos() {
+        super(TYPE);
+    }
+
+    @Override
+    public Byte getValue() {
+        return tos;
+    }
+
+    @Override
+    @XmlElement(name = "value")
+    protected String getValueString() {
+        return String.format("0X%s", Integer.toHexString(NetUtils.getUnsignedByte(tos)));
+    }
+
+    @Override
+    public Byte getMask() {
+        return null;
+    }
+
+    @Override
+    protected String getMaskString() {
+        return null;
+    }
+
+    @Override
+    public boolean isValid() {
+        return tos >= 0 && tos <= MAX;
+    }
+
+    @Override
+    public boolean hasReverse() {
+        return false;
+    }
+
+    @Override
+    public NwTos getReverse() {
+        return this.clone();
+    }
+
+    @Override
+    public NwTos clone() {
+        return new NwTos(tos);
+    }
+
+    @Override
+    public boolean isV6() {
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + tos;
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (!(obj instanceof NwTos)) {
+            return false;
+        }
+        NwTos other = (NwTos) obj;
+        if (tos != other.tos) {
+            return false;
+        }
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpDst.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpDst.java
new file mode 100644 (file)
index 0000000..022db4c
--- /dev/null
@@ -0,0 +1,104 @@
+package org.opendaylight.controller.sal.match.extensible;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class TpDst extends MatchField<Short> {
+    private static final long serialVersionUID = 1L;
+    public static final String TYPE = "TP_DST";
+    private short port;
+
+    /**
+     * Creates a Match field for the transport destination port
+     *
+     * @param port
+     *            the transport port
+     */
+    public TpDst(short port) {
+        super(TYPE);
+        this.port = port;
+    }
+
+    // To satisfy JAXB
+    private TpDst() {
+        super(TYPE);
+    }
+
+    @Override
+    public Short getValue() {
+        return port;
+    }
+
+    @Override
+    @XmlElement(name = "value")
+    protected String getValueString() {
+        return String.valueOf(NetUtils.getUnsignedShort(port));
+    }
+
+    @Override
+    public Short getMask() {
+        return null;
+    }
+
+    @Override
+    protected String getMaskString() {
+        return null;
+    }
+
+    @Override
+    public boolean isValid() {
+        return true;
+    }
+
+    @Override
+    public TpSrc getReverse() {
+        return new TpSrc(port);
+    }
+
+    @Override
+    public boolean hasReverse() {
+        return true;
+    }
+
+    @Override
+    public TpDst clone() {
+        return new TpDst(port);
+    }
+
+    @Override
+    public boolean isV6() {
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = super.hashCode();
+        result = prime * result + port;
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (!super.equals(obj)) {
+            return false;
+        }
+        if (!(obj instanceof TpDst)) {
+            return false;
+        }
+        TpDst other = (TpDst) obj;
+        if (port != other.port) {
+            return false;
+        }
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpSrc.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpSrc.java
new file mode 100644 (file)
index 0000000..1c93d1e
--- /dev/null
@@ -0,0 +1,104 @@
+package org.opendaylight.controller.sal.match.extensible;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+public class TpSrc extends MatchField<Short> {
+    private static final long serialVersionUID = 1L;
+    public static final String TYPE = "TP_SRC";
+    private short port;
+
+    /**
+     * Creates a Match field for the Transport source port
+     *
+     * @param port
+     *            the transport port
+     */
+    public TpSrc(short port) {
+        super(TYPE);
+        this.port = port;
+    }
+
+    // To satisfy JAXB
+    private TpSrc() {
+        super(TYPE);
+    }
+
+    @Override
+    public Short getValue() {
+        return port;
+    }
+
+    @Override
+    @XmlElement(name = "value")
+    protected String getValueString() {
+        return String.valueOf(NetUtils.getUnsignedShort(port));
+    }
+
+    @Override
+    public Short getMask() {
+        return null;
+    }
+
+    @Override
+    protected String getMaskString() {
+        return null;
+    }
+
+    @Override
+    public boolean isValid() {
+        return true;
+    }
+
+    @Override
+    public boolean hasReverse() {
+        return true;
+    }
+
+    @Override
+    public TpDst getReverse() {
+        return new TpDst(port);
+    }
+
+    @Override
+    public TpSrc clone() {
+        return new TpSrc(port);
+    }
+
+    @Override
+    public boolean isV6() {
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = super.hashCode();
+        result = prime * result + port;
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (!super.equals(obj)) {
+            return false;
+        }
+        if (!(obj instanceof TpSrc)) {
+            return false;
+        }
+        TpSrc other = (TpSrc) obj;
+        if (port != other.port) {
+            return false;
+        }
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchExtensibleTest.java b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchExtensibleTest.java
new file mode 100644 (file)
index 0000000..0f49f42
--- /dev/null
@@ -0,0 +1,589 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.sal.match;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.sal.core.Node;
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.match.extensible.DlDst;
+import org.opendaylight.controller.sal.match.extensible.DlSrc;
+import org.opendaylight.controller.sal.match.extensible.DlType;
+import org.opendaylight.controller.sal.match.extensible.DlVlan;
+import org.opendaylight.controller.sal.match.extensible.DlVlanPriority;
+import org.opendaylight.controller.sal.match.extensible.InPort;
+import org.opendaylight.controller.sal.match.extensible.Match;
+import org.opendaylight.controller.sal.match.extensible.MatchField;
+import org.opendaylight.controller.sal.match.extensible.NwDst;
+import org.opendaylight.controller.sal.match.extensible.NwProtocol;
+import org.opendaylight.controller.sal.match.extensible.NwSrc;
+import org.opendaylight.controller.sal.match.extensible.NwTos;
+import org.opendaylight.controller.sal.match.extensible.TpDst;
+import org.opendaylight.controller.sal.match.extensible.TpSrc;
+import org.opendaylight.controller.sal.utils.EtherTypes;
+import org.opendaylight.controller.sal.utils.IPProtocols;
+import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
+import org.opendaylight.controller.sal.utils.NodeCreator;
+
+public class MatchExtensibleTest {
+    @Test
+    public void testMatchCreation() {
+        Node node = NodeCreator.createOFNode(7L);
+        NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 6, node);
+        MatchField<?> field = new InPort(port);
+
+        Assert.assertTrue(field != null);
+        Assert.assertEquals(field.getType(), InPort.TYPE);
+        Assert.assertEquals(field.getValue(), port);
+        Assert.assertTrue(field.isValid());
+
+
+        byte mac[] = { (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 11, (byte) 22 };
+        field = null;
+        field = new DlSrc(mac);
+        Assert.assertNotNull(field.getValue());
+
+        field = null;
+        field = new NwTos((byte) 0x22);
+        Assert.assertNotNull(field.getValue());
+    }
+
+    @Test
+    public void testMatchSetGet() {
+        Match x = new Match();
+        short val = 2346;
+        NodeConnector inPort = NodeConnectorCreator.createOFNodeConnector(val, NodeCreator.createOFNode(1L));
+        x.setField(new InPort(inPort));
+        Assert.assertEquals(x.getField(InPort.TYPE).getValue(), inPort);
+        Assert.assertTrue((Short) ((NodeConnector) x.getField(InPort.TYPE).getValue()).getID() == val);
+    }
+
+    @Test
+    public void testMatchSetGetMAC() {
+        Match x = new Match();
+        byte mac[] = { (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 11, (byte) 22 };
+        byte mac2[] = { (byte) 0xaa, (byte) 0xbb, 0, 0, 0, (byte) 0xbb };
+
+        x.setField(new DlSrc(mac));
+        x.setField(new DlDst(mac2));
+        Assert.assertArrayEquals(mac, (byte[]) x.getField(DlSrc.TYPE).getValue());
+        Assert.assertFalse(Arrays.equals((byte[]) x.getField(DlSrc.TYPE).getValue(), (byte[]) x.getField(DlDst.TYPE)
+                .getValue()));
+
+        x.setField(new DlDst(mac.clone()));
+        Assert.assertArrayEquals((byte[]) x.getField(DlSrc.TYPE).getValue(), (byte[]) x.getField(DlDst.TYPE).getValue());
+    }
+
+    @Test
+    public void testMatchSetGetNWAddr() throws UnknownHostException {
+        Match x = new Match();
+        String ip = "172.20.231.23";
+        InetAddress address = InetAddress.getByName(ip);
+        InetAddress mask = InetAddress.getByName("255.255.0.0");
+
+        x.setField(new NwSrc(address, mask));
+        Assert.assertEquals(address, x.getField(NwSrc.TYPE).getValue());
+        Assert.assertEquals(x.getField(NwSrc.TYPE).getMask(), mask);
+    }
+
+    @Test
+    public void testMatchSetGetEtherType() throws UnknownHostException {
+        Match x = new Match();
+
+        x.setField(new DlType(EtherTypes.QINQ.shortValue()));
+        Assert.assertEquals(x.getField(DlType.TYPE).getValue(), EtherTypes.QINQ.shortValue());
+
+        x.setField(new DlType(EtherTypes.LLDP.shortValue()));
+        Assert.assertEquals(x.getField(DlType.TYPE).getValue(), EtherTypes.LLDP.shortValue());
+        Assert.assertFalse(x.getField(DlType.TYPE).equals(EtherTypes.LLDP.intValue()));
+    }
+
+    @Test
+    public void testSetGetNwTos() {
+        Match x = new Match();
+        x.setField(new NwTos((byte) 0xb));
+
+        Byte t = new Byte((byte) 0xb);
+
+        Object o = x.getField(NwTos.TYPE).getValue();
+        Assert.assertEquals(o, t);
+        Assert.assertEquals(o, Byte.valueOf((byte)0xb));
+    }
+
+    @Test
+    public void testSetGetNwProto() {
+        Match x = new Match();
+        Byte proto = (byte) 199;
+        x.setField(new NwProtocol(proto));
+
+        Byte o = (Byte) x.getField(NwProtocol.TYPE).getValue();
+        Assert.assertEquals(o, proto);
+    }
+
+    @Test
+    public void testSetTpSrc() {
+        // Minimum value validation.
+        Match match = new Match();
+        short tp_src = 0;
+        match.setField(new TpSrc(tp_src));
+
+        Object o = match.getField(TpSrc.TYPE).getValue();
+        Assert.assertEquals(o, tp_src);
+
+        // Maximum value validation.
+        match = new Match();
+        tp_src = (short) 0xffff;
+        match.setField(new TpSrc(tp_src));
+
+        o = match.getField(TpSrc.TYPE).getValue();
+        Assert.assertEquals(o, tp_src);
+    }
+
+    @Test
+    public void testSetTpDst() {
+        // Minimum value validation.
+        Match match = new Match();
+        short tp_dst = 0;
+        match.setField(new TpDst(tp_dst));
+
+        Object o = match.getField(TpDst.TYPE).getValue();
+        Assert.assertTrue(o.equals(tp_dst));
+
+        // Maximum value validation.
+        match = new Match();
+        tp_dst = (short) 0xffff;
+        match.setField(new TpDst(tp_dst));
+
+        o = match.getField(TpDst.TYPE).getValue();
+        Assert.assertEquals(o, tp_dst);
+    }
+
+    @Test
+    public void testEquality() throws Exception {
+        Node node = NodeCreator.createOFNode(7L);
+        NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
+        NodeConnector port2 = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
+        byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
+        byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
+        byte srcMac2[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
+        byte dstMac2[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
+        InetAddress srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355");
+        InetAddress dstIP = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0");
+        InetAddress ipMask = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0");
+        InetAddress ipMaskd = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0");
+        InetAddress ipMask2 = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0");
+        InetAddress ipMaskd2 = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0");
+        short ethertype = EtherTypes.IPv6.shortValue();
+        short ethertype2 = EtherTypes.IPv6.shortValue();
+        short vlan = (short) 27, vlan2 = (short) 27;
+        byte vlanPr = (byte) 3, vlanPr2 = (byte) 3;
+        Byte tos = 4, tos2 = 4;
+        byte proto = IPProtocols.UDP.byteValue(), proto2 = IPProtocols.UDP.byteValue();
+        short src = (short) 5500, src2 = (short) 5500;
+        short dst = 80, dst2 = 80;
+
+        /*
+         * Create a SAL Flow aFlow
+         */
+        Match match1 = new Match();
+        Match match2 = new Match();
+        match1.setField(new InPort(port));
+        match1.setField(new DlSrc(srcMac));
+        match1.setField(new DlDst(dstMac));
+        match1.setField(new DlType(ethertype));
+        match1.setField(new DlVlan(vlan));
+        match1.setField(new DlVlanPriority(vlanPr));
+        match1.setField(new NwSrc(srcIP, ipMask));
+        match1.setField(new NwDst(dstIP, ipMaskd));
+        match1.setField(new NwTos(tos));
+        match1.setField(new NwProtocol(proto));
+        match1.setField(new TpSrc(src));
+        match1.setField(new TpDst(dst));
+
+        match2.setField(new InPort(port2));
+        match2.setField(new DlSrc(srcMac2));
+        match2.setField(new DlDst(dstMac2));
+        match2.setField(new DlType(ethertype2));
+        match2.setField(new DlVlan(vlan2));
+        match2.setField(new DlVlanPriority(vlanPr2));
+        match2.setField(new NwSrc(srcIP, ipMask2));
+        match2.setField(new NwDst(dstIP, ipMaskd2));
+        match2.setField(new NwTos(tos2));
+        match2.setField(new NwProtocol(proto2));
+        match2.setField(new TpSrc(src2));
+        match2.setField(new TpDst(dst2));
+
+        Assert.assertTrue(match1.equals(match2));
+
+        Set<String> allFields = new HashSet<String>(match1.getMatchesList());
+        allFields.addAll(match2.getMatchesList());
+        // Make sure all values are equals
+        for (String type : allFields) {
+            if (match1.isPresent(type)) {
+                Assert.assertEquals(match1.getField(type), match2.getField(type));
+            }
+        }
+
+        // Make none of the fields couples are pointing to the same reference
+        MatchField<?> a = null, b = null;
+        for (String type : allFields) {
+            a = match1.getField(type);
+            b = match2.getField(type);
+            if (a != null && b != null) {
+                Assert.assertFalse(a == b);
+            }
+        }
+    }
+
+    @Test
+    public void testEqualityNetMask() throws Exception {
+
+        InetAddress srcIP = InetAddress.getByName("1.1.1.1");
+        InetAddress ipMask = InetAddress.getByName("255.255.255.255");
+        InetAddress srcIP2 = InetAddress.getByName("1.1.1.1");
+        InetAddress ipMask2 = null;
+        short ethertype = EtherTypes.IPv4.shortValue();
+        short ethertype2 = EtherTypes.IPv4.shortValue();
+
+        /*
+         * Create a SAL Flow aFlow
+         */
+        Match match1 = new Match();
+        Match match2 = new Match();
+
+        match1.setField(new DlType(ethertype));
+        match1.setField(new NwSrc(srcIP, ipMask));
+
+        match2.setField(new DlType(ethertype2));
+        match2.setField(new NwSrc(srcIP2, ipMask2));
+
+        Assert.assertTrue(match1.equals(match2));
+
+        ipMask2 = InetAddress.getByName("255.255.255.255");
+        match2.setField(new NwSrc(srcIP2, ipMask2));
+
+        srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355");
+        srcIP2 = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355");
+        ipMask = null;
+        ipMask2 = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
+        ethertype = EtherTypes.IPv6.shortValue();
+        ethertype2 = EtherTypes.IPv6.shortValue();
+
+        match1.setField(new DlType(ethertype));
+        match1.setField(new NwSrc(srcIP, ipMask));
+
+        match2.setField(new DlType(ethertype2));
+        match2.setField(new NwSrc(srcIP2, ipMask2));
+
+        Assert.assertEquals(match1, match2);
+    }
+
+    @Test
+    public void testHashCodeWithReverseMatch() throws Exception {
+        InetAddress srcIP1 = InetAddress.getByName("1.1.1.1");
+        InetAddress ipMask1 = InetAddress.getByName("255.255.255.255");
+        InetAddress srcIP2 = InetAddress.getByName("2.2.2.2");
+        InetAddress ipMask2 = InetAddress.getByName("255.255.255.255");
+        MatchField<?> field1 = new NwSrc(srcIP1, ipMask1);
+        MatchField<?> field2 = new NwDst(srcIP2, ipMask2);
+        Match match1 = new Match();
+        match1.setField(field1);
+        match1.setField(field2);
+        Match match2 = match1.reverse();
+        Assert.assertFalse(match1.hashCode() == match2.hashCode());
+    }
+
+    @Test
+    public void testHashCode() throws Exception {
+        byte srcMac1[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
+        byte srcMac2[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
+        byte dstMac1[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
+        byte dstMac2[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
+        short ethertype = EtherTypes.IPv4.shortValue();
+        short ethertype2 = EtherTypes.IPv4.shortValue();
+        InetAddress srcIP1 = InetAddress.getByName("1.1.1.1");
+        InetAddress ipMask1 = InetAddress.getByName("255.255.255.255");
+        InetAddress srcIP2 = InetAddress.getByName("1.1.1.1");
+        InetAddress ipMask2 = InetAddress.getByName("255.255.255.255");
+
+        Match match1 = new Match();
+        Match match2 = new Match();
+
+        MatchField<?> field1 = new DlSrc(srcMac1);
+        MatchField<?> field2 = new DlSrc(srcMac2);
+        Assert.assertTrue(field1.hashCode() == field2.hashCode());
+
+        match1.setField(field1);
+        match2.setField(field2);
+        Assert.assertTrue(match1.hashCode() == match2.hashCode());
+
+        MatchField<?> field3 = new DlDst(dstMac1);
+        MatchField<?> field4 = new DlDst(dstMac2);
+        Assert.assertTrue(field3.hashCode() == field4.hashCode());
+
+        match1.setField(field3);
+        match2.setField(field4);
+        Assert.assertTrue(match1.hashCode() == match2.hashCode());
+
+        MatchField<?> field5 = new DlType(ethertype);
+        MatchField<?> field6 = new DlType(ethertype2);
+        Assert.assertTrue(field5.hashCode() == field6.hashCode());
+
+        match1.setField(field5);
+        match2.setField(field6);
+        Assert.assertTrue(match1.hashCode() == match2 .hashCode());
+
+        MatchField<?> field7 = new NwSrc(srcIP1, ipMask1);
+        MatchField<?> field8 = new NwSrc(srcIP2, ipMask2);
+        Assert.assertTrue(field7.hashCode() == field8.hashCode());
+
+        match1.setField(field7);
+        match2.setField(field8);
+        Assert.assertTrue(match1.hashCode() == match2.hashCode());
+
+    }
+
+    @Test
+    public void testCloning() throws Exception {
+        Node node = NodeCreator.createOFNode(7L);
+        NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
+        byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
+        byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
+        InetAddress srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355");
+        InetAddress dstIP = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0");
+        InetAddress ipMasks = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0");
+        InetAddress ipMaskd = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0");
+        short ethertype = EtherTypes.IPv6.shortValue();
+        short vlan = (short) 27;
+        byte vlanPr = (byte) 3;
+        Byte tos = 4;
+        byte proto = IPProtocols.UDP.byteValue();
+        short src = (short) 5500;
+        short dst = 80;
+
+        /*
+         * Create a SAL Flow aFlow
+         */
+        Match match = new Match();
+        match.setField(new InPort(port));
+        match.setField(new DlSrc(srcMac));
+        match.setField(new DlDst(dstMac));
+        match.setField(new DlType(ethertype));
+        match.setField(new DlVlan(vlan));
+        match.setField(new DlVlanPriority(vlanPr));
+        match.setField(new NwSrc(srcIP, ipMasks));
+        match.setField(new NwDst(dstIP, ipMaskd));
+        match.setField(new NwTos(tos));
+        match.setField(new NwProtocol(proto));
+        match.setField(new TpSrc(src));
+        match.setField(new TpDst(dst));
+
+        Match cloned = match.clone();
+
+        // Make sure all values are equals
+        for (String type : match.getMatchesList()) {
+            if (match.isPresent(type)) {
+                if (!match.getField(type).equals(cloned.getField(type))) {
+                    Assert.assertEquals(match.getField(type), cloned.getField(type));
+                }
+            }
+        }
+
+        // Make sure none of the fields couples are pointing to the same
+        // reference
+        MatchField<?> a = null, b = null;
+        for (String type : match.getMatchesList()) {
+            a = match.getField(type);
+            b = cloned.getField(type);
+            if (a != null && b != null) {
+                Assert.assertFalse(a == b);
+            }
+        }
+
+        Assert.assertTrue(match.equals(cloned));
+
+        Assert.assertEquals(match.getField(DlSrc.TYPE), cloned.getField(DlSrc.TYPE));
+        Assert.assertEquals(match.getField(NwDst.TYPE), cloned.getField(NwDst.TYPE));
+        Assert.assertEquals(match.getField(NwDst.TYPE).getMask(), cloned.getField(NwDst.TYPE).getMask());
+        Assert.assertEquals(match.hashCode(), cloned.hashCode());
+    }
+
+    @Test
+    public void testFlip() throws Exception {
+        Node node = NodeCreator.createOFNode(7L);
+        NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
+        byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
+        byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
+        InetAddress srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355");
+        InetAddress dstIP = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0");
+        InetAddress ipMasks = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0");
+        InetAddress ipMaskd = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0");
+        short ethertype = EtherTypes.IPv6.shortValue();
+        short vlan = (short) 27;
+        byte vlanPr = (byte) 3;
+        Byte tos = 4;
+        byte proto = IPProtocols.UDP.byteValue();
+        short src = (short) 5500;
+        short dst = 80;
+
+        /*
+         * Create a SAL Flow aFlow
+         */
+        Match match = new Match();
+        match.setField(new InPort(port));
+        match.setField(new DlSrc(srcMac));
+        match.setField(new DlDst(dstMac));
+        match.setField(new DlType(ethertype));
+        match.setField(new DlVlan(vlan));
+        match.setField(new DlVlanPriority(vlanPr));
+        match.setField(new NwSrc(srcIP, ipMasks));
+        match.setField(new NwDst(dstIP, ipMaskd));
+        match.setField(new NwTos(tos));
+        match.setField(new NwProtocol(proto));
+        match.setField(new TpSrc(src));
+        match.setField(new TpDst(dst));
+
+        Match flipped = match.reverse();
+
+        Assert.assertEquals(match.getField(DlType.TYPE), flipped.getField(DlType.TYPE));
+        Assert.assertEquals(match.getField(DlVlan.TYPE), flipped.getField(DlVlan.TYPE));
+
+        Assert.assertArrayEquals((byte[]) match.getField(DlDst.TYPE).getValue(), (byte[]) flipped.getField(DlSrc.TYPE)
+                .getValue());
+
+        Assert.assertEquals(match.getField(NwDst.TYPE).getValue(), flipped.getField(NwSrc.TYPE).getValue());
+
+        Assert.assertEquals(match.getField(TpDst.TYPE).getValue(), flipped.getField(TpSrc.TYPE).getValue());
+
+        Match flipflip = flipped.reverse().reverse();
+        Assert.assertEquals(flipflip, flipped);
+
+    }
+
+    @Test
+    public void testVlanNone() throws Exception {
+        // The value 0 is used to indicate that no VLAN ID is set
+        short vlan = (short) 0;
+        MatchField<?> field = new DlVlan(vlan);
+
+        Assert.assertTrue(field != null);
+        Assert.assertEquals(field.getValue(), new Short(vlan));
+        Assert.assertTrue(field.isValid());
+    }
+
+    @Test
+    public void testIntersection() throws UnknownHostException {
+        Short ethType = Short.valueOf((short)0x800);
+        InetAddress ip1 = InetAddress.getByName("1.1.1.1");
+        InetAddress ip2 = InetAddress.getByName("1.1.1.0");
+        InetAddress ipm2 = InetAddress.getByName("255.255.255.0");
+        InetAddress ip3 = InetAddress.getByName("1.3.0.0");
+        InetAddress ipm3 = InetAddress.getByName("255.255.0.0");
+        InetAddress ip4 = InetAddress.getByName("1.3.4.4");
+        InetAddress ipm4 = InetAddress.getByName("255.255.255.0");
+
+        Match m1 = new Match();
+        m1.setField(new DlType(ethType));
+        m1.setField(new NwSrc(ip1));
+
+        Match m2 = new Match();
+        m2.setField(new DlType(ethType));
+        m2.setField(new NwSrc(ip2, ipm2));
+
+        Match m3 = new Match();
+        m3.setField(new DlType(ethType));
+        m3.setField(new NwSrc(ip3, ipm3));
+        m3.setField(new NwProtocol(IPProtocols.TCP.byteValue()));
+
+        Match m3r = m3.reverse();
+        Assert.assertTrue(m3.intersetcs(m3r));
+
+        Assert.assertTrue(m1.intersetcs(m2));
+        Assert.assertTrue(m2.intersetcs(m1));
+        Assert.assertFalse(m1.intersetcs(m3));
+        Assert.assertTrue(m1.intersetcs(m3r));
+        Assert.assertFalse(m3.intersetcs(m1));
+        Assert.assertTrue(m3.intersetcs(m1.reverse()));
+        Assert.assertFalse(m2.intersetcs(m3));
+        Assert.assertFalse(m3.intersetcs(m2));
+        Assert.assertTrue(m2.intersetcs(m3r));
+
+
+        Match i = m1.getIntersection(m2);
+        Assert.assertTrue(((Short)i.getField(DlType.TYPE).getValue()).equals(ethType));
+        // Verify intersection of IP addresses is correct
+        Assert.assertTrue(((InetAddress)i.getField(NwSrc.TYPE).getValue()).equals(ip1));
+        Assert.assertNull(i.getField(NwSrc.TYPE).getMask());
+
+        // Empty set
+        i = m2.getIntersection(m3);
+        Assert.assertNull(i);
+
+        Match m4 = new Match();
+        m4.setField(new DlType(ethType));
+        m4.setField(new NwProtocol(IPProtocols.TCP.byteValue()));
+        m3.setField(new NwSrc(ip4, ipm4));
+        Assert.assertTrue(m4.intersetcs(m3));
+
+        // Verify intersection of IP and IP mask addresses is correct
+        Match ii = m3.getIntersection(m4);
+        Assert.assertTrue(((InetAddress)ii.getField(NwSrc.TYPE).getValue()).equals(ip4));
+        Assert.assertTrue(((InetAddress)ii.getField(NwSrc.TYPE).getMask()).equals(ipm4));
+
+        Match m5 = new Match();
+        m5.setField(new DlType(ethType));
+        m3.setField(new NwSrc(ip3, ipm3));
+        m5.setField(new NwProtocol(IPProtocols.UDP.byteValue()));
+        Assert.assertFalse(m5.intersetcs(m3));
+        Assert.assertFalse(m5.intersetcs(m4));
+        Assert.assertTrue(m5.intersetcs(m5));
+        Assert.assertFalse(m3.intersetcs(m5));
+        Assert.assertFalse(m4.intersetcs(m5));
+
+
+        Match i2 = m4.getIntersection(m3);
+        Assert.assertFalse(i2.isEmpty());
+        Assert.assertFalse(i2.getMatchesList().isEmpty());
+        Assert.assertTrue(((InetAddress)i2.getField(NwSrc.TYPE).getValue()).equals(ip3));
+        Assert.assertTrue(((InetAddress)i2.getField(NwSrc.TYPE).getMask()).equals(ipm3));
+        Assert.assertTrue(((Byte)i2.getField(NwProtocol.TYPE).getValue()).equals(IPProtocols.TCP.byteValue()));
+
+        byte src[] = {(byte)0, (byte)0xab,(byte)0xbc,(byte)0xcd,(byte)0xde,(byte)0xef};
+        byte dst[] = {(byte)0x10, (byte)0x11,(byte)0x12,(byte)0x13,(byte)0x14,(byte)0x15};
+        Short srcPort = (short)1024;
+        Short dstPort = (short)80;
+
+        // Check identity
+        Match m6 = new Match();
+        m6.setField(new DlSrc(src));
+        m6.setField(new DlDst(dst));
+        m6.setField(new NwSrc(ip2, ipm2));
+        m6.setField(new NwDst(ip3, ipm3));
+        m6.setField(new NwProtocol(IPProtocols.UDP.byteValue()));
+        m6.setField(new TpSrc(srcPort));
+        m6.setField(new TpDst(dstPort));
+        Assert.assertTrue(m6.intersetcs(m6));
+        Assert.assertTrue(m6.getIntersection(m6).equals(m6));
+
+        // Empty match, represents the universal set (all packets)
+        Match u = new Match();
+        Assert.assertEquals(m6.getIntersection(u), m6);
+        Assert.assertEquals(u.getIntersection(m6), m6);
+
+        // No intersection with null match, empty set
+        Assert.assertNull(m6.getIntersection(null));
+    }
+}