Merge "Fix testing support for OSGi services registration under String name(s)"
authorEd Warnicke <eaw@cisco.com>
Wed, 8 Jan 2014 22:09:02 +0000 (22:09 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Wed, 8 Jan 2014 22:09:02 +0000 (22:09 +0000)
60 files changed:
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ComponentActivator.xtend
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/FlowProgrammerAdapter.xtend
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/FromSalConversionsUtils.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.xtend
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/MDFlowMapping.xtend
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.xtend
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ToSalConversionsUtils.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/topology/TopologyAdapter.xtend
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/topology/TopologyCommitHandler.xtend
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/topology/TopologyMapping.xtend
opendaylight/md-sal/model/model-flow-base/pom.xml
opendaylight/md-sal/model/model-flow-base/src/main/yang/match-types.yang
opendaylight/md-sal/model/pom.xml
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/BindingIndependentConnector.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/PutAugmentationTest.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlMapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonBasicYangTypesTest.java [moved from opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/ToJsonBasicYangTypesTest.java with 90% similarity]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonChoiceCaseTest.java [moved from opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/ToJsonChoiceCaseTest.java with 86% similarity]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java [moved from opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/ToJsonBasicDataTypesTest.java with 56% similarity]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIdentityrefTest.java [moved from opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/ToJsonIdentityrefTest.java with 56% similarity]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonNotExistingLeafTypeTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/ToJsonLeafrefType.java [deleted file]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/ToJsonWithAugmentTest.java [deleted file]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlNotExistingLeafTypeTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithChoiceTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonIdentityrefToCnSnTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonToCnSnTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/ControllerContextTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/ReadConfAndOperDataTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestCodecExceptionsTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlProvidersTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/YangAndXmlAndDataSchemaLoader.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java
opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/invalid-top-level-element/invalid-top-level-element.yang [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/list/list-types-module [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-xml/choice/module-with-choice.yang [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-xml/yang/basic-module.yang
opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/leafref/json/data.json [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/leafref/leafref-module [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/simple-list-yang/1/simple-list1.yang [moved from opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/simple-list-yang/simple-list1.yang with 100% similarity]
opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/simple-list-yang/2/simple-list2.yang [moved from opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/simple-list-yang/simple-list2.yang with 100% similarity]
opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/unsupported-json-format.json [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/leafref-module [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/xml/data.xml [new file with mode: 0644]
opendaylight/md-sal/statistics-manager/src/main/java/org/opendaylight/controller/md/statistics/manager/StatisticsUpdateCommiter.java
opendaylight/md-sal/topology-lldp-discovery/src/main/java/org/opendaylight/md/controller/topology/lldp/utils/LLDPDiscoveryUtils.java
opendaylight/web/root/src/main/java/org/opendaylight/controller/web/DaylightWeb.java
opendaylight/web/root/src/main/resources/WEB-INF/web.xml

index 272e8bafb7f8648f6cc35024f0ab54f89bf5e893..d7a345cfc86198ead50ff1a937eadf0dd1348d21 100644 (file)
@@ -82,6 +82,7 @@ class ComponentActivator extends ComponentActivatorAbstractBase implements Bindi
 
         // Registration of Flow Service
         flow.delegate = session.getRpcService(SalFlowService)
+        flow.dataBrokerService = session.getSALService(DataBrokerService);
         subscribe.registerNotificationListener(flow);
 
         // Data Packet Service
index 2eae511e02975e6aa23f9d2a09091fa186ab3764..450c7f1f239c4634b994fd6b71b941492321d8b4 100644 (file)
@@ -18,7 +18,24 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.Node
 import org.opendaylight.yangtools.yang.common.RpcResult
 import org.slf4j.LoggerFactory
 
-import static org.opendaylight.controller.sal.compatibility.MDFlowMapping.*
+import org.opendaylight.controller.sal.binding.api.data.DataBrokerService
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus
+import org.opendaylight.controller.md.sal.common.api.data.DataModification
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey
+import org.opendaylight.yangtools.yang.binding.DataObject
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId
+
+
+import static extension org.opendaylight.controller.sal.compatibility.MDFlowMapping.*
 
 import static extension org.opendaylight.controller.sal.compatibility.NodeMapping.*
 import static extension org.opendaylight.controller.sal.compatibility.ToSalConversionsUtils.*
@@ -29,64 +46,52 @@ class FlowProgrammerAdapter implements IPluginInFlowProgrammerService, SalFlowLi
 
     @Property
     private SalFlowService delegate;
+
+    @Property
+    private DataBrokerService dataBrokerService;
     
     @Property
     private IPluginOutFlowProgrammerService flowProgrammerPublisher;
 
     override addFlow(Node node, Flow flow) {
-        val input = addFlowInput(node, flow);
-        val future = delegate.addFlow(input);
-        try {
-            val result = future.get();
-            return toStatus(result); // how get status from result? conversion?
-        } catch (Exception e) {
-            return processException(e);
-        }
+        return addFlowAsync(node,flow,0)
     }
 
     override modifyFlow(Node node, Flow oldFlow, Flow newFlow) {
-        val input = updateFlowInput(node, oldFlow, newFlow);
-        val future = delegate.updateFlow(input);
-        try {
-            val result = future.get();
-            return toStatus(result);
-        } catch (Exception e) {
-            return processException(e);
-        }
+        return modifyFlowAsync(node, oldFlow,newFlow,0)
     }
 
     override removeFlow(Node node, Flow flow) {
-        val input = removeFlowInput(node, flow);
-        val future = delegate.removeFlow(input);
-
-        try {
-            val result = future.get();
-            return toStatus(result);
-        } catch (Exception e) {
-            return processException(e);
-        }
+        return removeFlowAsync(node, flow,0);
     }
 
     override addFlowAsync(Node node, Flow flow, long rid) {
-        val input = addFlowInput(node, flow);
-        delegate.addFlow(input);
-        return new Status(StatusCode.SUCCESS);
+        writeFlow(flow.toMDFlow, new NodeKey(new NodeId(node.getNodeIDString())));
+        return toStatus(true);
     }
 
     override modifyFlowAsync(Node node, Flow oldFlow, Flow newFlow, long rid) {
-        val input = updateFlowInput(node, oldFlow, newFlow);
-        delegate.updateFlow(input);
-        return new Status(StatusCode.SUCCESS);
+        writeFlow(newFlow.toMDFlow, new NodeKey(new NodeId(node.getNodeIDString())));
+        return toStatus(true);
     }
 
-    override removeFlowAsync(Node node, Flow flow, long rid) {
-        val input = removeFlowInput(node, flow);
-        delegate.removeFlow(input);
-        return new Status(StatusCode.SUCCESS);
+    override removeFlowAsync(Node node, Flow adflow, long rid) {
+        val flow = adflow.toMDFlow;
+        val modification = this._dataBrokerService.beginTransaction();
+        val flowPath = InstanceIdentifier.builder(Nodes)
+                .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node, new NodeKey(new NodeId(node.getNodeIDString())))
+                .augmentation(FlowCapableNode)
+                .child(Table, new TableKey(flow.getTableId()))
+                .child(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow, new FlowKey(flow.id))
+                .build;
+        modification.removeConfigurationData(flowPath);
+        val commitFuture = modification.commit();
+        return toStatus(true);
     }
 
     override removeAllFlows(Node node) {
-        throw new UnsupportedOperationException("Not present in MD-SAL");
+        // I know this looks like a copout... but its exactly what the legacy OFplugin did
+        return new Status(StatusCode.SUCCESS);
     }
 
     override syncSendBarrierMessage(Node node) {
@@ -101,13 +106,38 @@ class FlowProgrammerAdapter implements IPluginInFlowProgrammerService, SalFlowLi
         return null;
     }
 
-    public static def toStatus(RpcResult<?> result) {
-        if (result.isSuccessful()) {
+    private static def toStatus(boolean successful) {
+        if (successful) {
             return new Status(StatusCode.SUCCESS);
         } else {
             return new Status(StatusCode.INTERNALERROR);
         }
     }
+
+
+    private def writeFlow(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow flow, NodeKey nodeKey) {
+        val modification = this._dataBrokerService.beginTransaction();
+        val flowPath = InstanceIdentifier.builder(Nodes)
+                .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node, nodeKey)
+                .augmentation(FlowCapableNode)
+                .child(Table, new TableKey(flow.getTableId()))
+                .child(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow, new FlowKey(flow.id))
+                .build;
+        modification.putConfigurationData(flowPath, flow);
+        val commitFuture = modification.commit();
+        try {
+            val result = commitFuture.get();
+            val status = result.getResult();
+        } catch (InterruptedException e) {
+            LOG.error(e.getMessage(), e);
+        } catch (ExecutionException e) {
+            LOG.error(e.getMessage(), e);
+        }
+    }
+
+    public static def toStatus(RpcResult<?> result) {
+        return toStatus(result.isSuccessful());
+    }
     
     private static dispatch def Status processException(InterruptedException e) {
         LOG.error("Interruption occured during processing flow",e);
index 4e6e49eac70cefd3576754d542e159c649fa457b..eba4aa901bdc1d2496a485c9676024bb01002f3b 100644 (file)
@@ -12,6 +12,7 @@ import java.net.Inet4Address;
 import java.net.Inet6Address;
 import java.net.InetAddress;
 
+import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.match.Match;
 import org.opendaylight.controller.sal.match.MatchField;
 import org.opendaylight.controller.sal.match.MatchType;
@@ -26,6 +27,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.addr
 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.address.address.Ipv6Builder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanPcp;
@@ -83,6 +85,7 @@ public class FromSalConversionsUtils {
             targetBuilder.setVlanMatch(vlanMatch(sourceMatch));
             targetBuilder.setLayer3Match(layer3Match(sourceMatch));
             targetBuilder.setLayer4Match(layer4Match(sourceMatch));
+            targetBuilder.setInPort(inPortMatch(sourceMatch));
 
             return targetBuilder.build();
         }
@@ -90,6 +93,14 @@ public class FromSalConversionsUtils {
 
     }
 
+    private static NodeConnectorId inPortMatch(Match sourceMatch) {
+        MatchField inPort = sourceMatch.getField(MatchType.IN_PORT);
+        if(inPort != null && inPort.getValue() != null && (inPort.getValue() instanceof NodeConnector)) {
+            return new NodeConnectorId(((NodeConnector) inPort.getValue()).getNodeConnectorIdAsString());
+        }
+        return null;
+    }
+
     private static Layer4Match layer4Match(final Match sourceMatch) {
         MatchField nwProto = sourceMatch.getField(MatchType.NW_PROTO);
         Short nwProtocolSource = null;
@@ -121,8 +132,10 @@ public class FromSalConversionsUtils {
             sctpMatchBuilder.setSctpDestinationPort(new PortNumber(
                     destinationPort));
         }
-
-        return sctpMatchBuilder.build();
+        if(sourcePort != null || destinationPort != null) {
+            return sctpMatchBuilder.build();
+        }
+        return null;
     }
 
     private static Layer4Match Layer4MatchAsUdp(final Match sourceMatch) {
@@ -140,8 +153,10 @@ public class FromSalConversionsUtils {
             udpMatchBuilder.setUdpDestinationPort(new PortNumber(
                     destinationPort));
         }
-
-        return udpMatchBuilder.build();
+        if(sourcePort != null || destinationPort != null) {
+            return udpMatchBuilder.build();
+        }
+        return null;
     }
 
     private static Layer4Match Layer4MatchAsTcp(final Match sourceMatch) {
@@ -158,8 +173,10 @@ public class FromSalConversionsUtils {
             tcpMatchBuilder.setTcpDestinationPort(new PortNumber(
                     destinationPort));
         }
-
-        return tcpMatchBuilder.build();
+        if(sourcePort != null || destinationPort != null) {
+            return tcpMatchBuilder.build();
+        }
+        return null;
     }
 
     private static Integer transportPort(final Match sourceMatch,
@@ -189,8 +206,10 @@ public class FromSalConversionsUtils {
             vlanMatchBuild.setVlanPcp(new VlanPcp((short) ((byte) vlanPriority
                     .getValue())));
         }
-
-        return vlanMatchBuild.build();
+        if((vlan != null && vlan.getValue() != null) || (vlanPriority != null && vlanPriority.getValue() != null)) {
+            return vlanMatchBuild.build();
+        }
+        return null;
     }
 
     private static IpMatch ipMatch(final Match sourceMatch) {
@@ -208,21 +227,24 @@ public class FromSalConversionsUtils {
             targetIpMatchBuild.setIpProtocol((short) ((byte) protocol
                     .getValue()));
         }
-
-        return targetIpMatchBuild.build();
-
+        if((networkTos != null && networkTos.getValue() != null) || (protocol != null && protocol.getValue() != null)) {
+            return targetIpMatchBuild.build();
+        }
+        return null;
     }
 
     private static EthernetMatch ethernetMatch(final Match sourceMatch) {
         final EthernetMatchBuilder targetEthMatchBuild = new EthernetMatchBuilder();
-
-        EthernetSourceBuilder ethSourBuild = new EthernetSourceBuilder()
-                .setAddress(ethernetSourceAddress(sourceMatch));
-        targetEthMatchBuild.setEthernetSource(ethSourBuild.build());
-
-        EthernetDestinationBuilder ethDestBuild = new EthernetDestinationBuilder()
-                .setAddress(ethernetDestAddress(sourceMatch));
-        targetEthMatchBuild.setEthernetDestination(ethDestBuild.build());
+        if(sourceMatch.getField(DL_SRC) != null && sourceMatch.getField(DL_SRC).getValue() != null) {
+            EthernetSourceBuilder ethSourBuild = new EthernetSourceBuilder()
+                    .setAddress(ethernetSourceAddress(sourceMatch));
+            targetEthMatchBuild.setEthernetSource(ethSourBuild.build());
+        }
+        if(sourceMatch.getField(DL_DST) != null && sourceMatch.getField(DL_DST).getValue() != null) {
+            EthernetDestinationBuilder ethDestBuild = new EthernetDestinationBuilder()
+                    .setAddress(ethernetDestAddress(sourceMatch));
+            targetEthMatchBuild.setEthernetDestination(ethDestBuild.build());
+        }
 
         final MatchField dataLinkType = sourceMatch.getField(MatchType.DL_TYPE);
         if (dataLinkType != null && dataLinkType.getValue() != null) {
@@ -232,7 +254,12 @@ public class FromSalConversionsUtils {
                     .setType(etherType);
             targetEthMatchBuild.setEthernetType(ethType.build());
         }
-        return targetEthMatchBuild.build();
+        if((sourceMatch.getField(DL_SRC) != null && sourceMatch.getField(DL_SRC).getValue() != null) || 
+                (sourceMatch.getField(DL_DST) != null && sourceMatch.getField(DL_DST).getValue() != null)|| 
+                dataLinkType != null ) {
+            return targetEthMatchBuild.build();            
+        } 
+        return null;
     }
 
     private static MacAddress ethernetSourceAddress(final Match sourceMatch) {
@@ -258,7 +285,7 @@ public class FromSalConversionsUtils {
         }
 
         if ((inetSourceAddress instanceof Inet4Address)
-                && (inetDestAddress instanceof Inet4Address)) {
+                || (inetDestAddress instanceof Inet4Address)) {
             MatchField dataLinkType = sourceMatch.getField(DL_TYPE);
             Short dLType = null;
             if (dataLinkType != null && dataLinkType.getValue() != null) {
@@ -273,7 +300,7 @@ public class FromSalConversionsUtils {
                         (Inet4Address) inetDestAddress);
             }
         } else if ((inetSourceAddress instanceof Inet6Address)
-                && (inetDestAddress instanceof Inet6Address)) {
+                || (inetDestAddress instanceof Inet6Address)) {
             return setLayer3MatchAsIpv6((Inet6Address) inetSourceAddress,
                     (Inet6Address) inetDestAddress);
         }
@@ -327,15 +354,18 @@ public class FromSalConversionsUtils {
     private static Layer3Match setLayer3MatchAsIpv4(
             final Inet4Address inetSourceAddress,
             final Inet4Address inetDestAddress) {
-        String inetSrcAddressString = InetAddresses
-                .toAddrString(inetSourceAddress);
-        String inetDstAddressString = InetAddresses
-                .toAddrString(inetDestAddress);
-
         Ipv4MatchBuilder layer4MatchBuild = new Ipv4MatchBuilder();
-        layer4MatchBuild.setIpv4Source(new Ipv4Prefix(inetSrcAddressString));
-        layer4MatchBuild
-                .setIpv4Destination(new Ipv4Prefix(inetDstAddressString));
+        if(inetSourceAddress != null) {
+            String inetSrcAddressString = InetAddresses
+                    .toAddrString(inetSourceAddress);
+            layer4MatchBuild.setIpv4Source(new Ipv4Prefix(inetSrcAddressString));
+        }
+        if(inetDestAddress != null) {
+            String inetDstAddressString = InetAddresses
+                    .toAddrString(inetDestAddress);
+            layer4MatchBuild
+            .setIpv4Destination(new Ipv4Prefix(inetDstAddressString));
+        }       
         return layer4MatchBuild.build();
 
     }
@@ -343,15 +373,18 @@ public class FromSalConversionsUtils {
     private static Layer3Match setLayer3MatchAsIpv6(
             final Inet6Address inetSourceAddress,
             final Inet6Address inetDestAddress) {
-        String inetSrcAddressString = InetAddresses
-                .toAddrString(inetSourceAddress);
-        String inetDstAddressString = InetAddresses
-                .toAddrString(inetDestAddress);
         Ipv6MatchBuilder layer6MatchBuild = new Ipv6MatchBuilder();
-
-        layer6MatchBuild.setIpv6Source(new Ipv6Prefix(inetSrcAddressString));
-        layer6MatchBuild
-                .setIpv6Destination(new Ipv6Prefix(inetDstAddressString));
+        if(inetSourceAddress != null) {
+            String inetSrcAddressString = InetAddresses
+                    .toAddrString(inetSourceAddress);
+            layer6MatchBuild.setIpv6Source(new Ipv6Prefix(inetSrcAddressString));
+        }
+        if(inetDestAddress != null) {
+            String inetDstAddressString = InetAddresses
+                    .toAddrString(inetDestAddress);    
+            layer6MatchBuild
+                    .setIpv6Destination(new Ipv6Prefix(inetDstAddressString));
+        }
         return layer6MatchBuild.build();
     }
     
index d5fbd041e4a45d593d3d744e2aa6f5e90bc42288..56ca1b609cf2c6eeb6d5dfe669b660319d4d792d 100644 (file)
@@ -64,6 +64,9 @@ import org.slf4j.LoggerFactory
 
 import static extension org.opendaylight.controller.sal.common.util.Arguments.*
 import static extension org.opendaylight.controller.sal.compatibility.NodeMapping.*
+import org.opendaylight.controller.md.sal.binding.util.TypeSafeDataReader
+import java.util.concurrent.ConcurrentHashMap
+import java.util.Map
 
 class InventoryAndReadAdapter implements IPluginInReadService,
                                                                                         IPluginInInventoryService,
@@ -349,7 +352,7 @@ class InventoryAndReadAdapter implements IPluginInReadService,
         if ( this._dataService.readOperationalData(identifier) == null ){
             updateType = UpdateType.ADDED;
         }
-        inventoryPublisher.updateNode(notification.nodeRef.toADNode, updateType, properties);
+        inventoryPublisher.updateNode(notification.nodeRef.toADNode, updateType, notification.toADNodeProperties);
         
                //Notify the listeners of IPluginOutReadService
         
@@ -360,15 +363,64 @@ class InventoryAndReadAdapter implements IPluginInReadService,
     }
 
     override getNodeProps() {
-
-        // FIXME: Read from MD-SAL inventory service
-        return null;
+        val props = new ConcurrentHashMap<Node, Map<String, org.opendaylight.controller.sal.core.Property>>()
+        
+        val nodes = readAllMDNodes()
+        for (node : nodes.node ) {
+            val fcn = node.getAugmentation(FlowCapableNode)
+            if(fcn != null) {
+                val perNodeProps = fcn.toADNodeProperties(node.id)
+                val perNodePropMap = new ConcurrentHashMap<String, org.opendaylight.controller.sal.core.Property>
+                if(perNodeProps != null ) {
+                    for(perNodeProp : perNodeProps) {
+                        perNodePropMap.put(perNodeProp.name,perNodeProp)
+                    }
+                }
+                props.put(new Node(MD_SAL_TYPE, node.id.toADNodeId),perNodePropMap)
+            }
+        }
+        return props;
+    }
+    
+    private def readAllMDNodes() {
+        val nodesRef = InstanceIdentifier.builder(Nodes)
+            .toInstance
+        val reader = TypeSafeDataReader.forReader(dataService)
+        return reader.readOperationalData(nodesRef)
+    }
+    
+    private def readAllMDNodeConnectors(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node node) {
+        val nodeRef = InstanceIdentifier.builder(Nodes)
+            .child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node,new NodeKey(node.id))
+            .toInstance
+        val reader = TypeSafeDataReader.forReader(dataService)
+        return reader.readOperationalData(nodeRef).nodeConnector
     }
 
     override getNodeConnectorProps(Boolean refresh) {
-
-        // FIXME: Read from MD-SAL Invcentory Service
-        return null;
+        // Note, because the MD-SAL has a unified data store, we can ignore the Boolean refresh, as we have no secondary 
+        // data store to refresh from
+        val props = new ConcurrentHashMap<org.opendaylight.controller.sal.core.NodeConnector, Map<String, org.opendaylight.controller.sal.core.Property>>()
+        val nodes = readAllMDNodes()
+        for (node : nodes.node) {
+            val ncs = node.readAllMDNodeConnectors
+            if(ncs != null) {
+                for( nc : ncs ) {
+                    val fcnc = nc.getAugmentation(FlowCapableNodeConnector)
+                    if(fcnc != null) {
+                        val ncps = fcnc.toADNodeConnectorProperties
+                        val ncpsm = new ConcurrentHashMap<String, org.opendaylight.controller.sal.core.Property>
+                        if(ncps != null) {
+                            for(p : ncps) {
+                                ncpsm.put(p.name,p)
+                            }
+                        }  
+                        props.put(nc.id.toADNodeConnector(node.id),ncpsm)
+                    }
+                }
+            }
+        }
+        return props
     }
 
     private def FlowCapableNode readFlowCapableNode(NodeRef ref) {
index 2f458c41ddfc8dce40325338fe015ba41e8c4118..b0f6065bac751a25ceb57d6d1bde65ed9550f6cb 100644 (file)
@@ -105,6 +105,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instru
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCaseBuilder
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId
 
 public class MDFlowMapping {
 
@@ -129,14 +130,37 @@ public class MDFlowMapping {
         }
         instructions = targetActions.toApplyInstruction();
         match = sourceFlow.match.toMatch();
+        tableId = new Integer(0).shortValue
         return it.build();
 
     }
     
+    public static def toMDFlow(Flow sourceFlow) {
+       if (sourceFlow == null)
+            throw new IllegalArgumentException();
+       val it = new FlowBuilder();
+       hardTimeout = sourceFlow.hardTimeout as int
+       idleTimeout = sourceFlow.idleTimeout as int
+       cookie = BigInteger.valueOf(sourceFlow.id)
+       priority = sourceFlow.priority as int
+       id = new FlowId(sourceFlow.id)
+    
+       val sourceActions = sourceFlow.actions;
+       val targetActions = new ArrayList<Action>();
+       for (sourceAction : sourceActions) {
+           targetActions.add(sourceAction.toAction());
+       }
+       instructions = targetActions.toApplyInstruction();
+       match = sourceFlow.match.toMatch();
+       tableId = new Integer(0).shortValue
+       return it.build();
+    }
+    
     public static def Instructions toApplyInstruction(ArrayList<Action> actions) {
         val it = new InstructionsBuilder;
         val applyActions = new InstructionBuilder;
         applyActions.instruction = new ApplyActionsCaseBuilder().setApplyActions(new ApplyActionsBuilder().setAction(actions).build()).build()
+        applyActions.setOrder(new Integer(0))
         instruction = Collections.<Instruction>singletonList(applyActions.build)
         return it.build;
     }
@@ -144,12 +168,14 @@ public class MDFlowMapping {
     public static def removeFlowInput(Node sourceNode, Flow sourceFlow) {
         val source = flowAdded(sourceFlow);
         val it = new RemoveFlowInputBuilder(source as org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.Flow);
+        node = sourceNode.toNodeRef()
         return it.build();
     }
 
     public static def addFlowInput(Node sourceNode, Flow sourceFlow) {
         val source = flowAdded(sourceFlow);
         val it = new AddFlowInputBuilder(source as org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.Flow);
+        it.setNode(sourceNode.toNodeRef)
         return it.build();
     }
 
index 29973b7b330887454c48dbc976712041e428b3d4..4378e7dffece701592936ce85dba77884c6ce8d8 100644 (file)
@@ -7,6 +7,7 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableIt
 
 import static com.google.common.base.Preconditions.*;
 import static extension org.opendaylight.controller.sal.common.util.Arguments.*;
+import static extension org.opendaylight.controller.sal.compatibility.ToSalConversionsUtils.*;
 
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef
@@ -27,48 +28,110 @@ import org.opendaylight.controller.sal.core.Name
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortConfig
 import org.opendaylight.controller.sal.core.Config
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.flow.capable.port.State
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdated
+import java.util.HashSet
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdated
+import org.opendaylight.controller.sal.core.Tables
+import java.util.List
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FeatureCapability
+import org.opendaylight.controller.sal.core.Buffers
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityFlowStats
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityTableStats
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityIpReasm
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityPortStats
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityStp
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityQueueStats
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityArpMatchIp
+import org.opendaylight.controller.sal.core.Capabilities
+import org.opendaylight.controller.sal.core.MacAddress
+import java.util.Date
+import org.opendaylight.controller.sal.core.TimeStamp
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowNodeConnector
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowNode
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector
 
 public class NodeMapping {
 
     public static val MD_SAL_TYPE = "MD_SAL";
     private static val NODE_CLASS = org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-    private static val NODECONNECTOR_CLASS = org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
+    private static val NODECONNECTOR_CLASS = org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.
+        NodeConnector;
 
     private new() {
         throw new UnsupportedOperationException("Utility class. Instantiation is not allowed.");
     }
 
     public static def toADNode(InstanceIdentifier<?> node) throws ConstructionException {
+        return node.toNodeId.toADNode
+    }
+
+    public static def toADNode(NodeId id) {
+        return new Node(MD_SAL_TYPE, id.toADNodeId);
+    }
+
+    public static def toNodeId(InstanceIdentifier<?> node) {
         checkNotNull(node);
         checkNotNull(node.getPath());
         checkArgument(node.getPath().size() >= 2);
         val arg = node.getPath().get(1);
         val item = arg.checkInstanceOf(IdentifiableItem);
         val nodeKey = item.getKey().checkInstanceOf(NodeKey);
-        return new Node(MD_SAL_TYPE, nodeKey.id.toADNodeId);
+        return nodeKey.id
     }
-    
+
     public static def toADNodeId(NodeId nodeId) {
         checkNotNull(nodeId);
         return nodeId.value
     }
 
-
     public static def toADNodeConnector(NodeConnectorRef source) throws ConstructionException {
         checkNotNull(source);
         val InstanceIdentifier<?> path = checkNotNull(source.getValue());
-        val node = path.toADNode();
         checkArgument(path.path.size() >= 3);
         val arg = path.getPath().get(2);
         val item = arg.checkInstanceOf(IdentifiableItem);
         val connectorKey = item.getKey().checkInstanceOf(NodeConnectorKey);
-        return new NodeConnector(MD_SAL_TYPE, connectorKey.id.toADNodeConnectorId, node);
+        return connectorKey.id.toADNodeConnector(path.toNodeId)
     }
     
-    public static def toADNodeConnectorId(NodeConnectorId nodeConnectorId) {
+    public static def toADNodeConnector(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId ncid,
+        org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nid) {
+            return new NodeConnector(ncid.toNodeConnectorType(nid),
+            ncid.toADNodeConnectorId(nid), nid.toADNode);
+     }
+
+    public static def toNodeConnectorType(NodeConnectorId ncId, NodeId nodeId) {
+        if (ncId.equals(nodeId.toLocalNodeConnectorId)) {
+            return NodeConnector.NodeConnectorIDType.SWSTACK
+        } else if (ncId.equals(nodeId.toNormalNodeConnectorId)) {
+            return NodeConnector.NodeConnectorIDType.HWPATH
+        } else if (ncId.equals(nodeId.toControllerNodeConnectorId)) {
+            return NodeConnector.NodeConnectorIDType.CONTROLLER
+        }
+        return MD_SAL_TYPE
+    }
+
+    public static def toADNodeConnectorId(NodeConnectorId nodeConnectorId, NodeId nodeId) {
+        if (nodeConnectorId.equals(nodeId.toLocalNodeConnectorId) ||
+            nodeConnectorId.equals(nodeId.toNormalNodeConnectorId) ||
+            nodeConnectorId.equals(nodeId.toControllerNodeConnectorId)) {
+            return NodeConnector.SPECIALNODECONNECTORID
+        }
         return nodeConnectorId.value
     }
-    
+
+    public static def toControllerNodeConnectorId(NodeId node) {
+        return new NodeConnectorId(node.value + ":" + 4294967293L)
+    }
+
+    public static def toLocalNodeConnectorId(NodeId node) {
+        return new NodeConnectorId(node.value + ":" + 4294967294L)
+    }
+
+    public static def toNormalNodeConnectorId(NodeId node) {
+        return new NodeConnectorId(node.value + ":" + 4294967290L)
+    }
+
     public static def toNodeRef(Node node) {
         checkArgument(MD_SAL_TYPE.equals(node.getType()));
         var nodeId = node.ID.checkInstanceOf(String)
@@ -76,12 +139,23 @@ public class NodeMapping {
         val nodePath = InstanceIdentifier.builder().node(Nodes).child(NODE_CLASS, nodeKey).toInstance();
         return new NodeRef(nodePath);
     }
-    
+
     public static def toNodeConnectorRef(NodeConnector nodeConnector) {
         val node = nodeConnector.node.toNodeRef();
         val nodePath = node.getValue() as InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node>
-        var nodeConnectorId = nodeConnector.ID.checkInstanceOf(String)
-        val connectorKey = new NodeConnectorKey(new NodeConnectorId(nodeConnectorId));
+        var NodeConnectorId nodeConnectorId
+        if (nodeConnector.ID.equals(NodeConnector.SPECIALNODECONNECTORID)) {
+            if (nodeConnector.type.equals(NodeConnector.NodeConnectorIDType.SWSTACK)) {
+                nodeConnectorId = nodePath.toNodeId.toLocalNodeConnectorId
+            } else if (nodeConnector.type.equals(NodeConnector.NodeConnectorIDType.HWPATH)) {
+                nodeConnectorId = nodePath.toNodeId.toNormalNodeConnectorId
+            } else if (nodeConnector.type.equals(NodeConnector.NodeConnectorIDType.CONTROLLER)) {
+                nodeConnectorId = nodePath.toNodeId.toControllerNodeConnectorId
+            }
+        } else {
+            nodeConnectorId = new NodeConnectorId(nodeConnector.ID.checkInstanceOf(String))
+        }
+        val connectorKey = new NodeConnectorKey(nodeConnectorId);
         val path = InstanceIdentifier.builder(nodePath).child(NODECONNECTOR_CLASS, connectorKey).toInstance();
         return new NodeConnectorRef(path);
     }
@@ -89,108 +163,195 @@ public class NodeMapping {
     public static def toADNode(NodeRef node) throws ConstructionException {
         return toADNode(node.getValue());
     }
-    
+
     public static def toADNodeConnectorProperties(NodeConnectorUpdated nc) {
-        val props = new java.util.HashSet<org.opendaylight.controller.sal.core.Property>();
         val fcncu = nc.getAugmentation(FlowCapableNodeConnectorUpdated)
-        if(fcncu != null) {
-            if(fcncu.currentFeature != null && fcncu.currentFeature.toAdBandwidth != null) {
+        if (fcncu != null) {
+            return fcncu.toADNodeConnectorProperties
+        }
+        return new HashSet<org.opendaylight.controller.sal.core.Property>();
+    }
+
+    public static def toADNodeConnectorProperties(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector nc) {
+        val fcnc = nc.getAugmentation(FlowCapableNodeConnector)
+        if (fcnc != null) {
+            return fcnc.toADNodeConnectorProperties
+        }
+        return new HashSet<org.opendaylight.controller.sal.core.Property>();
+    }
+
+    public static def toADNodeConnectorProperties(FlowNodeConnector fcncu) {
+        val props = new HashSet<org.opendaylight.controller.sal.core.Property>();
+        if (fcncu != null) {
+            if (fcncu.currentFeature != null && fcncu.currentFeature.toAdBandwidth != null) {
                 props.add(fcncu.currentFeature.toAdBandwidth)
             }
-            if(fcncu.advertisedFeatures != null && fcncu.advertisedFeatures.toAdAdvertizedBandwidth != null) {
+            if (fcncu.advertisedFeatures != null && fcncu.advertisedFeatures.toAdAdvertizedBandwidth != null) {
                 props.add(fcncu.advertisedFeatures.toAdAdvertizedBandwidth)
             }
-            if(fcncu.supported != null && fcncu.supported.toAdSupportedBandwidth != null) {
+            if (fcncu.supported != null && fcncu.supported.toAdSupportedBandwidth != null) {
                 props.add(fcncu.supported.toAdSupportedBandwidth)
             }
-            if(fcncu.peerFeatures != null && fcncu.peerFeatures.toAdPeerBandwidth != null) {
+            if (fcncu.peerFeatures != null && fcncu.peerFeatures.toAdPeerBandwidth != null) {
                 props.add(fcncu.peerFeatures.toAdPeerBandwidth)
             }
-            if(fcncu.name != null && fcncu.name.toAdName != null) {
+            if (fcncu.name != null && fcncu.name.toAdName != null) {
                 props.add(fcncu.name.toAdName)
             }
-            if(fcncu.configuration != null && fcncu.configuration.toAdConfig != null) {
+            if (fcncu.configuration != null && fcncu.configuration.toAdConfig != null) {
                 props.add(fcncu.configuration.toAdConfig)
             }
-            if(fcncu.state != null && fcncu.state.toAdState != null) {
+            if (fcncu.state != null && fcncu.state.toAdState != null) {
                 props.add(fcncu.state.toAdState)
             }
         }
         return props
     }
-    
+
     public static def toAdName(String name) {
         return new Name(name)
-    } 
-    
+    }
+
     public static def toAdConfig(PortConfig pc) {
         var Config config;
-        if(pc.PORTDOWN){
+        if (pc.PORTDOWN) {
             config = new Config(Config.ADMIN_DOWN)
         } else {
             config = new Config(Config.ADMIN_UP)
         }
         return config
     }
-    
+
     public static def toAdState(State s) {
         var org.opendaylight.controller.sal.core.State state
-        if(s.linkDown) {
+        if (s.linkDown) {
             state = new org.opendaylight.controller.sal.core.State(org.opendaylight.controller.sal.core.State.EDGE_DOWN)
         } else {
             state = new org.opendaylight.controller.sal.core.State(org.opendaylight.controller.sal.core.State.EDGE_UP)
         }
         return state
     }
-    
+
     public static def toAdBandwidth(PortFeatures pf) {
         var Bandwidth bw = null
-        if (pf.is_10mbHd || pf.is_10mbFd ) {
-            bw= new Bandwidth(Bandwidth.BW10Mbps)
-        } else if (pf.is_100mbHd || pf.is_100mbFd ) {
-            bw= new Bandwidth(Bandwidth.BW100Mbps)
-        } else if (pf.is_1gbHd || pf.is_1gbFd ) {
-            bw= new Bandwidth(Bandwidth.BW1Gbps)
-        } else if (pf.is_1gbFd ) {
-            bw= new Bandwidth(Bandwidth.BW10Gbps)
-        } else if ( pf.is_10gbFd ) {
-            bw= new Bandwidth(Bandwidth.BW10Gbps)
-        } else if ( pf.is_40gbFd ) {
-            bw= new Bandwidth(Bandwidth.BW40Gbps)
-        } else if ( pf.is_100gbFd ) {
-            bw= new Bandwidth(Bandwidth.BW100Gbps)
-        } else if ( pf.is_1tbFd ) {
-            bw= new Bandwidth(Bandwidth.BW1Tbps)
-        } 
+        if (pf.is_10mbHd || pf.is_10mbFd) {
+            bw = new Bandwidth(Bandwidth.BW10Mbps)
+        } else if (pf.is_100mbHd || pf.is_100mbFd) {
+            bw = new Bandwidth(Bandwidth.BW100Mbps)
+        } else if (pf.is_1gbHd || pf.is_1gbFd) {
+            bw = new Bandwidth(Bandwidth.BW1Gbps)
+        } else if (pf.is_1gbFd) {
+            bw = new Bandwidth(Bandwidth.BW10Gbps)
+        } else if (pf.is_10gbFd) {
+            bw = new Bandwidth(Bandwidth.BW10Gbps)
+        } else if (pf.is_40gbFd) {
+            bw = new Bandwidth(Bandwidth.BW40Gbps)
+        } else if (pf.is_100gbFd) {
+            bw = new Bandwidth(Bandwidth.BW100Gbps)
+        } else if (pf.is_1tbFd) {
+            bw = new Bandwidth(Bandwidth.BW1Tbps)
+        }
         return bw;
     }
-    
+
     public static def toAdAdvertizedBandwidth(PortFeatures pf) {
         var AdvertisedBandwidth abw
         val bw = pf.toAdBandwidth
-        if(bw != null) {
+        if (bw != null) {
             abw = new AdvertisedBandwidth(bw.value)
         }
         return abw
     }
-    
+
     public static def toAdSupportedBandwidth(PortFeatures pf) {
         var SupportedBandwidth sbw
         val bw = pf.toAdBandwidth
-        if(bw != null ) {
+        if (bw != null) {
             sbw = new SupportedBandwidth(bw.value)
         }
         return sbw
     }
-    
+
     public static def toAdPeerBandwidth(PortFeatures pf) {
         var PeerBandwidth pbw
         val bw = pf.toAdBandwidth
-        if(bw != null) {
+        if (bw != null) {
             pbw = new PeerBandwidth(bw.value)
         }
         return pbw
     }
-    
-    
+
+    public static def toADNodeProperties(NodeUpdated nu) {
+        val fcnu = nu.getAugmentation(FlowCapableNodeUpdated)
+        if (fcnu != null) {
+            return fcnu.toADNodeProperties(nu.id)
+        }
+        return new HashSet<org.opendaylight.controller.sal.core.Property>();
+
+    }
+
+    public static def toADNodeProperties(FlowNode fcnu, NodeId id) {
+        val props = new HashSet<org.opendaylight.controller.sal.core.Property>();
+        if (fcnu != null) {
+            props.add(toADTimestamp)
+
+            // props.add(fcnu.supportedActions.toADActions) - TODO
+            if (id != null) {
+                props.add(id.toADMacAddress)
+            }
+            if (fcnu.switchFeatures != null) {
+                if (fcnu.switchFeatures.maxTables != null) {
+                    props.add(fcnu.switchFeatures.maxTables.toADTables)
+                }
+                if (fcnu.switchFeatures.capabilities != null) {
+                    props.add(fcnu.switchFeatures.capabilities.toADCapabiliities)
+                }
+                if (fcnu.switchFeatures.maxBuffers != null) {
+                    props.add(fcnu.switchFeatures.maxBuffers.toADBuffers)
+                }
+            }
+        }
+        return props;
+    }
+
+    public static def toADTimestamp() {
+        val date = new Date();
+        val timestamp = new TimeStamp(date.time, "connectedSince")
+        return timestamp;
+    }
+
+    public static def toADMacAddress(NodeId id) {
+        return new MacAddress(Long.parseLong(id.value.replaceAll("openflow:", "")).longValue.bytesFromDpid)
+    }
+
+    public static def toADTables(Short tables) {
+        return new Tables(tables.byteValue)
+    }
+
+    public static def toADCapabiliities(List<Class<? extends FeatureCapability>> capabilities) {
+        var int b
+        for (capability : capabilities) {
+            if (capability.equals(FlowFeatureCapabilityFlowStats)) {
+                b = Capabilities.CapabilitiesType.FLOW_STATS_CAPABILITY.value.bitwiseOr(b)
+            } else if (capability.equals(FlowFeatureCapabilityTableStats)) {
+                b = Capabilities.CapabilitiesType.TABLE_STATS_CAPABILITY.value.bitwiseOr(b)
+            } else if (capability.equals(FlowFeatureCapabilityPortStats)) {
+                b = Capabilities.CapabilitiesType.PORT_STATS_CAPABILITY.value.bitwiseOr(b)
+            } else if (capability.equals(FlowFeatureCapabilityStp)) {
+                b = Capabilities.CapabilitiesType.STP_CAPABILITY.value.bitwiseOr(b)
+            } else if (capability.equals(FlowFeatureCapabilityIpReasm)) {
+                b = Capabilities.CapabilitiesType.IP_REASSEM_CAPABILITY.value.bitwiseOr(b)
+            } else if (capability.equals(FlowFeatureCapabilityQueueStats)) {
+                b = Capabilities.CapabilitiesType.QUEUE_STATS_CAPABILITY.value.bitwiseOr(b)
+            } else if (capability.equals(FlowFeatureCapabilityArpMatchIp)) {
+                b = Capabilities.CapabilitiesType.ARP_MATCH_IP_CAPABILITY.value.bitwiseOr(b)
+            }
+        }
+        return new Capabilities(b)
+    }
+
+    public static def toADBuffers(Long buffers) {
+        return new Buffers(buffers.intValue)
+    }
+
 }
index 37bb2778584dc6deb08add85d63eee4ca9489acd..46fd62f3f2790dbd7223b9cba53af42284c57ef1 100644 (file)
@@ -43,6 +43,7 @@ import org.opendaylight.controller.sal.action.SetVlanCfi;
 import org.opendaylight.controller.sal.action.SetVlanId;
 import org.opendaylight.controller.sal.action.SetVlanPcp;
 import org.opendaylight.controller.sal.action.SwPath;
+import org.opendaylight.controller.sal.core.Capabilities;
 import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.flowprogrammer.Flow;
 import org.opendaylight.controller.sal.match.Match;
@@ -85,6 +86,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.acti
 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.address.Address;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.address.address.Ipv4;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.address.address.Ipv6;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FeatureCapability;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCase;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType;
@@ -563,7 +565,7 @@ public class ToSalConversionsUtils {
         }
     }
 
-    private static byte[] bytesFrom(MacAddress address) {
+    public static byte[] bytesFrom(MacAddress address) {
         String[] mac = address.getValue().split(":");
         byte[] macAddress = new byte[6]; // mac.length == 6 bytes
         for (int i = 0; i < mac.length; i++) {
@@ -571,4 +573,15 @@ public class ToSalConversionsUtils {
         }
         return macAddress;
     }
+    
+    public static byte[] bytesFromDpid(long dpid) {
+        byte[] mac = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+
+        for (short i = 0; i < 6; i++) {
+            mac[5 - i] = (byte) dpid;
+            dpid >>= 8;
+        }
+
+        return mac;
+    }
 }
index 6c5c5db4190459d33047156954334380b3aa440a..bd2590f18b4dc5927acd8da2b1a9882faa731413 100644 (file)
@@ -1,5 +1,6 @@
 package org.opendaylight.controller.sal.compatibility.topology
 
+import org.opendaylight.controller.md.sal.binding.util.TypeSafeDataReader
 import org.opendaylight.controller.sal.binding.api.data.DataProviderService
 import org.opendaylight.controller.sal.topology.IPluginInTopologyService
 import org.opendaylight.controller.sal.topology.IPluginOutTopologyService
@@ -10,9 +11,6 @@ import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier
 
 import static extension org.opendaylight.controller.sal.compatibility.topology.TopologyMapping.*
-import java.util.List
-import org.opendaylight.controller.sal.topology.TopoEdgeUpdate
-import java.util.Collections
 
 class TopologyAdapter implements IPluginInTopologyService {
     
@@ -24,8 +22,9 @@ class TopologyAdapter implements IPluginInTopologyService {
     
     override sollicitRefresh() {
         val path = InstanceIdentifier.builder(NetworkTopology).child(Topology,new TopologyKey(new TopologyId("flow:1"))).toInstance;
-        val topology =  (dataService.readOperationalData(path) as Topology);
-        topologyPublisher.edgeUpdate(topology.toADEdgeUpdates)
+        val reader = TypeSafeDataReader.forReader(dataService)
+        val topology = reader.readOperationalData(path)
+        topologyPublisher.edgeUpdate(topology.toADEdgeUpdates(reader))
     }
     
 }
\ No newline at end of file
index abe9701dd4dc80e05e9bec8ec6ad24f2ee69f2ff..7d05ce60fa43c7fd3920dcbc59b1d6396ff159d9 100644 (file)
@@ -40,16 +40,16 @@ class TopologyCommitHandler implements DataCommitHandler<InstanceIdentifier<? ex
             val topology = reader.readOperationalData(topologyPath)
             val adds = FluentIterable.from(modification.createdOperationalData.entrySet)
                 .filter[value instanceof Link]
-                .transform[(value as Link).toAdEdge(topology).toTopoEdgeUpdate(UpdateType.ADDED)]
+                .transform[(value as Link).toAdEdge(topology).toTopoEdgeUpdate(UpdateType.ADDED,reader)]
                 .toList
             val updates = FluentIterable.from(modification.updatedOperationalData.entrySet)
                 .filter[!modification.createdOperationalData.containsKey(key) && (value instanceof Link)]
-                .transform[(value as Link).toAdEdge(topology).toTopoEdgeUpdate(UpdateType.ADDED)] // Evidently the ADSAL does not expect edge 'CHANGED"
+                .transform[(value as Link).toAdEdge(topology).toTopoEdgeUpdate(UpdateType.ADDED,reader)] // Evidently the ADSAL does not expect edge 'CHANGED"
                 .toList
             val removes = FluentIterable.from(modification.removedOperationalData)
                 .transform[reader.readOperationalData(it as InstanceIdentifier<DataObject>)]
                 .filter[it instanceof Link]
-                .transform[(it as Link).toAdEdge(topology).toTopoEdgeUpdate(UpdateType.REMOVED)]
+                .transform[(it as Link).toAdEdge(topology).toTopoEdgeUpdate(UpdateType.REMOVED,reader)]
                 .toList
             msg.addAll(adds)
             msg.addAll(updates)
index 1f0eeea7833edf465d9f6a1bfe2fc0ea55934d92..62983ccce477abec0a6c9a3a069b763c0911fdc9 100644 (file)
@@ -16,7 +16,10 @@ import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev130712.network.topology.topology.Link
 
 import static com.google.common.base.Preconditions.*
-import static org.opendaylight.controller.sal.compatibility.NodeMapping.*
+import static extension org.opendaylight.controller.sal.compatibility.NodeMapping.*
+import org.opendaylight.controller.md.sal.binding.util.TypeSafeDataReader
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector
 
 class TopologyMapping {
     
@@ -24,9 +27,9 @@ class TopologyMapping {
         throw new UnsupportedOperationException("Utility class. Instantiation is not allowed.");
     }
     
-    public static def toADEdgeUpdates(Topology topology) {
+    public static def toADEdgeUpdates(Topology topology,TypeSafeDataReader reader) {
         val List<TopoEdgeUpdate> result = new CopyOnWriteArrayList<TopoEdgeUpdate>()
-        return FluentIterable.from(topology.link).transform[toAdEdge(topology).toTopoEdgeUpdate].copyInto(result)
+        return FluentIterable.from(topology.link).transform[toAdEdge(topology).toTopoEdgeUpdate(reader)].copyInto(result)
     }
     
     public static def toAdEdge(Link link,Topology topology) {
@@ -35,12 +38,17 @@ class TopologyMapping {
         return new Edge(adSrc,adDst); 
     }
     
-    public static def toTopoEdgeUpdate(Edge e) {
-        return toTopoEdgeUpdate(e,UpdateType.ADDED)
+    public static def toTopoEdgeUpdate(Edge e,TypeSafeDataReader reader) {
+        return toTopoEdgeUpdate(e,UpdateType.ADDED,reader)
     }
     
-    public static def toTopoEdgeUpdate(Edge e,UpdateType type) {
-        return new TopoEdgeUpdate(e,Collections.emptySet,type)
+    public static def toTopoEdgeUpdate(Edge e,UpdateType type,TypeSafeDataReader reader) {
+        return new TopoEdgeUpdate(e,e.toAdEdgeProperties(reader),type)
+    }
+    
+    public static def toAdEdgeProperties(Edge e,TypeSafeDataReader reader) {
+        val nc = reader.readOperationalData(e.tailNodeConnector.toNodeConnectorRef.value as InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector>)
+        return nc.toADNodeConnectorProperties     
     }
     
     public static def toADNodeId(NodeId nodeId) {
index 13ffa3f91002121c17dc71abb1d748ffe90f906f..1c21effd05ac1c9e93f26b187b32760046b4390e 100644 (file)
             <artifactId>opendaylight-l2-types</artifactId>
             <version>2013.08.27.0</version>
         </dependency>
+        <dependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>model-inventory</artifactId>
+            <version>${project.version}</version>
+        </dependency>
     </dependencies>
     <packaging>bundle</packaging>
 </project>
index 1ed1b6827bdc6ace925576b207b7d818d27ac8b5..31736d2737dbcd7358ef264587de0910153afb63 100644 (file)
@@ -5,6 +5,7 @@ module opendaylight-match-types {
     import ietf-inet-types {prefix inet; revision-date "2010-09-24";}
     import ietf-yang-types {prefix yang; revision-date "2010-09-24";}
     import opendaylight-l2-types {prefix l2t;revision-date "2013-08-27";}
+    import opendaylight-inventory {prefix inv;revision-date "2013-08-19";}
 
     revision "2013-10-26" {
         description "Initial revision of macth types";
@@ -270,11 +271,11 @@ module opendaylight-match-types {
     
     grouping match {
         leaf in-port {
-            type uint32;
+            type inv:node-connector-id;
         }
         
         leaf in-phy-port {
-            type uint32;
+            type inv:node-connector-id;
         }
         
         container "metadata" {
index c5f1dddc344b0e239595d7ae55ac6aa3dbd1bf99..571e9d8df2a66f2ea7e48b7aebc03c7e4a338320 100644 (file)
@@ -19,7 +19,7 @@
 
     <properties>
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
-        <bundle.plugin.version>2.3.7</bundle.plugin.version>
+        <bundle.plugin.version>2.4.0</bundle.plugin.version>
     </properties>
 
     <modules>
@@ -40,7 +40,7 @@
                 <configuration>
                     <instructions>
                         <Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name>
-                        <Import-Package>*,org.opendaylight.yangtools.yang.binding.annotations</Import-Package>
+                        <Import-Package>org.opendaylight.yangtools.yang.binding.annotations, *</Import-Package>
                     </instructions>
                 </configuration>
             </plugin>
                                     <codeGeneratorClass>org.opendaylight.yangtools.yang.unified.doc.generator.maven.DocumentationGeneratorImpl</codeGeneratorClass>
                                     <outputBaseDir>target/site/models</outputBaseDir>
                                 </generator>
+                                <generator>
+                                    <codeGeneratorClass>org.opendaylight.yangtools.yang.wadl.generator.maven.WadlGenerator</codeGeneratorClass>
+                                    <outputBaseDir>target/site/models</outputBaseDir>
+                                </generator>
                             </codeGenerators>
                             <inspectDependencies>true</inspectDependencies>
                         </configuration>
index daa3914cf73fd717c63cb2c3e251dc175ffe1191..0a769921d80410742cb22b4ad7ee8cc0e9920f0a 100644 (file)
@@ -115,32 +115,32 @@ public class BindingIndependentConnector implements //
     public DataObject readOperationalData(InstanceIdentifier<? extends DataObject> path) {
         try {
             org.opendaylight.yangtools.yang.data.api.InstanceIdentifier biPath = mappingService.toDataDom(path);
-
             CompositeNode result = biDataService.readOperationalData(biPath);
-            Class<? extends DataObject> targetType = path.getTargetType();
-
-            if (Augmentation.class.isAssignableFrom(targetType)) {
-                path = mappingService.fromDataDom(biPath);
-                Class<? extends Augmentation<?>> augmentType = (Class<? extends Augmentation<?>>) targetType;
-                DataObject parentTo = mappingService.dataObjectFromDataDom(path, result);
-                if (parentTo instanceof Augmentable<?>) {
-                    return (DataObject) ((Augmentable) parentTo).getAugmentation(augmentType);
-                }
-
-            }
-            return mappingService.dataObjectFromDataDom(path, result);
-
+            return potentialAugmentationRead(path,biPath,result);
         } catch (DeserializationException e) {
             throw new IllegalStateException(e);
         }
     }
 
+    private DataObject potentialAugmentationRead(InstanceIdentifier<? extends DataObject> path, org.opendaylight.yangtools.yang.data.api.InstanceIdentifier biPath, CompositeNode result) throws DeserializationException {
+        Class<? extends DataObject> targetType = path.getTargetType();
+        if (Augmentation.class.isAssignableFrom(targetType)) {
+            path = mappingService.fromDataDom(biPath);
+            Class<? extends Augmentation<?>> augmentType = (Class<? extends Augmentation<?>>) targetType;
+            DataObject parentTo = mappingService.dataObjectFromDataDom(path, result);
+            if (parentTo instanceof Augmentable<?>) {
+                return (DataObject) ((Augmentable) parentTo).getAugmentation(augmentType);
+            }
+        }
+        return mappingService.dataObjectFromDataDom(path, result);
+    }
+
     @Override
     public DataObject readConfigurationData(InstanceIdentifier<? extends DataObject> path) {
         try {
             org.opendaylight.yangtools.yang.data.api.InstanceIdentifier biPath = mappingService.toDataDom(path);
             CompositeNode result = biDataService.readConfigurationData(biPath);
-            return mappingService.dataObjectFromDataDom(path, result);
+            return potentialAugmentationRead(path,biPath,result);
         } catch (DeserializationException e) {
             throw new IllegalStateException(e);
         }
index 96d0361b1dd5194e9665ab89a80c774e64d5cb4a..d9b16af469727f80e66d608dfb576a936ddfa8c9 100644 (file)
@@ -12,6 +12,8 @@ import org.opendaylight.controller.sal.binding.api.data.DataChangeListener;
 import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnectorBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.flow.node.SupportedActions;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.flow.node.SupportedActionsBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.flow.node.supported.actions.ActionType;
@@ -130,8 +132,60 @@ public class PutAugmentationTest extends AbstractDataServiceTest implements Data
         assertBindingIndependentVersion(NODE_INSTANCE_ID_BI);
         testNodeRemove();
     }
+    
+    @Test
+    public void putNodeWithAugmentation() throws Exception {
+        
+        NodeBuilder nodeBuilder = new NodeBuilder();
+        nodeBuilder.setId(new NodeId(NODE_ID));
+        nodeBuilder.setKey(NODE_KEY);
+        FlowCapableNodeBuilder fnub = new FlowCapableNodeBuilder();
+        fnub.setHardware("Hardware Foo");
+        fnub.setManufacturer("Manufacturer Foo");
+        fnub.setSerialNumber("Serial Foo");
+        fnub.setDescription("Description Foo");
+        fnub.setSoftware("JUnit emulated");
+        FlowCapableNode fnu = fnub.build();
+        
+        nodeBuilder.addAugmentation(FlowCapableNode.class, fnu);
+        DataModificationTransaction baseTransaction = baDataService.beginTransaction();
+        baseTransaction.putOperationalData(NODE_INSTANCE_ID_BA, nodeBuilder.build());
+        RpcResult<TransactionStatus> result = baseTransaction.commit().get();
+        assertEquals(TransactionStatus.COMMITED, result.getResult());
+        
+        FlowCapableNode readedAugmentation = (FlowCapableNode) baDataService.readOperationalData(InstanceIdentifier.builder(NODE_INSTANCE_ID_BA).augmentation(FlowCapableNode.class).toInstance());
+        assertNotNull(readedAugmentation);
+        assertEquals(fnu.getHardware(), readedAugmentation.getHardware());
+        
+        testPutNodeConnectorWithAugmentation();
+        testNodeRemove();
+    }
 
     
+    private void testPutNodeConnectorWithAugmentation() throws Exception {
+        NodeConnectorKey ncKey = new NodeConnectorKey(new NodeConnectorId("test:0:0"));
+        InstanceIdentifier<NodeConnector> ncPath = InstanceIdentifier.builder(NODE_INSTANCE_ID_BA)
+        .child(NodeConnector.class, ncKey).toInstance();
+        InstanceIdentifier<FlowCapableNodeConnector> ncAugmentPath = InstanceIdentifier.builder(ncPath)
+        .augmentation(FlowCapableNodeConnector.class).toInstance();
+        
+        NodeConnectorBuilder nc = new NodeConnectorBuilder();
+        nc.setKey(ncKey);
+        
+        FlowCapableNodeConnectorBuilder fncb = new FlowCapableNodeConnectorBuilder();
+        fncb.setName("Baz");
+        nc.addAugmentation(FlowCapableNodeConnector.class, fncb.build());
+        
+        DataModificationTransaction baseTransaction = baDataService.beginTransaction();
+        baseTransaction.putOperationalData(ncPath, nc.build());
+        RpcResult<TransactionStatus> result = baseTransaction.commit().get();
+        assertEquals(TransactionStatus.COMMITED, result.getResult());
+        
+        FlowCapableNodeConnector readedAugmentation = (FlowCapableNodeConnector) baDataService.readOperationalData(ncAugmentPath);
+        assertNotNull(readedAugmentation);
+        assertEquals(fncb.getName(), readedAugmentation.getName());
+    }
+
     private void testNodeRemove() throws Exception {
         DataModificationTransaction transaction = baDataService.beginTransaction();
         transaction.removeOperationalData(NODE_INSTANCE_ID_BA);
index fb7872f8bcd4e1efdf27be0183fd20176651ac33..8b1bdef8ba71b9be2f72d8d9158a412d9d79a84e 100644 (file)
@@ -43,7 +43,7 @@ class JsonMapper {
 
     private final Set<LeafListSchemaNode> foundLeafLists = new HashSet<>();
     private final Set<ListSchemaNode> foundLists = new HashSet<>();
-    private final Logger logger = LoggerFactory.getLogger(JsonMapper.class); 
+    private final Logger logger = LoggerFactory.getLogger(JsonMapper.class);
 
     public void write(JsonWriter writer, CompositeNode data, DataNodeContainer schema) throws IOException {
         Preconditions.checkNotNull(writer);
@@ -184,16 +184,23 @@ class JsonMapper {
 
         TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(type);
 
+        if (node.getValue() == null && !(baseType instanceof EmptyTypeDefinition)) {
+            logger.debug("While generationg JSON output null value was found for type "
+                    + baseType.getClass().getSimpleName() + ".");
+        }
+
         // TODO check InstanceIdentifierTypeDefinition
         if (baseType instanceof IdentityrefTypeDefinition) {
             if (node.getValue() instanceof QName) {
                 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType).serialize(node.getValue());
                 IdentityValue valueFromDTO = valueDTO.getValuesWithNamespaces().get(0);
-                String moduleName = ControllerContext.getInstance().findModuleByNamespace(URI.create(valueFromDTO.getNamespace()));
+                String moduleName = ControllerContext.getInstance().findModuleByNamespace(
+                        URI.create(valueFromDTO.getNamespace()));
                 writer.value(moduleName + ":" + valueFromDTO.getValue());
             } else {
                 logger.debug("Value of " + baseType.getQName().getNamespace() + ":"
-                        + baseType.getQName().getLocalName() + " is not instance of " + QName.class + " but is " + node.getValue().getClass());
+                        + baseType.getQName().getLocalName() + " is not instance of " + QName.class + " but is "
+                        + node.getValue().getClass());
                 writer.value(String.valueOf(node.getValue()));
             }
         } else if (baseType instanceof DecimalTypeDefinition || baseType instanceof IntegerTypeDefinition
index 0e9bad046b1f1ba52233ecaff2da40b8dcca5126..0dd4668a749fdd5b50af9e8e72a26d7a4636d009 100644 (file)
@@ -1,14 +1,60 @@
 package org.opendaylight.controller.sal.rest.impl;
 
 import javax.activation.UnsupportedDataTypeException;
+
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.util.Leafref;
 import org.w3c.dom.Document;
 
+import com.google.common.base.Optional;
 
 public class XmlMapper {
+    private static final LeafrefCodecImpl LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl(
+            Optional.<LeafrefTypeDefinition> absent());
+
+    private static class LeafrefCodecImpl extends TypeDefinitionAwareCodec<Object, LeafrefTypeDefinition> implements
+            LeafrefCodec<String> {
+
+        protected LeafrefCodecImpl(Optional<LeafrefTypeDefinition> typeDef) {
+            super(typeDef, Object.class);
+        }
+
+        @Override
+        public String serialize(Object data) {
+            return String.valueOf(data);
+        }
+
+        @Override
+        public Object deserialize(String data) {
+            return data;
+        }
+    }
+
+    private static class XmlCodecProviderImpl implements XmlCodecProvider {
+        @Override
+        public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
+            TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = TypeDefinitionAwareCodec
+                    .from(baseType);
+
+            if (codec == null) {
+                if (baseType instanceof Leafref) {
+                    return LEAFREF_DEFAULT_CODEC;
+                }
+            }
+            return codec;
+        }
+    }
+
+    private static final XmlCodecProvider XML_CODEC_PROVIDER_IMPL = new XmlCodecProviderImpl();
+
     public Document write(CompositeNode data, DataNodeContainer schema) throws UnsupportedDataTypeException {
-        return XmlDocumentUtils.toDocument(data, schema, XmlDocumentUtils.defaultValueCodecProvider());
+        return XmlDocumentUtils.toDocument(data, schema, XML_CODEC_PROVIDER_IMPL);
     }
 }
index 450ba02b56071412d8aff89030db7b221a128605..40fba88356e89f924e6c2903e7460102a74d818c 100644 (file)
@@ -19,16 +19,16 @@ public class RestCodec {
 
     private RestCodec() {
     }
-    
+
     public static final Codec<Object, Object> from(TypeDefinition<?> typeDefinition) {
         return new ObjectCodec(typeDefinition);
     }
-    
+
     @SuppressWarnings("rawtypes")
     public static final class ObjectCodec implements Codec<Object, Object> {
 
         private final Logger logger = LoggerFactory.getLogger(RestCodec.class);
-        
+
         public static final Codec IDENTITYREF_DEFAULT_CODEC = new IdentityrefCodecImpl();
         public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
 
@@ -37,7 +37,7 @@ public class RestCodec {
         private ObjectCodec(TypeDefinition<?> typeDefinition) {
             type = RestUtil.resolveBaseTypeFrom(typeDefinition);
         }
-        
+
         @SuppressWarnings("unchecked")
         @Override
         public Object deserialize(Object input) {
@@ -47,16 +47,21 @@ public class RestCodec {
                 } else if (type instanceof LeafrefTypeDefinition) {
                     return LEAFREF_DEFAULT_CODEC.deserialize(input);
                 } else {
-                    TypeDefinitionAwareCodec<Object,? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec.from(type);
+                    TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec
+                            .from(type);
                     if (typeAwarecodec != null) {
                         return typeAwarecodec.deserialize(String.valueOf(input));
                     } else {
-                        logger.debug("Codec for type \"" + type.getQName().getLocalName() + "\" is not implemented yet.");
+                        logger.debug("Codec for type \"" + type.getQName().getLocalName()
+                                + "\" is not implemented yet.");
                         return null;
                     }
                 }
-            } catch (ClassCastException e) { // TODO remove this catch when everyone use codecs
-                logger.error("ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input), e);
+            } catch (ClassCastException e) { // TODO remove this catch when
+                                             // everyone use codecs
+                logger.error(
+                        "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
+                        e);
                 return input;
             }
         }
@@ -70,22 +75,27 @@ public class RestCodec {
                 } else if (type instanceof LeafrefTypeDefinition) {
                     return LEAFREF_DEFAULT_CODEC.serialize(input);
                 } else {
-                    TypeDefinitionAwareCodec<Object,? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec.from(type);
+                    TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec
+                            .from(type);
                     if (typeAwarecodec != null) {
                         return typeAwarecodec.serialize(input);
                     } else {
-                        logger.debug("Codec for type \"" + type.getQName().getLocalName() + "\" is not implemented yet.");
+                        logger.debug("Codec for type \"" + type.getQName().getLocalName()
+                                + "\" is not implemented yet.");
                         return null;
                     }
                 }
-            } catch (ClassCastException e) { // TODO remove this catch when everyone use codecs
-                logger.error("ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input), e);
+            } catch (ClassCastException e) { // TODO remove this catch when
+                                             // everyone use codecs
+                logger.error(
+                        "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
+                        e);
                 return input;
             }
         }
-        
+
     }
-    
+
     public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
 
         @Override
@@ -105,7 +115,7 @@ public class RestCodec {
         }
 
     }
-    
+
     public static class LeafrefCodecImpl implements LeafrefCodec<String> {
 
         @Override
@@ -117,7 +127,7 @@ public class RestCodec {
         public Object deserialize(String data) {
             return data;
         }
-        
+
     }
-    
+
 }
@@ -1,22 +1,44 @@
 package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
 
 import java.io.IOException;
 import java.io.StringReader;
 import java.util.Map;
 import java.util.Set;
 
+import javax.ws.rs.WebApplicationException;
+
+import org.junit.BeforeClass;
 import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
+import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
 import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
-import org.opendaylight.controller.sal.restconf.impl.test.structures.*;
-import org.opendaylight.yangtools.yang.data.api.*;
+import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
+import org.opendaylight.controller.sal.restconf.impl.test.structures.Cont;
+import org.opendaylight.controller.sal.restconf.impl.test.structures.Lf;
+import org.opendaylight.controller.sal.restconf.impl.test.structures.LfLst;
+import org.opendaylight.controller.sal.restconf.impl.test.structures.Lst;
+import org.opendaylight.controller.sal.restconf.impl.test.structures.LstItem;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.ModifyAction;
+import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 
 import com.google.gson.stream.JsonReader;
 import com.google.gson.stream.JsonToken;
 
-public class ToJsonBasicYangTypesTest {
+public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
+
+    @BeforeClass
+    public static void initialize() {
+        dataLoad("/cnsn-to-json/simple-yang-types", 1, "simple-yang-types", "cont1");
+    }
 
     /**
      * Test of json output when as input are specified composite node with empty
@@ -24,9 +46,16 @@ public class ToJsonBasicYangTypesTest {
      */
     @Test
     public void compositeNodeAndYangWithJsonReaderEmptyDataTest() {
-        String jsonOutput = TestUtils.convertCompositeNodeDataAndYangToJson(prepareCompositeNodeWithEmpties(),
-                "/cnsn-to-json/simple-yang-types", "/cnsn-to-json/simple-yang-types/xml", "simple-yang-types", "cont1");
-        verifyJsonOutputForEmpty(jsonOutput);
+        CompositeNode compositeNode = prepareCompositeNodeWithEmpties();
+        TestUtils.normalizeCompositeNode(compositeNode, modules, searchedModuleName + ":" + searchedDataSchemaName);
+        String jsonOutput = null;
+        try {
+            jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode,
+                    StructuredDataToJsonProvider.INSTANCE);
+        } catch (WebApplicationException | IOException e) {
+        }
+
+        verifyJsonOutputForEmptyData(jsonOutput);
     }
 
     /**
@@ -35,13 +64,21 @@ public class ToJsonBasicYangTypesTest {
      */
     @Test
     public void xmlAndYangTypesWithJsonReaderTest() {
-        String jsonOutput = TestUtils.convertCompositeNodeDataAndYangToJson(
-                TestUtils.loadCompositeNode("/cnsn-to-json/simple-yang-types/xml/data.xml"),
-                "/cnsn-to-json/simple-yang-types", "/cnsn-to-json/simple-yang-types/xml", "simple-yang-types", "cont1");
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-yang-types/xml/data.xml",
+                XmlToCompositeNodeProvider.INSTANCE);
+        TestUtils.normalizeCompositeNode(compositeNode, modules, searchedModuleName + ":" + searchedDataSchemaName);
+        String jsonOutput = null;
+        try {
+            jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode,
+                    StructuredDataToJsonProvider.INSTANCE);
+        } catch (WebApplicationException | IOException e) {
+        }
+
         verifyJsonOutput(jsonOutput);
     }
 
-    private void verifyJsonOutputForEmpty(String jsonOutput) {
+    private void verifyJsonOutputForEmptyData(String jsonOutput) {
+        assertNotNull(jsonOutput);
         StringReader strReader = new StringReader(jsonOutput);
         JsonReader jReader = new JsonReader(strReader);
 
@@ -60,6 +97,7 @@ public class ToJsonBasicYangTypesTest {
     }
 
     private void verifyJsonOutput(String jsonOutput) {
+        assertNotNull(jsonOutput);
         StringReader strReader = new StringReader(jsonOutput);
         JsonReader jReader = new JsonReader(strReader);
 
@@ -8,11 +8,13 @@ import javax.ws.rs.WebApplicationException;
 
 import org.junit.BeforeClass;
 import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
+import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
 import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
 import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
-public class ToJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader {
+public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader {
 
     @BeforeClass
     public static void initialization() {
@@ -111,10 +113,11 @@ public class ToJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     private void testWrapper(String xmlPath, String pathToSchemaNode) {
-        CompositeNode compNode = TestUtils.loadCompositeNode(xmlPath);
-        TestUtils.normalizeCompositeNode(compNode, modules, dataSchemaNode, pathToSchemaNode);
+        CompositeNode compNode = TestUtils.readInputToCnSn(xmlPath, XmlToCompositeNodeProvider.INSTANCE);
+        TestUtils.normalizeCompositeNode(compNode, modules, pathToSchemaNode);
         try {
-            TestUtils.writeCompNodeWithSchemaContextToJson(compNode, modules, dataSchemaNode);
+            TestUtils.writeCompNodeWithSchemaContextToOutput(compNode, modules, dataSchemaNode,
+                    StructuredDataToJsonProvider.INSTANCE);
         } catch (WebApplicationException | IOException e) {
             // shouldn't end here
             assertTrue(false);
 package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
 
 import java.io.IOException;
 import java.io.StringReader;
-import java.math.BigDecimal;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
 
 import javax.ws.rs.WebApplicationException;
-import javax.xml.bind.DatatypeConverter;
 
+import org.junit.BeforeClass;
 import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
+import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
 import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.*;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
 import com.google.gson.stream.JsonReader;
 import com.google.gson.stream.JsonToken;
 
-public class ToJsonBasicDataTypesTest {
+public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader {
+
+    @BeforeClass
+    public static void initialize() {
+        dataLoad("/cnsn-to-json/simple-data-types");
+    }
 
     @Test
     public void simpleYangDataTest() {
-        String jsonOutput = "";
-        CompositeNode compositeNode = TestUtils.loadCompositeNode("/cnsn-to-json/simple-data-types/xml/data.xml");
 
-        Set<Module> modules = TestUtils.resolveModules("/cnsn-to-json/simple-data-types");
-        assertEquals(1, modules.size());
-        Module module = TestUtils.resolveModule(null, modules);
-        assertNotNull(module);
-        DataSchemaNode dataSchemaNode = TestUtils.resolveDataSchemaNode(module, null);
-        assertNotNull(dataSchemaNode);
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml",
+                XmlToCompositeNodeProvider.INSTANCE);
 
-        TestUtils.normalizeCompositeNode(compositeNode, modules, dataSchemaNode, "simple-data-types:cont");
+        String jsonOutput = null;
+
+        TestUtils.normalizeCompositeNode(compositeNode, modules, "simple-data-types:cont");
 
         try {
-            jsonOutput = TestUtils.writeCompNodeWithSchemaContextToJson(compositeNode, modules, dataSchemaNode);
+            jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode,
+                    StructuredDataToJsonProvider.INSTANCE);
         } catch (WebApplicationException | IOException e) {
-            assertTrue(false); // shouldn't get here
         }
+        assertNotNull(jsonOutput);
 
-        System.out.println(jsonOutput);
         verifyJsonOutput(jsonOutput);
     }
 
-    private CompositeNode prepareData() {
-        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont"), null, null,
-                ModifyAction.CREATE, null);
-
-        List<Node<?>> childNodes = new ArrayList<>();
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfnint8Min"), cont, (byte) -128,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfnint8Max"), cont, (byte) 127,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfnint16Min"), cont, (short) -32768,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfnint16Max"), cont, (short) 32767,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfnint32Min"), cont,
-                (int) -2147483648, ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfnint32Max"), cont, (int) 2147483647,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfnint64Min"), cont, new Long(
-                "-9223372036854775807"), ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfnint64Max"), cont, new Long(
-                "9223372036854775807"), ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfnuint8Max"), cont, (short) 255,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfnuint16Max"), cont, (int) 65535,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfnuint32Max"), cont, new Long(
-                "4294967295"), ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfstr"), cont, "lfstr",
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfstr1"), cont, "",
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfbool1"), cont, Boolean.TRUE,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfbool2"), cont, Boolean.FALSE,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfdecimal1"), cont, new BigDecimal(
-                "43.32"), ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfdecimal2"), cont, new BigDecimal(
-                "-0.43"), ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfdecimal3"), cont, new BigDecimal(
-                "43"), ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfdecimal4"), cont, new BigDecimal(
-                "43E3"), ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfdecimal6"), cont, new BigDecimal(
-                "33.12345"), ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfenum"), cont, "enum3",
-                ModifyAction.CREATE, null));
-
-        HashSet<String> bits = new HashSet<String>();
-        bits.add("bit3");
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfbits"), cont, bits,
-                ModifyAction.CREATE, null));
-
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfbinary"), cont, DatatypeConverter
-                .parseBase64Binary("AAaacdabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"),
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfempty"), cont, null,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfunion1"), cont, (int) 324,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfunion2"), cont, new BigDecimal(
-                "33.3"), ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfunion3"), cont, "55",
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfunion4"), cont, Boolean.TRUE,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfunion5"), cont, "true",
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfunion6"), cont, "false",
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfunion7"), cont, null,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfunion8"), cont, "",
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfunion9"), cont, "",
-                ModifyAction.CREATE, null));
-
-        HashSet<String> bits2 = new HashSet<String>();
-        bits2.add("bt1");
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfunion10"), cont, bits2,
-                ModifyAction.CREATE, null));
-
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfunion11"), cont, (short) 33,
-                ModifyAction.CREATE, null));
-        childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfunion12"), cont, Boolean.FALSE,
-                ModifyAction.CREATE, null));
-        try {
-            childNodes.add(NodeFactory.createMutableSimpleNode(TestUtils.buildQName("identityref1"), cont, new QName(
-                    new URI("simple:data:types"), "iden"), ModifyAction.CREATE, null));
-        } catch (URISyntaxException e) {
-        }
-
-        cont.getChildren().addAll(childNodes);
-
-        cont.init();
-
-        return cont;
-    }
-
     private void verifyJsonOutput(String jsonOutput) {
         StringReader strReader = new StringReader(jsonOutput);
         JsonReader jReader = new JsonReader(strReader);
@@ -178,7 +82,6 @@ public class ToJsonBasicDataTypesTest {
     private void jsonReadContElements(JsonReader jReader) throws IOException {
         jReader.beginObject();
         List<String> loadedLfs = new ArrayList<>();
-        boolean exceptForDecimal5Raised = false;
         boolean enumChecked = false;
         boolean bitsChecked = false;
         boolean lfdecimal6Checked = false;
@@ -190,7 +93,6 @@ public class ToJsonBasicDataTypesTest {
         boolean lfbool2Checked = false;
         boolean lfstrChecked = false;
         boolean lfbinaryChecked = false;
-        // boolean lfref1Checked = false;
         boolean lfemptyChecked = false;
         boolean lfstr1Checked = false;
         boolean lfidentityrefChecked = false;
@@ -201,11 +103,7 @@ public class ToJsonBasicDataTypesTest {
             try {
                 peek = jReader.peek();
             } catch (IOException e) {
-                if (keyName.equals("lfdecimal5")) {
-                    exceptForDecimal5Raised = true;
-                } else {
-                    assertTrue("Key " + keyName + " has incorrect value for specifed type", false);
-                }
+                assertTrue("Key " + keyName + " has incorrect value for specifed type", false);
             }
 
             if (keyName.startsWith("lfnint") || keyName.startsWith("lfnuint")) {
@@ -11,12 +11,14 @@ import javax.ws.rs.WebApplicationException;
 
 import org.junit.BeforeClass;
 import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
 import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
 import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
+import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.*;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 
-public class ToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader {
+public class CnSnToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader {
 
     @BeforeClass
     public static void initialization() {
@@ -27,7 +29,9 @@ public class ToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader {
     public void identityrefToJsonTest() {
         String json = null;
         try {
-            json = TestUtils.writeCompNodeWithSchemaContextToJson(prepareCompositeNode(), modules, dataSchemaNode);
+            QName valueAsQname = TestUtils.buildQName("name_test", "identityref:module", "2013-12-2");
+            json = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(valueAsQname), modules,
+                    dataSchemaNode, StructuredDataToJsonProvider.INSTANCE);
         } catch (WebApplicationException | IOException e) {
             // shouldn't end here
             assertTrue(false);
@@ -40,15 +44,35 @@ public class ToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader {
         assertTrue(mtch.matches());
     }
 
-    private CompositeNode prepareCompositeNode() {
+    @Test
+    public void identityrefToJsonWithoutQNameTest() {
+        String json = null;
+        try {
+            String value = "not q name value";
+            json = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(value), modules,
+                    dataSchemaNode, StructuredDataToJsonProvider.INSTANCE);
+        } catch (WebApplicationException | IOException e) {
+            // shouldn't end here
+            assertTrue(false);
+        }
+        System.out.println(json);
+        assertNotNull(json);
+        Pattern ptrn = Pattern.compile(".*\"lf1\"\\p{Space}*:\\p{Space}*\"not q name value\".*", Pattern.DOTALL);
+        Matcher mtch = ptrn.matcher(json);
+
+        assertTrue(mtch.matches());
+    }
+
+    private CompositeNode prepareCompositeNode(Object value) {
         MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont"), null, null,
                 ModifyAction.CREATE, null);
         MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont1"), cont, null,
                 ModifyAction.CREATE, null);
         cont.getChildren().add(cont1);
 
-        MutableSimpleNode<?> lf1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1"), cont1,
-                TestUtils.buildQName("name_test", "identityref:module", "2013-12-2"), ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1"), cont1, value,
+                ModifyAction.CREATE, null);
+
         cont1.getChildren().add(lf1);
         cont1.init();
         cont.init();
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java
new file mode 100644 (file)
index 0000000..6b57762
--- /dev/null
@@ -0,0 +1,170 @@
+package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+
+import javax.activation.UnsupportedDataTypeException;
+import javax.ws.rs.WebApplicationException;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
+import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
+import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
+import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.Status;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.UsesNode;
+import org.opendaylight.yangtools.yang.model.api.YangNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class CnSnToJsonIncorrectTopLevelTest extends YangAndXmlAndDataSchemaLoader {
+
+    private static final Logger LOG = LoggerFactory.getLogger(CnSnToJsonIncorrectTopLevelTest.class);
+
+    @BeforeClass
+    public static void initialize() {
+        dataLoad("/cnsn-to-json/simple-data-types");
+    }
+
+    private class IncorrectDataSchema implements DataSchemaNode, DataNodeContainer {
+
+        @Override
+        public String getDescription() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public SchemaPath getPath() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public QName getQName() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public String getReference() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public Status getStatus() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public List<UnknownSchemaNode> getUnknownSchemaNodes() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public Set<DataSchemaNode> getChildNodes() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public DataSchemaNode getDataChildByName(QName arg0) {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public DataSchemaNode getDataChildByName(String arg0) {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public Set<GroupingDefinition> getGroupings() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public Set<TypeDefinition<?>> getTypeDefinitions() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public Set<UsesNode> getUses() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public ConstraintDefinition getConstraints() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public YangNode getParent() {
+            // TODO Auto-generated method stub
+            return null;
+        }
+
+        @Override
+        public boolean isAddedByUses() {
+            // TODO Auto-generated method stub
+            return false;
+        }
+
+        @Override
+        public boolean isAugmenting() {
+            // TODO Auto-generated method stub
+            return false;
+        }
+
+        @Override
+        public boolean isConfiguration() {
+            // TODO Auto-generated method stub
+            return false;
+        }
+
+    }
+
+    @Test
+    public void incorrectTopLevelElementTest() {
+
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml", XmlToCompositeNodeProvider.INSTANCE);
+        DataSchemaNode incorrectDataSchema = null;
+        incorrectDataSchema = new IncorrectDataSchema();
+
+        TestUtils.normalizeCompositeNode(compositeNode, modules, "simple-data-types:cont");
+
+        boolean exceptionRaised = false;
+        try {
+            TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, incorrectDataSchema,
+                    StructuredDataToJsonProvider.INSTANCE);
+        } catch (UnsupportedDataTypeException e) {
+            exceptionRaised = true;
+        } catch (WebApplicationException | IOException e) {
+            LOG.error("WebApplicationException or IOException was raised");
+        }
+
+        assertTrue(exceptionRaised);
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java
new file mode 100644 (file)
index 0000000..3215e81
--- /dev/null
@@ -0,0 +1,103 @@
+package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.ws.rs.WebApplicationException;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
+import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
+import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
+import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+
+/**
+ * 
+ * All tests are commented now because leafref isn't supported now
+ * 
+ */
+
+public class CnSnToJsonLeafrefType extends YangAndXmlAndDataSchemaLoader {
+
+    @BeforeClass
+    public static void initialization() {
+        dataLoad("/cnsn-to-json/leafref", 2, "main-module", "cont");
+    }
+
+    @Test
+    public void leafrefAbsolutePathToExistingLeafTest() {
+        String json = toJson("/cnsn-to-json/leafref/xml/data_absolut_ref_to_existing_leaf.xml");
+        validateJson(".*\"lf3\":\\p{Blank}*\"true\".*", json);
+    }
+
+    @Test
+    public void leafrefRelativePathToExistingLeafTest() {
+        String json = toJson("/cnsn-to-json/leafref/xml/data_relativ_ref_to_existing_leaf.xml");
+        validateJson(".*\"lf2\":\\p{Blank}*\"121\".*", json);
+    }
+
+    /**
+     * Tests case when reference to not existing element is present. In this
+     * case value from single node is printed as string.
+     */
+    @Test
+    public void leafrefToNonExistingLeafTest() {
+        String json = toJson("/cnsn-to-json/leafref/xml/data_ref_to_non_existing_leaf.xml");
+        validateJson(".*\"lf5\":\\p{Blank}*\"137\".*", json);
+    }
+
+    /**
+     * Tests case when non leaf element is referenced. In this case value from
+     * single node is printed as string.
+     */
+    @Test
+    public void leafrefToNotLeafTest() {
+        String json = toJson("/cnsn-to-json/leafref/xml/data_ref_to_not_leaf.xml");
+        validateJson(".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lf6\":\\p{Blank}*\"44.33\".*", json);
+    }
+
+    /**
+     * Tests case when leaflist element is refers to leaf.
+     */
+    @Test
+    public void leafrefFromLeafListToLeafTest() {
+        String json = toJson("/cnsn-to-json/leafref/xml/data_relativ_ref_from_leaflist_to_existing_leaf.xml");
+        validateJson(
+                ".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lflst1\":\\p{Blank}*.*\"345\",\\p{Space}*\"346\",\\p{Space}*\"347\".*",
+                json);
+    }
+
+    /**
+     * Tests case when leaflist element is refers to leaf.
+     */
+    @Test
+    public void leafrefFromLeafrefToLeafrefTest() {
+        String json = toJson("/cnsn-to-json/leafref/xml/data_from_leafref_to_leafref.xml");
+        validateJson(".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lf7\":\\p{Blank}*\"200\".*", json);
+    }
+
+    private void validateJson(String regex, String value) {
+        assertNotNull(value);
+        Pattern ptrn = Pattern.compile(regex, Pattern.DOTALL);
+        Matcher mtch = ptrn.matcher(value);
+        assertTrue(mtch.matches());
+    }
+
+    private String toJson(String xmlDataPath) {
+        try {
+            CompositeNode compositeNode = TestUtils.readInputToCnSn(xmlDataPath, XmlToCompositeNodeProvider.INSTANCE);
+            TestUtils.normalizeCompositeNode(compositeNode, modules, searchedModuleName + ":" + searchedDataSchemaName);
+            return TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode,
+                    StructuredDataToJsonProvider.INSTANCE);
+        } catch (WebApplicationException | IOException e) {
+        }
+        return "";
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonNotExistingLeafTypeTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonNotExistingLeafTypeTest.java
new file mode 100644 (file)
index 0000000..e5a317e
--- /dev/null
@@ -0,0 +1,72 @@
+package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Set;
+
+import javax.ws.rs.WebApplicationException;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
+import org.opendaylight.controller.sal.restconf.impl.test.*;
+import org.opendaylight.yangtools.yang.data.api.*;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class CnSnToJsonNotExistingLeafTypeTest extends YangAndXmlAndDataSchemaLoader {
+
+    private static final Logger LOG = LoggerFactory.getLogger(CnSnToJsonNotExistingLeafTypeTest.class);
+
+    @BeforeClass
+    public static void initialize() {
+        dataLoad("/cnsn-to-json/simple-data-types");
+    }
+
+    @Test
+    public void incorrectTopLevelElementTest() {
+
+        String jsonOutput = null;
+        try {
+            jsonOutput = TestUtils
+                    .writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
+                            (Set<Module>) Collections.EMPTY_SET, prepareDataSchemaNode(),
+                            StructuredDataToJsonProvider.INSTANCE);
+        } catch (WebApplicationException | IOException e) {
+            LOG.error("WebApplicationException or IOException was raised");
+        }
+        assertNotNull(jsonOutput);
+        assertTrue(jsonOutput.contains("\"lf1\": \"\""));
+    }
+
+    private CompositeNode prepareCompositeNode() {
+        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont", "simple:uri", "2012-12-17"), null, null, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf1", "simple:uri", "2012-12-17"), cont, "any value", ModifyAction.CREATE, null);
+        cont.getChildren().add(lf1);
+        cont.init();
+        return cont;
+    }
+
+    private DataSchemaNode prepareDataSchemaNode() {
+        ContainerSchemaNodeBuilder contBuild = new ContainerSchemaNodeBuilder("module", 1, TestUtils.buildQName("cont",
+                "simple:uri", "2012-12-17"), null);
+        LeafSchemaNodeBuilder leafBuild = new LeafSchemaNodeBuilder("module", 2, TestUtils.buildQName("lf1",
+                "simple:uri", "2012-12-17"), null);
+        leafBuild.setType(new DummyType());
+        leafBuild.setConfiguration(true);
+
+        contBuild.addChildNode(leafBuild);
+        return contBuild.build(null);
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java
new file mode 100644 (file)
index 0000000..3c2325c
--- /dev/null
@@ -0,0 +1,51 @@
+package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+
+import javax.ws.rs.WebApplicationException;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
+import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
+import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
+import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+
+public class CnSnToJsonWithAugmentTest extends YangAndXmlAndDataSchemaLoader {
+
+    @BeforeClass
+    public static void initialize() {
+        dataLoad("/cnsn-to-json/augmentation", 5, "yang", "cont");
+    }
+
+    /**
+     * Test of json output when as input are specified composite node with empty
+     * data + YANG file
+     */
+    @Test
+    public void augmentedElementsToJson() {
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/augmentation/xml/data.xml",
+                XmlToCompositeNodeProvider.INSTANCE);
+        TestUtils.normalizeCompositeNode(compositeNode, modules, searchedModuleName + ":" + searchedDataSchemaName);
+
+        String jsonOutput = null;
+        try {
+            jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode,
+                    StructuredDataToJsonProvider.INSTANCE);
+        } catch (WebApplicationException | IOException e) {
+        }
+        assertNotNull(jsonOutput);
+
+        assertTrue(jsonOutput.contains("\"augment-leaf:lf2\": \"lf2\""));
+        assertTrue(jsonOutput.contains("\"augment-container:cont1\": {"));
+        assertTrue(jsonOutput.contains("\"augment-container:lf11\": \"lf11\""));
+        assertTrue(jsonOutput.contains("\"augment-list:lst1\": ["));
+        assertTrue(jsonOutput.contains("\"augment-list:lf11\": \"lf1_1\""));
+        assertTrue(jsonOutput.contains("\"augment-list:lf11\": \"lf1_2\""));
+        assertTrue(jsonOutput.contains("\"augment-leaflist:lflst1\": ["));
+    }
+}
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/ToJsonLeafrefType.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/ToJsonLeafrefType.java
deleted file mode 100644 (file)
index 1ac81a3..0000000
+++ /dev/null
@@ -1,161 +0,0 @@
-package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.util.regex.Matcher;
-
-import javax.ws.rs.WebApplicationException;
-
-import org.junit.*;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
-import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-
-/**
- * 
- * All tests are commented now because leafref isn't supported now
- * 
- */
-
-public class ToJsonLeafrefType extends YangAndXmlAndDataSchemaLoader {
-
-    @BeforeClass
-    public static void initialization() {
-        dataLoad("/cnsn-to-json/leafref", 2, "main-module", "cont");
-    }
-
-    @Ignore
-    @Test
-    public void leafrefAbsolutePathToExistingLeafTest() {
-        String json = null;
-        try {
-            json = TestUtils.writeCompNodeWithSchemaContextToJson(
-                    TestUtils.loadCompositeNode("/cnsn-to-json/leafref/xml/data_absolut_ref_to_existing_leaf.xml"),
-                    modules, dataSchemaNode);
-        } catch (WebApplicationException | IOException e) {
-            // shouldn't end here
-            assertTrue(false);
-        }
-        assertNotNull(json);
-        java.util.regex.Pattern ptrn = java.util.regex.Pattern.compile(".*\"lf3\":\\p{Blank}*true.*",
-                java.util.regex.Pattern.DOTALL);
-        Matcher mtch = ptrn.matcher(json);
-        assertTrue(mtch.matches());
-    }
-
-    @Ignore
-    @Test
-    public void leafrefRelativePathToExistingLeafTest() {
-        String json = null;
-        try {
-            json = TestUtils.writeCompNodeWithSchemaContextToJson(
-                    TestUtils.loadCompositeNode("/cnsn-to-json/leafref/xml/data_relativ_ref_to_existing_leaf.xml"),
-                    modules, dataSchemaNode);
-        } catch (WebApplicationException | IOException e) {
-            // shouldn't end here
-            assertTrue(false);
-        }
-        assertNotNull(json);
-        java.util.regex.Pattern ptrn = java.util.regex.Pattern.compile(".*\"lf2\":\\p{Blank}*121.*",
-                java.util.regex.Pattern.DOTALL);
-        Matcher mtch = ptrn.matcher(json);
-        assertTrue(mtch.matches());
-    }
-
-    /**
-     * Tests case when reference to not existing element is present. In this
-     * case value from single node is printed as string.
-     */
-    @Ignore
-    @Test
-    public void leafrefToNonExistingLeafTest() {
-        String json = null;
-        try {
-            json = TestUtils.writeCompNodeWithSchemaContextToJson(
-                    TestUtils.loadCompositeNode("/cnsn-to-json/leafref/xml/data_ref_to_non_existing_leaf.xml"),
-                    modules, dataSchemaNode);
-        } catch (WebApplicationException | IOException e) {
-            // shouldn't end here
-            assertTrue(false);
-        }
-        assertNotNull(json);
-        java.util.regex.Pattern ptrn = java.util.regex.Pattern.compile(".*\"lf5\":\\p{Blank}*\"137\".*",
-                java.util.regex.Pattern.DOTALL);
-        Matcher mtch = ptrn.matcher(json);
-        assertTrue(mtch.matches());
-    }
-
-    /**
-     * Tests case when non leaf element is referenced. In this case value from
-     * single node is printed as string.
-     */
-    @Ignore
-    @Test
-    public void leafrefToNotLeafTest() {
-        String json = null;
-        try {
-            json = TestUtils.writeCompNodeWithSchemaContextToJson(
-                    TestUtils.loadCompositeNode("/cnsn-to-json/leafref/xml/data_ref_to_not_leaf.xml"), modules,
-                    dataSchemaNode);
-        } catch (WebApplicationException | IOException e) {
-            // shouldn't end here
-            assertTrue(false);
-        }
-        assertNotNull(json);
-        java.util.regex.Pattern ptrn = java.util.regex.Pattern.compile(
-                ".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lf6\":\\p{Blank}*\"44.33\".*",
-                java.util.regex.Pattern.DOTALL);
-        Matcher mtch = ptrn.matcher(json);
-        assertTrue(mtch.matches());
-    }
-
-    /**
-     * Tests case when leaflist element is refers to leaf.
-     */
-    @Ignore
-    @Test
-    public void leafrefFromLeafListToLeafTest() {
-        String json = null;
-        try {
-            json = TestUtils
-                    .writeCompNodeWithSchemaContextToJson(
-                            TestUtils
-                                    .loadCompositeNode("/cnsn-to-json/leafref/xml/data_relativ_ref_from_leaflist_to_existing_leaf.xml"),
-                            modules, dataSchemaNode);
-        } catch (WebApplicationException | IOException e) {
-            // shouldn't end here
-            assertTrue(false);
-        }
-        assertNotNull(json);
-        java.util.regex.Pattern ptrn = java.util.regex.Pattern
-                .compile(
-                        ".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lflst1\":\\p{Blank}*.*345,\\p{Space}*346,\\p{Space}*347.*",
-                        java.util.regex.Pattern.DOTALL);
-        Matcher mtch = ptrn.matcher(json);
-        assertTrue(mtch.matches());
-    }
-
-    /**
-     * Tests case when leaflist element is refers to leaf.
-     */
-    @Ignore
-    @Test
-    public void leafrefFromLeafrefToLeafrefTest() {
-        String json = null;
-        try {
-            json = TestUtils.writeCompNodeWithSchemaContextToJson(
-                    TestUtils.loadCompositeNode("/cnsn-to-json/leafref/xml/data_from_leafref_to_leafref.xml"), modules,
-                    dataSchemaNode);
-        } catch (WebApplicationException | IOException e) {
-            // shouldn't end here
-            assertTrue(false);
-        }
-        assertNotNull(json);
-        java.util.regex.Pattern ptrn = java.util.regex.Pattern.compile(
-                ".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lf7\":\\p{Blank}*200.*", java.util.regex.Pattern.DOTALL);
-        Matcher mtch = ptrn.matcher(json);
-        assertTrue(mtch.matches());
-    }
-
-}
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/ToJsonWithAugmentTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/ToJsonWithAugmentTest.java
deleted file mode 100644 (file)
index 73bd178..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
-
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-
-public class ToJsonWithAugmentTest {
-
-    /**
-     * Test of json output when as input are specified composite node with empty
-     * data + YANG file
-     */
-    @Test
-    public void augmentedElementsToJson() {
-
-        CompositeNode compositeNode = TestUtils.loadCompositeNode("/cnsn-to-json/augmentation/xml/data.xml");
-        String jsonOutput = TestUtils.convertCompositeNodeDataAndYangToJson(compositeNode,
-                "/cnsn-to-json/augmentation", "/cnsn-to-json/augmentation/xml", "yang", "cont");
-
-        assertTrue(jsonOutput.contains("\"augment-leaf:lf2\": \"lf2\""));
-        assertTrue(jsonOutput.contains("\"augment-container:cont1\": {"));
-        assertTrue(jsonOutput.contains("\"augment-container:lf11\": \"lf11\""));
-        assertTrue(jsonOutput.contains("\"augment-list:lst1\": ["));
-        assertTrue(jsonOutput.contains("\"augment-list:lf11\": \"lf1_1\""));
-        assertTrue(jsonOutput.contains("\"augment-list:lf11\": \"lf1_2\""));
-        assertTrue(jsonOutput.contains("\"augment-leaflist:lflst1\": ["));
-    }
-}
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlNotExistingLeafTypeTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlNotExistingLeafTypeTest.java
new file mode 100644 (file)
index 0000000..d779b5c
--- /dev/null
@@ -0,0 +1,70 @@
+package org.opendaylight.controller.sal.restconf.impl.cnsn.to.xml.test;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Set;
+
+import javax.ws.rs.WebApplicationException;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
+import org.opendaylight.controller.sal.restconf.impl.test.DummyType;
+import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
+import org.opendaylight.yangtools.yang.data.api.*;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class CnSnToXmlNotExistingLeafTypeTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(CnSnToXmlNotExistingLeafTypeTest.class);
+
+    @Ignore
+    @Test
+    public void incorrectTopLevelElementTest() {
+
+        boolean nullPointerExceptionRaised = false;
+        try {
+            TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
+                    (Set<Module>) Collections.EMPTY_SET, prepareDataSchemaNode(), StructuredDataToXmlProvider.INSTANCE);
+        } catch (WebApplicationException | IOException e) {
+            LOG.error("WebApplicationException or IOException was raised");
+        } catch (NullPointerException e) {
+            nullPointerExceptionRaised = true;
+        }
+        assertTrue(nullPointerExceptionRaised);
+
+    }
+
+    private CompositeNode prepareCompositeNode() {
+        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont", "simple:uri", "2012-12-17"), null, null, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf1", "simple:uri", "2012-12-17"), cont, "any value", ModifyAction.CREATE, null);
+        cont.getChildren().add(lf1);
+        cont.init();
+        return cont;
+    }
+
+    private DataSchemaNode prepareDataSchemaNode() {
+        ContainerSchemaNodeBuilder contBuild = new ContainerSchemaNodeBuilder("module", 1, TestUtils.buildQName("cont",
+                "simple:uri", "2012-12-17"), null);
+        LeafSchemaNodeBuilder leafBuild = new LeafSchemaNodeBuilder("module", 2, TestUtils.buildQName("lf1",
+                "simple:uri", "2012-12-17"), null);
+        leafBuild.setType(new DummyType());
+        leafBuild.setConfiguration(true);
+
+        contBuild.addChildNode(leafBuild);
+        return contBuild.build(null);
+
+    }
+
+}
index d04337865a9e549c71838dc749d073218a9130c9..96e03a5a3ca4b8b6b0d619232457a8669f3dae06 100644 (file)
@@ -1,24 +1,21 @@
 package org.opendaylight.controller.sal.restconf.impl.cnsn.to.xml.test;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 
-import java.io.StringWriter;
-import java.util.Set;
+import java.io.IOException;
 
-import javax.activation.UnsupportedDataTypeException;
-import javax.xml.transform.*;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
+import javax.ws.rs.WebApplicationException;
+import javax.xml.transform.TransformerFactoryConfigurationError;
 
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.XmlMapper;
+import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
 import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
+import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
 import org.opendaylight.yangtools.yang.data.api.*;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
-import org.opendaylight.yangtools.yang.model.api.*;
-import org.w3c.dom.Document;
 
 /**
  * 
@@ -27,25 +24,31 @@ import org.w3c.dom.Document;
  * XML file
  * 
  */
-public class CnSnToXmlTest {
-
-    private static Set<Module> modules;
-    private static DataSchemaNode dataSchemaNode;
-
+public class CnSnToXmlTest extends YangAndXmlAndDataSchemaLoader {
     @BeforeClass
     public static void initialization() {
-        modules = TestUtils.resolveModules("/cnsn-to-xml/yang");
-        assertEquals(2, modules.size());
-        Module module = TestUtils.resolveModule("basic-module", modules);
-        assertNotNull(module);
-        dataSchemaNode = TestUtils.resolveDataSchemaNode(module, "cont");
-        assertNotNull(dataSchemaNode);
-
+        dataLoad("/cnsn-to-xml/yang", 2, "basic-module", "cont");
     }
 
     @Test
     public void snAsYangIdentityrefToXMLTest() {
-        serializeToXml(prepareIdentityrefData(), "<lf11 xmlns:x=\"referenced:module\">x:iden</lf11>");
+        serializeToXml(prepareIdentityrefData(null, true), "<lf11 xmlns:x=\"referenced:module\">x:iden</lf11>");
+    }
+
+    @Test
+    public void snAsYangIdentityrefWithQNamePrefixToXMLTest() {
+        serializeToXml(prepareIdentityrefData("prefix", true),
+                "<lf11 xmlns:prefix=\"referenced:module\">prefix:iden</lf11>");
+    }
+
+    @Test
+    public void snAsYangIdentityrefWithPrefixToXMLTest() {
+        serializeToXml(prepareIdentityrefData("prefix", false), "<lf11>no qname value</lf11>");
+    }
+
+    @Test
+    public void snAsYangLeafrefWithPrefixToXMLTest() {
+        serializeToXml(prepareLeafrefData(), "<lfBoolean>true</lfBoolean>", "<lfLfref>true</lfLfref>");
     }
 
     @Test
@@ -186,22 +189,13 @@ public class CnSnToXmlTest {
 
     private void serializeToXml(CompositeNode compositeNode, String... xmlRepresentation)
             throws TransformerFactoryConfigurationError {
-        XmlMapper xmlMapper = new XmlMapper();
-        String xmlString = null;
-        if (dataSchemaNode instanceof DataNodeContainer) {
-            try {
-                Document doc = xmlMapper.write(compositeNode, (DataNodeContainer) dataSchemaNode);
-                DOMSource domSource = new DOMSource(doc);
-                StringWriter writer = new StringWriter();
-                StreamResult result = new StreamResult(writer);
-                TransformerFactory tf = TransformerFactory.newInstance();
-                Transformer transformer = tf.newTransformer();
-                transformer.transform(domSource, result);
-                xmlString = writer.toString();
-            } catch (UnsupportedDataTypeException | TransformerException e) {
-            }
+        String xmlString = "";
+        try {
+            xmlString = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode,
+                    StructuredDataToXmlProvider.INSTANCE);
+        } catch (WebApplicationException | IOException e) {
         }
-        assertNotNull(xmlMapper);
+        assertNotNull(xmlString);
         boolean containSearchedStr = false;
         String strRepresentation = "";
         for (String searchedStr : xmlRepresentation) {
@@ -215,16 +209,21 @@ public class CnSnToXmlTest {
 
     }
 
-    private CompositeNode prepareIdentityrefData() {
+    private CompositeNode prepareIdentityrefData(String prefix, boolean valueAsQName) {
         MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
                 TestUtils.buildQName("cont", "basic:module", "2013-12-2"), null, null, ModifyAction.CREATE, null);
         MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(
                 TestUtils.buildQName("cont1", "basic:module", "2013-12-2"), cont, null, ModifyAction.CREATE, null);
         cont.getChildren().add(cont1);
 
+        Object value = null;
+        if (valueAsQName) {
+            value = TestUtils.buildQName("iden", "referenced:module", "2013-12-2", prefix);
+        } else {
+            value = "no qname value";
+        }
         MutableSimpleNode<Object> lf11 = NodeFactory.createMutableSimpleNode(
-                TestUtils.buildQName("lf11", "basic:module", "2013-12-2"), cont1,
-                TestUtils.buildQName("iden", "referenced:module", "2013-12-2"), ModifyAction.CREATE, null);
+                TestUtils.buildQName("lf11", "basic:module", "2013-12-2"), cont1, value, ModifyAction.CREATE, null);
         cont1.getChildren().add(lf11);
         cont1.init();
         cont.init();
@@ -244,4 +243,19 @@ public class CnSnToXmlTest {
         return cont;
     }
 
+    private CompositeNode prepareLeafrefData() {
+        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont"), null, null,
+                ModifyAction.CREATE, null);
+
+        MutableSimpleNode<Object> lfBoolean = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfBoolean"),
+                cont, Boolean.TRUE, ModifyAction.CREATE, null);
+        MutableSimpleNode<Object> lfLfref = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfLfref"), cont,
+                "true", ModifyAction.CREATE, null);
+        cont.getChildren().add(lfBoolean);
+        cont.getChildren().add(lfLfref);
+        cont.init();
+
+        return cont;
+    }
+
 }
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithChoiceTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithChoiceTest.java
new file mode 100644 (file)
index 0000000..a23501c
--- /dev/null
@@ -0,0 +1,64 @@
+package org.opendaylight.controller.sal.restconf.impl.cnsn.to.xml.test;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+
+import javax.ws.rs.WebApplicationException;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
+import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
+import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
+import org.opendaylight.yangtools.yang.data.api.*;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
+
+/**
+ * 
+ * CnSn = Composite node and Simple node data structure Class contains test of
+ * serializing simple nodes data values according data types from YANG schema to
+ * XML file
+ * 
+ */
+public class CnSnToXmlWithChoiceTest extends YangAndXmlAndDataSchemaLoader {
+    @BeforeClass
+    public static void initialization() {
+        dataLoad("/cnsn-to-xml/choice", 1, "module-with-choice", "cont");
+    }
+
+    @Test
+    public void cnSnToXmlWithYangChoice() {
+        String xmlOutput = "";
+        try {
+            xmlOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(
+                    prepareCnStructForYangData("lf1", "String data1"), modules, dataSchemaNode,
+                    StructuredDataToXmlProvider.INSTANCE);
+        } catch (WebApplicationException | IOException e) {
+        }
+
+        assertTrue(xmlOutput.contains("<lf1>String data1</lf1>"));
+
+        try {
+            xmlOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(
+                    prepareCnStructForYangData("lf2", "String data2"), modules, dataSchemaNode,
+                    StructuredDataToXmlProvider.INSTANCE);
+        } catch (WebApplicationException | IOException e) {
+        }
+        assertTrue(xmlOutput.contains("<lf2>String data2</lf2>"));
+
+    }
+
+    private CompositeNode prepareCnStructForYangData(String lfName, Object data) {
+        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont"), null, null,
+                ModifyAction.CREATE, null);
+
+        MutableSimpleNode<Object> lf1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName(lfName), cont, data,
+                ModifyAction.CREATE, null);
+        cont.getChildren().add(lf1);
+        cont.init();
+
+        return cont;
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonIdentityrefToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonIdentityrefToCnSnTest.java
new file mode 100644 (file)
index 0000000..e9b1dbe
--- /dev/null
@@ -0,0 +1,74 @@
+package org.opendaylight.controller.sal.restconf.impl.json.to.cnsn.test;
+
+import static org.junit.Assert.*;
+
+import java.util.List;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
+import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
+import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.*;
+
+public class JsonIdentityrefToCnSnTest extends YangAndXmlAndDataSchemaLoader {
+
+    @BeforeClass
+    public static void initialize() {
+        dataLoad("/json-to-cnsn/identityref", 2, "identityref-module", "cont");
+    }
+
+    @Test
+    public void jsonIdentityrefToCompositeNode() {
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/identityref/json/data.json", false,
+                JsonToCompositeNodeProvider.INSTANCE);
+        assertNotNull(compositeNode);
+
+        TestUtils.normalizeCompositeNode(compositeNode, modules, searchedModuleName + ":" + searchedDataSchemaName);
+
+        assertEquals("cont", compositeNode.getNodeType().getLocalName());
+
+        List<Node<?>> childs = compositeNode.getChildren();
+        assertEquals(1, childs.size());
+        Node<?> nd = childs.iterator().next();
+        assertTrue(nd instanceof CompositeNode);
+        assertEquals("cont1", nd.getNodeType().getLocalName());
+
+        childs = ((CompositeNode) nd).getChildren();
+        assertEquals(4, childs.size());
+        SimpleNode<?> lf11 = null;
+        SimpleNode<?> lf12 = null;
+        SimpleNode<?> lf13 = null;
+        SimpleNode<?> lf14 = null;
+        for (Node<?> child : childs) {
+            assertTrue(child instanceof SimpleNode);
+            if (child.getNodeType().getLocalName().equals("lf11")) {
+                lf11 = (SimpleNode<?>) child;
+            } else if (child.getNodeType().getLocalName().equals("lf12")) {
+                lf12 = (SimpleNode<?>) child;
+            } else if (child.getNodeType().getLocalName().equals("lf13")) {
+                lf13 = (SimpleNode<?>) child;
+            } else if (child.getNodeType().getLocalName().equals("lf14")) {
+                lf14 = (SimpleNode<?>) child;
+            }
+        }
+
+        assertTrue(lf11.getValue() instanceof QName);
+        assertEquals("iden", ((QName) lf11.getValue()).getLocalName());
+        assertEquals("identity:module", ((QName) lf11.getValue()).getNamespace().toString());
+
+        assertTrue(lf12.getValue() instanceof QName);
+        assertEquals("iden_local", ((QName) lf12.getValue()).getLocalName());
+        assertEquals("identityref:module", ((QName) lf12.getValue()).getNamespace().toString());
+
+        assertTrue(lf13.getValue() instanceof QName);
+        assertEquals("iden_local", ((QName) lf13.getValue()).getLocalName());
+        assertEquals("identityref:module", ((QName) lf13.getValue()).getNamespace().toString());
+
+        assertTrue(lf14.getValue() instanceof QName);
+        assertEquals("iden_local", ((QName) lf14.getValue()).getLocalName());
+        assertEquals("identity:module", ((QName) lf14.getValue()).getNamespace().toString());
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java
new file mode 100644 (file)
index 0000000..2bb42d9
--- /dev/null
@@ -0,0 +1,48 @@
+package org.opendaylight.controller.sal.restconf.impl.json.to.cnsn.test;
+
+import static org.junit.Assert.*;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
+import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
+import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
+import org.opendaylight.yangtools.yang.data.api.*;
+
+public class JsonLeafrefToCnSnTest extends YangAndXmlAndDataSchemaLoader {
+
+    @BeforeClass
+    public static void initialize() {
+        dataLoad("/json-to-cnsn/leafref");
+    }
+
+    /**
+     * JSON values which represents leafref are always loaded to simple node as
+     * string
+     */
+    @Test
+    public void jsonIdentityrefToCompositeNode() {
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/leafref/json/data.json", false,
+                JsonToCompositeNodeProvider.INSTANCE);
+        assertNotNull(compositeNode);
+        TestUtils.normalizeCompositeNode(compositeNode, modules, searchedModuleName + ":" + searchedDataSchemaName);
+
+        assertEquals("cont", compositeNode.getNodeType().getLocalName());
+
+        SimpleNode<?> lf2 = null;
+        for (Node<?> childNode : compositeNode.getChildren()) {
+            if (childNode instanceof SimpleNode) {
+                if (childNode.getNodeType().getLocalName().equals("lf2")) {
+                    lf2 = (SimpleNode<?>) childNode;
+                    break;
+                }
+            }
+        }
+
+        assertNotNull(lf2);
+        assertTrue(lf2.getValue() instanceof String);
+        assertEquals("121", (String) lf2.getValue());
+
+    }
+
+}
index b02ea9a3a28fe439efc1d04341449bf28bd5e28f..f2c0c29bc4372b6b54eeec0dc3bf9d9805f36663 100644 (file)
@@ -1,9 +1,10 @@
 package org.opendaylight.controller.sal.restconf.impl.json.to.cnsn.test;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 
-import java.io.*;
-import java.net.URISyntaxException;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 
@@ -12,10 +13,12 @@ import javax.ws.rs.WebApplicationException;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
+import org.opendaylight.controller.sal.restconf.impl.ResponseException;
 import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.*;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.api.SimpleNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -28,7 +31,7 @@ public class JsonToCnSnTest {
 
     @Test
     public void simpleListTest() {
-        simpleTest("/json-to-cnsn/simple-list.json", "/json-to-cnsn/simple-list-yang", "lst", "simple:list:yang1",
+        simpleTest("/json-to-cnsn/simple-list.json", "/json-to-cnsn/simple-list-yang/1", "lst", "simple:list:yang1",
                 "simple-list-yang1");
     }
 
@@ -43,7 +46,8 @@ public class JsonToCnSnTest {
      */
     @Test
     public void multipleItemsInLeafList() {
-        CompositeNode compositeNode = compositeContainerFromJson("/json-to-cnsn/multiple-leaflist-items.json", true);
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/multiple-leaflist-items.json", true,
+                JsonToCompositeNodeProvider.INSTANCE);
         assertNotNull(compositeNode);
         assertEquals(3, compositeNode.getChildren().size());
 
@@ -76,9 +80,10 @@ public class JsonToCnSnTest {
      */
     @Test
     public void multipleItemsInListTest() {
-        CompositeNode compositeNode = compositeContainerFromJson("/json-to-cnsn/multiple-items-in-list.json", true);
-        assertNotNull(compositeNode);
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/multiple-items-in-list.json", true,
+                JsonToCompositeNodeProvider.INSTANCE);
 
+        assertNotNull(compositeNode);
         assertEquals("lst", compositeNode.getNodeType().getLocalName());
 
         verityMultipleItemsInList(compositeNode);
@@ -86,7 +91,8 @@ public class JsonToCnSnTest {
 
     @Test
     public void nullArrayToSimpleNodeWithNullValueTest() {
-        CompositeNode compositeNode = compositeContainerFromJson("/json-to-cnsn/array-with-null.json", true);
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/array-with-null.json", true,
+                JsonToCompositeNodeProvider.INSTANCE);
         assertNotNull(compositeNode);
         assertEquals("cont", compositeNode.getNodeType().getLocalName());
 
@@ -103,7 +109,8 @@ public class JsonToCnSnTest {
     public void incorrectTopLevelElementsTest() {
         Throwable cause1 = null;
         try {
-            compositeContainerFromJson("/json-to-cnsn/wrong-top-level1.json", true);
+            TestUtils
+                    .readInputToCnSn("/json-to-cnsn/wrong-top-level1.json", true, JsonToCompositeNodeProvider.INSTANCE);
         } catch (WebApplicationException e) {
             cause1 = e;
         }
@@ -117,7 +124,8 @@ public class JsonToCnSnTest {
 
         Throwable cause2 = null;
         try {
-            compositeContainerFromJson("/json-to-cnsn/wrong-top-level2.json", true);
+            TestUtils
+                    .readInputToCnSn("/json-to-cnsn/wrong-top-level2.json", true, JsonToCompositeNodeProvider.INSTANCE);
         } catch (WebApplicationException e) {
             cause2 = e;
         }
@@ -126,7 +134,8 @@ public class JsonToCnSnTest {
 
         Throwable cause3 = null;
         try {
-            compositeContainerFromJson("/json-to-cnsn/wrong-top-level3.json", true);
+            TestUtils
+                    .readInputToCnSn("/json-to-cnsn/wrong-top-level3.json", true, JsonToCompositeNodeProvider.INSTANCE);
         } catch (WebApplicationException e) {
             cause3 = e;
         }
@@ -145,7 +154,8 @@ public class JsonToCnSnTest {
      */
     @Test
     public void emptyDataReadTest() {
-        CompositeNode compositeNode = compositeContainerFromJson("/json-to-cnsn/empty-data.json", true);
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/empty-data.json", true,
+                JsonToCompositeNodeProvider.INSTANCE);
 
         assertNotNull(compositeNode);
 
@@ -158,7 +168,7 @@ public class JsonToCnSnTest {
 
         String reason = null;
         try {
-            compositeContainerFromJson("/json-to-cnsn/empty-data1.json", true);
+            TestUtils.readInputToCnSn("/json-to-cnsn/empty-data1.json", true, JsonToCompositeNodeProvider.INSTANCE);
         } catch (JsonSyntaxException e) {
             reason = e.getMessage();
         }
@@ -176,24 +186,20 @@ public class JsonToCnSnTest {
     @Test
     public void notSupplyNamespaceIfAlreadySupplied() {
 
-        CompositeNode compositeNode = compositeContainerFromJson("/json-to-cnsn/simple-list.json");
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/simple-list.json", false,
+                JsonToCompositeNodeProvider.INSTANCE);
         assertNotNull(compositeNode);
 
-        DataSchemaNode dataSchemaNode1 = null;
-        DataSchemaNode dataSchemaNode2 = null;
-        try {
-            dataSchemaNode1 = TestUtils.obtainSchemaFromYang("/json-to-cnsn/simple-list-yang", "simple-list-yang1");
-            dataSchemaNode2 = TestUtils.obtainSchemaFromYang("/json-to-cnsn/simple-list-yang", "simple-list-yang2");
-        } catch (FileNotFoundException e) {
-            LOG.error(e.getMessage());
-            assertTrue(false);
-        }
-        assertNotNull(dataSchemaNode1);
-        assertNotNull(dataSchemaNode2);
-
         // supplement namespaces according to first data schema -
         // "simple:data:types1"
-        TestUtils.supplementNamespace(dataSchemaNode1, compositeNode);
+        Set<Module> modules1 = new HashSet<>();
+        Set<Module> modules2 = new HashSet<>();
+        modules1 = TestUtils.loadModulesFrom("/json-to-cnsn/simple-list-yang/1");
+        modules2 = TestUtils.loadModulesFrom("/json-to-cnsn/simple-list-yang/2");
+        assertNotNull(modules1);
+        assertNotNull(modules2);
+
+        TestUtils.normalizeCompositeNode(compositeNode, modules1, "simple-list-yang1:lst");
 
         assertTrue(compositeNode instanceof CompositeNodeWrapper);
         CompositeNode compNode = ((CompositeNodeWrapper) compositeNode).unwrap();
@@ -201,26 +207,27 @@ public class JsonToCnSnTest {
         assertEquals("lst", compNode.getNodeType().getLocalName());
         verifyCompositeNode(compNode, "simple:list:yang1");
 
-        // dataSchemaNode2 should't be taken into account, because compNode
-        // isn't CompositeNodeWrapper
-        TestUtils.supplementNamespace(dataSchemaNode2, compNode);
-        verifyCompositeNode(compNode, "simple:list:yang1");
+        String exceptionMessage = "";
+        try {
+            TestUtils.normalizeCompositeNode(compositeNode, modules2, "simple-list-yang2:lst");
+        } catch (ResponseException e) {
+            exceptionMessage = String.valueOf(e.getResponse().getEntity());
+        }
+        assertTrue(exceptionMessage
+                .contains("Data has bad format\nIf data is in XML format then namespace for lst should be simple:list:yang2.\n If data is in Json format then module name for lst should be simple-list-yang2."));
 
     }
 
     @Test
     public void jsonIdentityrefToCompositeNode() {
-        CompositeNode compositeNode = compositeContainerFromJson("/json-to-cnsn/identityref/json/data.json");
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/json-to-cnsn/identityref/json/data.json", false,
+                JsonToCompositeNodeProvider.INSTANCE);
         assertNotNull(compositeNode);
 
-        Set<Module> modules = TestUtils.resolveModules("/json-to-cnsn/identityref");
+        Set<Module> modules = TestUtils.loadModulesFrom("/json-to-cnsn/identityref");
         assertEquals(2, modules.size());
-        Module module = TestUtils.resolveModule("identityref-module", modules);
-        assertNotNull(module);
-        DataSchemaNode dataSchemaNode = TestUtils.resolveDataSchemaNode(module, null);
-        assertNotNull(dataSchemaNode);
 
-        TestUtils.normalizeCompositeNode(compositeNode, modules, dataSchemaNode, "identityref-module:cont");
+        TestUtils.normalizeCompositeNode(compositeNode, modules, "identityref-module:cont");
 
         assertEquals("cont", compositeNode.getNodeType().getLocalName());
 
@@ -268,19 +275,14 @@ public class JsonToCnSnTest {
 
     private void simpleTest(String jsonPath, String yangPath, String topLevelElementName, String namespace,
             String moduleName) {
-        CompositeNode compositeNode = compositeContainerFromJson(jsonPath);
+        CompositeNode compositeNode = TestUtils.readInputToCnSn(jsonPath, false, JsonToCompositeNodeProvider.INSTANCE);
         assertNotNull(compositeNode);
 
-        DataSchemaNode dataSchemaNode = null;
-        try {
-            dataSchemaNode = TestUtils.obtainSchemaFromYang(yangPath, moduleName);
-        } catch (FileNotFoundException e) {
-            LOG.error(e.getMessage());
-            assertTrue(false);
-        }
-        assertNotNull(dataSchemaNode);
+        Set<Module> modules = null;
+        modules = TestUtils.loadModulesFrom(yangPath);
+        assertNotNull(modules);
 
-        TestUtils.supplementNamespace(dataSchemaNode, compositeNode);
+        TestUtils.normalizeCompositeNode(compositeNode, modules, moduleName + ":" + topLevelElementName);
 
         assertTrue(compositeNode instanceof CompositeNodeWrapper);
         CompositeNode compNode = ((CompositeNodeWrapper) compositeNode).unwrap();
@@ -331,7 +333,8 @@ public class JsonToCnSnTest {
         boolean lflst1_2Found = false;
         boolean lf1Found = false;
 
-        assertEquals(namespace, compositeNode.getNodeType().getNamespace().toString());
+        // assertEquals(namespace,
+        // compositeNode.getNodeType().getNamespace().toString());
 
         for (Node<?> node : compositeNode.getChildren()) {
             if (node.getNodeType().getLocalName().equals("cont1")) {
@@ -369,34 +372,16 @@ public class JsonToCnSnTest {
         assertTrue(lf1Found);
     }
 
-    private CompositeNode compositeContainerFromJson(String jsonPath) {
-        return compositeContainerFromJson(jsonPath, false);
-    }
-
-    private CompositeNode compositeContainerFromJson(String jsonPath, boolean dummyNamespaces)
-            throws WebApplicationException {
-
-        JsonToCompositeNodeProvider jsonToCompositeNodeProvider = JsonToCompositeNodeProvider.INSTANCE;
-        InputStream jsonStream = JsonToCnSnTest.class.getResourceAsStream(jsonPath);
+    @Test
+    public void unsupportedDataFormatTest() {
+        String exceptionMessage = "";
         try {
-            CompositeNode compositeNode = jsonToCompositeNodeProvider
-                    .readFrom(null, null, null, null, null, jsonStream);
-            assertTrue(compositeNode instanceof CompositeNodeWrapper);
-            if (dummyNamespaces) {
-                try {
-                    TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
-                    return ((CompositeNodeWrapper) compositeNode).unwrap();
-                } catch (URISyntaxException e) {
-                    LOG.error(e.getMessage());
-                    assertTrue(e.getMessage(), false);
-                }
-            }
-            return compositeNode;
-        } catch (IOException e) {
-            LOG.error(e.getMessage());
-            assertTrue(e.getMessage(), false);
+            TestUtils.readInputToCnSn("/json-to-cnsn/unsupported-json-format.json", true,
+                    JsonToCompositeNodeProvider.INSTANCE);
+        } catch (WebApplicationException e) {
+            exceptionMessage = e.getCause().getMessage();
         }
-        return null;
+        assertTrue(exceptionMessage.contains("Root element of Json has to be Object"));
     }
 
 }
index 08ec3f2b0c73c192a02f237132513ccce9b9522e..c68fcb90714567849192db25d9dc676e43f700a9 100644 (file)
@@ -1,21 +1,22 @@
 package org.opendaylight.controller.sal.restconf.impl.test;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 import java.io.FileNotFoundException;
 import java.util.Set;
 
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.mockito.Mock;
-
-import static org.mockito.Mockito.*;
-
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.controller.sal.core.api.mount.MountService;
 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
 import org.opendaylight.controller.sal.restconf.impl.InstanceIdWithSchemaNode;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
@@ -26,8 +27,8 @@ public class ControllerContextTest {
 
     @BeforeClass
     public static void init() throws FileNotFoundException {
-        Set<Module> allModules = TestUtils.loadModules(ControllerContextTest.class.getResource("/full-versions/yangs")
-                .getPath());
+        Set<Module> allModules = TestUtils.loadModulesFrom("/full-versions/yangs");
+        assertNotNull(allModules);
         SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
         controllerContext.setSchemas(schemaContext);
     }
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java
new file mode 100644 (file)
index 0000000..0876584
--- /dev/null
@@ -0,0 +1,64 @@
+package org.opendaylight.controller.sal.restconf.impl.test;
+
+import java.util.List;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.*;
+
+public class DummyType implements TypeDefinition<DummyType> {
+    QName dummyQName = TestUtils.buildQName("dummy type", "simple:uri", "2012-12-17");
+
+    @Override
+    public QName getQName() {
+        return dummyQName;
+    }
+
+    @Override
+    public SchemaPath getPath() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public String getDescription() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public String getReference() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public Status getStatus() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public List<UnknownSchemaNode> getUnknownSchemaNodes() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public DummyType getBaseType() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public String getUnits() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public Object getDefaultValue() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+}
index d58b7e9dab0cecac48f4d5641dd2b6ff9bc8ba3a..2370035861759584655b0f104516c231f3a6419c 100644 (file)
@@ -7,15 +7,25 @@ import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-import java.net.*;
-import java.util.*;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Set;
 
-import org.junit.*;
+import org.junit.BeforeClass;
+import org.junit.Test;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
-import org.opendaylight.controller.sal.restconf.impl.*;
-import org.opendaylight.yangtools.yang.common.*;
-import org.opendaylight.yangtools.yang.data.api.*;
+import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
+import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
+import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
+import org.opendaylight.controller.sal.restconf.impl.StructuredData;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.ModifyAction;
+import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
+import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 import org.opendaylight.yangtools.yang.model.api.Module;
 
@@ -33,7 +43,7 @@ public class InvokeRpcMethodTest {
 
     @BeforeClass
     public static void initialization() {
-        modules = TestUtils.resolveModules("/invoke-rpc");
+        modules = TestUtils.loadModulesFrom("/invoke-rpc");
         assertEquals(1, modules.size());
         Module module = TestUtils.resolveModule("invoke-rpc-module", modules);
         assertNotNull(module);
index 0bb03cb0ad77b5d7da5468f84faa05983e3d8703..f2eea9dbd24214d3b7a776a62680e64d8c7797e7 100644 (file)
@@ -1,6 +1,7 @@
 package org.opendaylight.controller.sal.restconf.impl.test;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -45,8 +46,8 @@ public class ReadConfAndOperDataTest extends JerseyTest {
 
     @BeforeClass
     public static void init() throws FileNotFoundException {
-        Set<Module> allModules = TestUtils.loadModules(RestconfImplTest.class.getResource("/full-versions/yangs")
-                .getPath());
+        Set<Module> allModules = TestUtils.loadModulesFrom("/full-versions/yangs");
+        assertNotNull(allModules);
         SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
         controllerContext = ControllerContext.getInstance();
         controllerContext.setSchemas(schemaContext);
@@ -69,15 +70,16 @@ public class ReadConfAndOperDataTest extends JerseyTest {
 
         String uri = createUri("/config/", "ietf-interfaces:interfaces/interface/eth0");
 
-        CompositeNode loadedCompositeNode = TestUtils.loadCompositeNodeWithXmlTreeBuilder("/parts/ietf-interfaces_interfaces.xml");
+        CompositeNode loadedCompositeNode = TestUtils.readInputToCnSn("/parts/ietf-interfaces_interfaces.xml", true,
+                XmlToCompositeNodeProvider.INSTANCE);
         when(brokerFacade.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(loadedCompositeNode);
 
         Response response = target(uri).request(MEDIA_TYPE_DRAFT02).get();
         assertEquals(200, response.getStatus());
-        
+
         uri = createUri("/config/", "ietf-interfaces:interfaces/interface/example");
         when(brokerFacade.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(null);
-        
+
         response = target(uri).request(MEDIA_TYPE_DRAFT02).get();
         assertEquals(404, response.getStatus());
     }
@@ -86,16 +88,17 @@ public class ReadConfAndOperDataTest extends JerseyTest {
     public void testReadOperationalData() throws UnsupportedEncodingException, FileNotFoundException {
         String uri = createUri("/operational/", "ietf-interfaces:interfaces/interface/eth0");
 
-        
-        CompositeNode loadedCompositeNode = TestUtils.loadCompositeNodeWithXmlTreeBuilder("/parts/ietf-interfaces_interfaces.xml");
+        CompositeNode loadedCompositeNode = TestUtils.readInputToCnSn("/parts/ietf-interfaces_interfaces.xml", true,
+                XmlToCompositeNodeProvider.INSTANCE);
+
         when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(loadedCompositeNode);
 
         Response response = target(uri).request(MEDIA_TYPE_DRAFT02).get();
         assertEquals(200, response.getStatus());
-        
+
         uri = createUri("/config/", "ietf-interfaces:interfaces/interface/example");
         when(brokerFacade.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(null);
-        
+
         response = target(uri).request(MEDIA_TYPE_DRAFT02).get();
         assertEquals(404, response.getStatus());
     }
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestCodecExceptionsTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestCodecExceptionsTest.java
new file mode 100644 (file)
index 0000000..fcc4c02
--- /dev/null
@@ -0,0 +1,33 @@
+package org.opendaylight.controller.sal.restconf.impl.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+
+import org.junit.Test;
+import org.opendaylight.controller.sal.restconf.impl.RestCodec;
+import org.opendaylight.yangtools.concepts.Codec;
+import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.util.BitsType;
+
+public class RestCodecExceptionsTest {
+
+    @Test
+    public void serializeExceptionTest() {
+        Codec<Object, Object> codec = RestCodec.from(new BitsType(null));
+        String serializedValue = (String) codec.serialize("incorrect value"); // set
+                                                                              // expected
+        assertEquals("incorrect value", serializedValue);
+    }
+
+    @Test
+    public void deserializeExceptionTest() {
+        IdentityrefTypeDefinition mockedIidentityrefType = mock(IdentityrefTypeDefinition.class);
+
+        Codec<Object, Object> codec = RestCodec.from(mockedIidentityrefType);
+        String serializedValue = (String) codec.deserialize("incorrect value"); // IdentityValuesDTO
+                                                                                // object
+        // expected
+        assertEquals("incorrect value", serializedValue);
+    }
+
+}
index 41cc0ddb5130f0fc49e4b76f51e9d423f25fd47a..c15cd530823fd06a49321946c1fe8e33bdaf4e9a 100644 (file)
@@ -1,17 +1,20 @@
 package org.opendaylight.controller.sal.restconf.impl.test;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
 import java.io.FileNotFoundException;
-import java.io.InputStream;
 import java.util.Set;
 
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.opendaylight.controller.sal.restconf.impl.*;
+import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
+import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
+import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
+import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.model.api.Module;
@@ -23,8 +26,8 @@ public class RestconfImplTest {
 
     @BeforeClass
     public static void init() throws FileNotFoundException {
-        Set<Module> allModules = TestUtils.loadModules(RestconfImplTest.class.getResource("/full-versions/yangs")
-                .getPath());
+        Set<Module> allModules = TestUtils.loadModulesFrom("/full-versions/yangs");
+        assertNotNull(allModules);
         SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
         ControllerContext controllerContext = ControllerContext.getInstance();
         controllerContext.setSchemas(schemaContext);
@@ -33,8 +36,7 @@ public class RestconfImplTest {
 
     @Test
     public void testExample() throws FileNotFoundException {
-        InputStream xmlStream = RestconfImplTest.class.getResourceAsStream("/parts/ietf-interfaces_interfaces.xml");
-        CompositeNode loadedCompositeNode = TestUtils.loadCompositeNodeWithXmlTreeBuilder(xmlStream);
+        CompositeNode loadedCompositeNode = TestUtils.readInputToCnSn("/parts/ietf-interfaces_interfaces.xml", XmlToCompositeNodeProvider.INSTANCE);
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
         when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(loadedCompositeNode);
         assertEquals(loadedCompositeNode, brokerFacade.readOperationalData(null));
index 366d99dbcb88a3dcb18f55c826b0b1c2dcc09b93..4295c29a22cea2f538d0006d94c70957163fabf9 100644 (file)
@@ -1,32 +1,50 @@
 package org.opendaylight.controller.sal.restconf.impl.test;
 
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-import java.io.*;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStreamWriter;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.sql.Date;
-import java.util.*;
-import java.util.concurrent.Future;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
 
 import javax.ws.rs.WebApplicationException;
-import javax.xml.parsers.*;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.transform.*;
+import javax.ws.rs.ext.MessageBodyReader;
+import javax.ws.rs.ext.MessageBodyWriter;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
 
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
-import org.opendaylight.controller.sal.rest.impl.*;
-import org.opendaylight.controller.sal.restconf.impl.*;
+import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
+import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
+import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
+import org.opendaylight.controller.sal.restconf.impl.NodeWrapper;
+import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
+import org.opendaylight.controller.sal.restconf.impl.StructuredData;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.*;
-import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder;
-import org.opendaylight.yangtools.yang.model.api.*;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
 import org.slf4j.Logger;
@@ -38,11 +56,11 @@ import com.google.common.base.Preconditions;
 
 public final class TestUtils {
 
-    private static final Logger logger = LoggerFactory.getLogger(TestUtils.class);
+    private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
 
     private final static YangModelParser parser = new YangParserImpl();
 
-    public static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
+    private static Set<Module> loadModules(String resourceDirectory) throws FileNotFoundException {
         final File testDir = new File(resourceDirectory);
         final String[] fileList = testDir.list();
         final List<File> testFiles = new ArrayList<File>();
@@ -58,34 +76,40 @@ public final class TestUtils {
         return parser.parseYangModels(testFiles);
     }
 
+    public static Set<Module> loadModulesFrom(String yangPath) {
+        try {
+            return TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
+        } catch (FileNotFoundException e) {
+            LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
+        }
+
+        return null;
+    }
+
     public static SchemaContext loadSchemaContext(Set<Module> modules) {
         return parser.resolveSchemaContext(modules);
     }
 
     public static SchemaContext loadSchemaContext(String resourceDirectory) throws FileNotFoundException {
-        return parser.resolveSchemaContext(loadModules(resourceDirectory));
+        return parser.resolveSchemaContext(loadModulesFrom(resourceDirectory));
     }
 
     public static Module findModule(Set<Module> modules, String moduleName) {
-        Module result = null;
         for (Module module : modules) {
             if (module.getName().equals(moduleName)) {
-                result = module;
-                break;
+                return module;
             }
         }
-        return result;
+        return null;
     }
 
-
-
     public static Document loadDocumentFrom(InputStream inputStream) {
         try {
             DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
             DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
             return docBuilder.parse(inputStream);
         } catch (SAXException | IOException | ParserConfigurationException e) {
-            logger.error("Error during loading Document from XML", e);
+            LOG.error("Error during loading Document from XML", e);
             return null;
         }
     }
@@ -107,288 +131,84 @@ public final class TestUtils {
             return new String(charData, "UTF-8");
         } catch (IOException | TransformerException e) {
             String msg = "Error during transformation of Document into String";
-            logger.error(msg, e);
+            LOG.error(msg, e);
             return msg;
         }
 
     }
 
-    public static String convertCompositeNodeDataAndYangToJson(CompositeNode compositeNode, String yangPath,
-            String outputPath, String searchedModuleName, String searchedDataSchemaName) {
-        Set<Module> modules = resolveModules(yangPath);
-        Module module = resolveModule(searchedModuleName, modules);
-        DataSchemaNode dataSchemaNode = resolveDataSchemaNode(module, searchedDataSchemaName);
-
-        normalizeCompositeNode(compositeNode, modules, dataSchemaNode, searchedModuleName + ":"
-                + searchedDataSchemaName);
-
-        try {
-            return writeCompNodeWithSchemaContextToJson(compositeNode, modules, dataSchemaNode);
-        } catch (WebApplicationException | IOException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-        return null;
-
-    }
-
-    public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules,
-            DataSchemaNode dataSchemaNode, String schemaNodePath) {
+    /**
+     * 
+     * Fill missing data (namespaces) and build correct data type in
+     * {@code compositeNode} according to {@code dataSchemaNode}. The method
+     * {@link RestconfImpl#createConfigurationData createConfigurationData} is
+     * used because it contains calling of method {code normalizeNode}
+     */
+    public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules, String schemaNodePath) {
         RestconfImpl restconf = RestconfImpl.getInstance();
         ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
 
-        TestUtils.prepareMockForRestconfBeforeNormalization(modules, dataSchemaNode, restconf);
+        prepareMocksForRestconf(modules, restconf);
         restconf.createConfigurationData(schemaNodePath, compositeNode);
     }
 
+    /**
+     * Searches module with name {@code searchedModuleName} in {@code modules}.
+     * If module name isn't specified and module set has only one element then
+     * this element is returned.
+     * 
+     */
     public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
-        assertNotNull("modules can't be null.", modules);
-        Module module = null;
+        assertNotNull("Modules can't be null.", modules);
         if (searchedModuleName != null) {
             for (Module m : modules) {
                 if (m.getName().equals(searchedModuleName)) {
-                    module = m;
-                    break;
+                    return m;
                 }
             }
         } else if (modules.size() == 1) {
-            module = modules.iterator().next();
+            return modules.iterator().next();
         }
-        return module;
-    }
-
-    public static Set<Module> resolveModules(String yangPath) {
-        Set<Module> modules = null;
-
-        try {
-            modules = TestUtils.loadModules(TestUtils.class.getResource(yangPath).getPath());
-        } catch (FileNotFoundException e) {
-            e.printStackTrace();
-        }
-
-        return modules;
+        return null;
     }
 
-    public static DataSchemaNode resolveDataSchemaNode(Module module, String searchedDataSchemaName) {
-        assertNotNull("Module is missing", module);
+    public static DataSchemaNode resolveDataSchemaNode(String searchedDataSchemaName, Module module) {
+        assertNotNull("Module can't be null", module);
 
-        DataSchemaNode dataSchemaNode = null;
         if (searchedDataSchemaName != null) {
             for (DataSchemaNode dsn : module.getChildNodes()) {
                 if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
-                    dataSchemaNode = dsn;
+                    return dsn;
                 }
             }
         } else if (module.getChildNodes().size() == 1) {
-            dataSchemaNode = module.getChildNodes().iterator().next();
+            return module.getChildNodes().iterator().next();
         }
-        return dataSchemaNode;
-    }
-
-    public static String writeCompNodeWithSchemaContextToJson(CompositeNode compositeNode, Set<Module> modules,
-            DataSchemaNode dataSchemaNode) throws IOException, WebApplicationException {
-        String jsonResult;
-
-        assertNotNull(dataSchemaNode);
-        assertNotNull("Composite node can't be null", compositeNode);
-        ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
-
-        ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
-
-        StructuredDataToJsonProvider structuredDataToJsonProvider = StructuredDataToJsonProvider.INSTANCE;
-        structuredDataToJsonProvider.writeTo(new StructuredData(compositeNode, dataSchemaNode), null, null, null, null,
-                null, byteArrayOS);
-
-        jsonResult = byteArrayOS.toString();
-
-        return jsonResult;
-    }
-
-    public static CompositeNode loadCompositeNode(String xmlDataPath) {
-        InputStream xmlStream = TestUtils.class.getResourceAsStream(xmlDataPath);
-        CompositeNode compositeNode = null;
-        try {
-            XmlReader xmlReader = new XmlReader();
-            compositeNode = xmlReader.read(xmlStream);
-
-        } catch (UnsupportedFormatException | XMLStreamException e) {
-            e.printStackTrace();
-        }
-        return compositeNode;
-    }
-
-    static void outputToFile(ByteArrayOutputStream outputStream, String outputDir) throws IOException {
-        FileOutputStream fileOS = null;
-        try {
-            String path = TestUtils.class.getResource(outputDir).getPath();
-            File outFile = new File(path + "/data.json");
-            fileOS = new FileOutputStream(outFile);
-            try {
-                fileOS.write(outputStream.toByteArray());
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-            fileOS.close();
-        } catch (FileNotFoundException e1) {
-            e1.printStackTrace();
-        }
-    }
-
-    static String readJsonFromFile(String path, boolean removeWhiteChars) {
-        FileReader fileReader = getFileReader(path);
-
-        StringBuilder strBuilder = new StringBuilder();
-        char[] buffer = new char[1000];
-
-        while (true) {
-            int loadedCharNum;
-            try {
-                loadedCharNum = fileReader.read(buffer);
-            } catch (IOException e) {
-                break;
-            }
-            if (loadedCharNum == -1) {
-                break;
-            }
-            strBuilder.append(buffer, 0, loadedCharNum);
-        }
-        try {
-            fileReader.close();
-        } catch (IOException e) {
-            System.out.println("The file wasn't closed");
-        }
-        String rawStr = strBuilder.toString();
-        if (removeWhiteChars) {
-            rawStr = rawStr.replace("\n", "");
-            rawStr = rawStr.replace("\r", "");
-            rawStr = rawStr.replace("\t", "");
-            rawStr = removeSpaces(rawStr);
-        }
-
-        return rawStr;
-    }
-
-    private static FileReader getFileReader(String path) {
-        String fullPath = TestUtils.class.getResource(path).getPath();
-        assertNotNull("Path to file can't be null.", fullPath);
-        File file = new File(fullPath);
-        assertNotNull("File can't be null", file);
-        FileReader fileReader = null;
-        try {
-            fileReader = new FileReader(file);
-        } catch (FileNotFoundException e) {
-            e.printStackTrace();
-        }
-        assertNotNull("File reader can't be null.", fileReader);
-        return fileReader;
-    }
-
-    private static String removeSpaces(String rawStr) {
-        StringBuilder strBuilder = new StringBuilder();
-        int i = 0;
-        int quoteCount = 0;
-        while (i < rawStr.length()) {
-            if (rawStr.substring(i, i + 1).equals("\"")) {
-                quoteCount++;
-            }
-
-            if (!rawStr.substring(i, i + 1).equals(" ") || (quoteCount % 2 == 1)) {
-                strBuilder.append(rawStr.charAt(i));
-            }
-            i++;
-        }
-
-        return strBuilder.toString();
+        return null;
     }
 
-    public static QName buildQName(String name, String uri, String date) {
+    public static QName buildQName(String name, String uri, String date, String prefix) {
         try {
             URI u = new URI(uri);
             Date dt = null;
             if (date != null) {
                 dt = Date.valueOf(date);
             }
-            return new QName(u, dt, name);
+            return new QName(u, dt, prefix, name);
         } catch (URISyntaxException e) {
             return null;
         }
     }
 
-    public static QName buildQName(String name) {
-        return buildQName(name, "", null);
-    }
-
-    public static void supplementNamespace(DataSchemaNode dataSchemaNode, CompositeNode compositeNode) {
-        RestconfImpl restconf = RestconfImpl.getInstance();
-
-        InstanceIdWithSchemaNode instIdAndSchema = new InstanceIdWithSchemaNode(mock(InstanceIdentifier.class),
-                dataSchemaNode);
-
-        ControllerContext controllerContext = mock(ControllerContext.class);
-        BrokerFacade broker = mock(BrokerFacade.class);
-
-        RpcResult<TransactionStatus> rpcResult = new DummyRpcResult.Builder<TransactionStatus>().result(
-                TransactionStatus.COMMITED).build();
-        Future<RpcResult<TransactionStatus>> future = DummyFuture.builder().rpcResult(rpcResult).build();
-        when(controllerContext.toInstanceIdentifier(any(String.class))).thenReturn(instIdAndSchema);
-        when(broker.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class))).thenReturn(
-                future);
-
-        restconf.setControllerContext(controllerContext);
-        restconf.setBroker(broker);
-
-        // method is called only because it contains call of method which
-        // supplement namespaces to compositeNode
-        restconf.createConfigurationData("something", compositeNode);
-    }
-
-    public static DataSchemaNode obtainSchemaFromYang(String yangFolder) throws FileNotFoundException {
-        return obtainSchemaFromYang(yangFolder, null);
+    public static QName buildQName(String name, String uri, String date) {
+        return buildQName(name, uri, date, null);
     }
 
-    public static DataSchemaNode obtainSchemaFromYang(String yangFolder, String moduleName)
-            throws FileNotFoundException {
-        Set<Module> modules = null;
-        modules = TestUtils.loadModules(TestUtils.class.getResource(yangFolder).getPath());
-
-        if (modules == null) {
-            return null;
-        }
-        if (modules.size() < 1) {
-            return null;
-        }
-
-        Module moduleRes = null;
-        if (modules.size() > 1) {
-            if (moduleName == null) {
-                return null;
-            } else {
-                for (Module module : modules) {
-                    if (module.getName().equals(moduleName)) {
-                        moduleRes = module;
-                    }
-                }
-                if (moduleRes == null) {
-                    return null;
-                }
-            }
-        } else {
-            moduleRes = modules.iterator().next();
-        }
-
-        if (moduleRes.getChildNodes() == null) {
-            return null;
-        }
-
-        if (moduleRes.getChildNodes().size() != 1) {
-            return null;
-        }
-        DataSchemaNode dataSchemaNode = moduleRes.getChildNodes().iterator().next();
-        return dataSchemaNode;
-
+    public static QName buildQName(String name) {
+        return buildQName(name, "", null);
     }
 
-    public static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
+    private static void addDummyNamespaceToAllNodes(NodeWrapper<?> wrappedNode) throws URISyntaxException {
         wrappedNode.setNamespace(new URI(""));
         if (wrappedNode instanceof CompositeNodeWrapper) {
             for (NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
@@ -397,56 +217,63 @@ public final class TestUtils {
         }
     }
 
-    public static void prepareMockForRestconfBeforeNormalization(Set<Module> modules, DataSchemaNode dataSchemaNode,
-            RestconfImpl restconf) {
-        ControllerContext instance = ControllerContext.getInstance();
-        instance.setSchemas(TestUtils.loadSchemaContext(modules));
-        restconf.setControllerContext(ControllerContext.getInstance());
-
+    private static void prepareMocksForRestconf(Set<Module> modules, RestconfImpl restconf) {
+        ControllerContext controllerContext = ControllerContext.getInstance();
         BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
+
+        controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
+
         when(mockedBrokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
                 .thenReturn(
                         new DummyFuture.Builder().rpcResult(
                                 new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
                                         .build()).build());
+
+        restconf.setControllerContext(controllerContext);
         restconf.setBroker(mockedBrokerFacade);
     }
-    
-    static CompositeNode loadCompositeNodeWithXmlTreeBuilder(String xmlDataPath) {
-        InputStream xmlStream = TestUtils.class.getResourceAsStream(xmlDataPath);
-        CompositeNode compositeNode = null;
+
+    public static CompositeNode readInputToCnSn(String path, boolean dummyNamespaces,
+            MessageBodyReader<CompositeNode> reader) throws WebApplicationException {
+
+        InputStream inputStream = TestUtils.class.getResourceAsStream(path);
         try {
-            compositeNode = TestUtils.loadCompositeNodeWithXmlTreeBuilder(xmlStream);
-        } catch (FileNotFoundException e) {
-            e.printStackTrace();
+            CompositeNode compositeNode = reader.readFrom(null, null, null, null, null, inputStream);
+            assertTrue(compositeNode instanceof CompositeNodeWrapper);
+            if (dummyNamespaces) {
+                try {
+                    TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
+                    return ((CompositeNodeWrapper) compositeNode).unwrap();
+                } catch (URISyntaxException e) {
+                    LOG.error(e.getMessage());
+                    assertTrue(e.getMessage(), false);
+                }
+            }
+            return compositeNode;
+        } catch (IOException e) {
+            LOG.error(e.getMessage());
+            assertTrue(e.getMessage(), false);
         }
-        return compositeNode;
-        
-        
-        
+        return null;
     }
-    
-    
-    public static CompositeNode loadCompositeNodeWithXmlTreeBuilder(InputStream xmlInputStream) throws FileNotFoundException {
-        if (xmlInputStream == null) {
-            throw new IllegalArgumentException();
-        }
-        Node<?> dataTree;
-        try {
-            dataTree = XmlTreeBuilder.buildDataTree(xmlInputStream);
-        } catch (XMLStreamException e) {
-            logger.error("Error during building data tree from XML", e);
-            return null;
-        }
-        if (dataTree == null) {
-            logger.error("data tree is null");
-            return null;
-        }
-        if (dataTree instanceof SimpleNode) {
-            logger.error("RPC XML was resolved as SimpleNode");
-            return null;
-        }
-        return (CompositeNode) dataTree;
-    }        
 
+    public static CompositeNode readInputToCnSn(String path, MessageBodyReader<CompositeNode> reader) {
+        return readInputToCnSn(path, false, reader);
+    }
+
+    public static String writeCompNodeWithSchemaContextToOutput(CompositeNode compositeNode, Set<Module> modules,
+            DataSchemaNode dataSchemaNode, MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
+            WebApplicationException {
+
+        assertNotNull(dataSchemaNode);
+        assertNotNull("Composite node can't be null", compositeNode);
+        ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
+
+        ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
+
+        messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode), null, null, null, null, null,
+                byteArrayOS);
+
+        return byteArrayOS.toString();
+    }
 }
index 4cea120d4d1896f498394e176184d1b63e3b262c..b18f526a237c4c841758fcace2c4903bd28a68ae 100644 (file)
@@ -1,6 +1,7 @@
 package org.opendaylight.controller.sal.restconf.impl.test;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -35,7 +36,6 @@ import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
 import org.opendaylight.controller.sal.restconf.impl.*;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.*;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
@@ -51,8 +51,8 @@ public class XmlProvidersTest extends JerseyTest {
 
     @BeforeClass
     public static void init() throws FileNotFoundException {
-        Set<Module> allModules = TestUtils.loadModules(RestconfImplTest.class.getResource("/full-versions/yangs")
-                .getPath());
+        Set<Module> allModules = TestUtils.loadModulesFrom("/full-versions/yangs");
+        assertNotNull(allModules);
         SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
         controllerContext = ControllerContext.getInstance();
         controllerContext.setSchemas(schemaContext);
index 7e3da0e4b4bd98ee8a6a04442001b91e10da37ad..3d24c6ba67ec1fc3a18ea1e290988f1e52fc8289 100644 (file)
@@ -4,24 +4,32 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 
 import java.util.Set;
-import org.opendaylight.yangtools.yang.model.api.*;
+
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
 
 public abstract class YangAndXmlAndDataSchemaLoader {
 
     protected static Set<Module> modules;
     protected static DataSchemaNode dataSchemaNode;
+    protected static String searchedModuleName;
+    protected static String searchedDataSchemaName;
+    protected static String schemaNodePath;
 
     protected static void dataLoad(String yangPath) {
         dataLoad(yangPath, 1, null, null);
     }
 
     protected static void dataLoad(String yangPath, int modulesNumber, String moduleName, String dataSchemaName) {
-        modules = TestUtils.resolveModules(yangPath);
+        modules = TestUtils.loadModulesFrom(yangPath);
         assertEquals(modulesNumber, modules.size());
         Module module = TestUtils.resolveModule(moduleName, modules);
+        searchedModuleName = module == null ? "" : module.getName();
         assertNotNull(module);
-        dataSchemaNode = TestUtils.resolveDataSchemaNode(module, dataSchemaName);
+        dataSchemaNode = TestUtils.resolveDataSchemaNode(dataSchemaName, module);
+        searchedDataSchemaName = dataSchemaNode == null ? "" : dataSchemaNode.getQName().getLocalName();
         assertNotNull(dataSchemaNode);
+        schemaNodePath = searchedModuleName + ":" + searchedDataSchemaName;
     }
 
 }
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java
new file mode 100644 (file)
index 0000000..beff572
--- /dev/null
@@ -0,0 +1,351 @@
+package org.opendaylight.controller.sal.restconf.impl.xml.to.cnsn.test;
+
+import static org.junit.Assert.*;
+
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
+import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.*;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class XmlLeafrefToCnSnTest {
+    private static final Logger LOG = LoggerFactory.getLogger(XmlLeafrefToCnSnTest.class);
+
+    /**
+     * top level element represents container. second level element is list with
+     * two elements.
+     */
+    @Test
+    public void testXmlDataContainer() {
+        CompositeNode compNode = TestUtils.readInputToCnSn("/xml-to-cnsn/data-container.xml", false,
+                XmlToCompositeNodeProvider.INSTANCE);
+        assertNotNull(compNode);
+        Set<Module> modules = TestUtils.loadModulesFrom("/xml-to-cnsn/data-container-yang");
+
+        assertNotNull(modules);
+        TestUtils.normalizeCompositeNode(compNode, modules, "data-container-yang:cont");
+
+        String nameSpace = "data:container:yang";
+        assertEquals(nameSpace, compNode.getNodeType().getNamespace().toString());
+
+        verifyNullAndEmptyStringSingleNode(compNode, nameSpace);
+        verifyCommonPartAOfXml(compNode, "", nameSpace);
+    }
+
+    private void verifyNullAndEmptyStringSingleNode(CompositeNode compNode, String nameSpace) {
+        assertEquals("cont", compNode.getNodeType().getLocalName());
+
+        SimpleNode<?> lf2 = null;
+        SimpleNode<?> lf3 = null;
+        int found = 0;
+        for (Node<?> child : compNode.getChildren()) {
+            if (found == 0x3)
+                break;
+            if (child instanceof SimpleNode<?>) {
+                SimpleNode<?> childSimple = (SimpleNode<?>) child;
+                if (childSimple.getNodeType().getLocalName().equals("lf3")) {
+                    lf3 = childSimple;
+                    found = found | (1 << 0);
+                } else if (childSimple.getNodeType().getLocalName().equals("lf2")) {
+                    lf2 = childSimple;
+                    found = found | (1 << 1);
+                }
+            }
+            assertEquals(nameSpace, child.getNodeType().getNamespace().toString());
+        }
+
+        assertEquals("", lf2.getValue());
+        assertEquals(null, lf3.getValue());
+    }
+
+    @Test
+    public void testXmlDataList() {
+        CompositeNode compNode = TestUtils.readInputToCnSn("/xml-to-cnsn/data-list.xml", false,
+                XmlToCompositeNodeProvider.INSTANCE);
+        assertNotNull(compNode);
+
+        Set<Module> modules = TestUtils.loadModulesFrom("/xml-to-cnsn/data-list-yang");
+        assertNotNull(modules);
+
+        TestUtils.normalizeCompositeNode(compNode, modules, "data-container-yang:cont");
+
+        String nameSpaceList = "data:list:yang";
+        String nameSpaceCont = "data:container:yang";
+        assertEquals(nameSpaceCont, compNode.getNodeType().getNamespace().toString());
+        assertEquals("cont", compNode.getNodeType().getLocalName());
+        assertEquals(3, compNode.getChildren().size());
+        CompositeNode lst1_1 = null;
+        CompositeNode lst1_2 = null;
+        int loopCount = 0;
+        for (Node<?> node : compNode.getChildren()) {
+            if (node.getNodeType().getLocalName().equals("lf1")) {
+                assertEquals(nameSpaceList, node.getNodeType().getNamespace().toString());
+                assertTrue(node instanceof SimpleNode<?>);
+                assertEquals("lf1", node.getValue());
+            } else {
+                assertTrue(node instanceof CompositeNode);
+                switch (loopCount++) {
+                case 0:
+                    lst1_1 = (CompositeNode) node;
+                    break;
+                case 1:
+                    lst1_2 = (CompositeNode) node;
+                    break;
+                }
+                assertEquals(nameSpaceCont, node.getNodeType().getNamespace().toString());
+            }
+        }
+        // lst1_1
+        verifyCommonPartAOfXml(lst1_1, "1", nameSpaceCont);
+        // :lst1_1
+
+        // lst1_2
+        SimpleNode<?> lflst11 = null;
+        CompositeNode cont11 = null;
+        for (Node<?> node : lst1_2.getChildren()) {
+            String nodeName = node.getNodeType().getLocalName();
+            if (nodeName.equals("lflst11")) {
+                assertTrue(node instanceof SimpleNode<?>);
+                lflst11 = (SimpleNode<?>) node;
+
+            } else if (nodeName.equals("cont11")) {
+                assertTrue(node instanceof CompositeNode);
+                cont11 = (CompositeNode) node;
+            }
+            assertEquals(nameSpaceCont, compNode.getNodeType().getNamespace().toString());
+        }
+        assertEquals("221", lflst11.getValue());
+
+        assertEquals(1, cont11.getChildren().size());
+        assertTrue(cont11.getChildren().get(0) instanceof SimpleNode<?>);
+        SimpleNode<?> cont11_lf111 = (SimpleNode<?>) cont11.getChildren().get(0);
+        assertEquals(nameSpaceCont, cont11_lf111.getNodeType().getNamespace().toString());
+        assertEquals("lf111", cont11_lf111.getNodeType().getLocalName());
+        assertEquals((short) 100, cont11_lf111.getValue());
+        // :lst1_2
+
+    }
+
+    @Test
+    public void testXmlEmptyData() {
+        CompositeNode compNode = TestUtils.readInputToCnSn("/xml-to-cnsn/empty-data.xml", true,
+                XmlToCompositeNodeProvider.INSTANCE);
+        assertEquals("cont", compNode.getNodeType().getLocalName());
+        SimpleNode<?> lf1 = null;
+        SimpleNode<?> lflst1_1 = null;
+        SimpleNode<?> lflst1_2 = null;
+        CompositeNode lst1 = null;
+        int lflst1Count = 0;
+        for (Node<?> node : compNode.getChildren()) {
+            if (node.getNodeType().getLocalName().equals("lf1")) {
+                assertTrue(node instanceof SimpleNode<?>);
+                lf1 = (SimpleNode<?>) node;
+            } else if (node.getNodeType().getLocalName().equals("lflst1")) {
+                assertTrue(node instanceof SimpleNode<?>);
+
+                switch (lflst1Count++) {
+                case 0:
+                    lflst1_1 = (SimpleNode<?>) node;
+                    break;
+                case 1:
+                    lflst1_2 = (SimpleNode<?>) node;
+                    break;
+                }
+            } else if (node.getNodeType().getLocalName().equals("lst1")) {
+                assertTrue(node instanceof CompositeNode);
+                lst1 = (CompositeNode) node;
+            }
+        }
+
+        assertNotNull(lf1);
+        assertNotNull(lflst1_1);
+        assertNotNull(lflst1_2);
+        assertNotNull(lst1);
+
+        assertEquals("", lf1.getValue());
+        assertEquals("", lflst1_1.getValue());
+        assertEquals("", lflst1_2.getValue());
+        assertEquals(1, lst1.getChildren().size());
+        assertEquals("lf11", lst1.getChildren().get(0).getNodeType().getLocalName());
+
+        assertTrue(lst1.getChildren().get(0) instanceof SimpleNode<?>);
+        assertEquals("", lst1.getChildren().get(0).getValue());
+
+    }
+
+    /**
+     * Test case like this <lf11 xmlns:x="namespace">x:identity</lf11>
+     */
+    @Test
+    public void testIdentityrefNmspcInElement() {
+        testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-nmspc-in-element.xml", "/xml-to-cnsn/identityref",
+                "identityref-module", "cont", 2, "iden", "identity:module");
+    }
+
+    /**
+     * 
+     * Test case like <lf11 xmlns="namespace1"
+     * xmlns:x="namespace">identity</lf11>
+     */
+
+    @Test
+    public void testIdentityrefDefaultNmspcInElement() {
+        testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-default-nmspc-in-element.xml",
+                "/xml-to-cnsn/identityref/yang-augments", "general-module", "cont", 3, "iden", "identityref:module");
+    }
+
+    /**
+     * 
+     * Test case like <cont1 xmlns="namespace1"> <lf11
+     * xmlns:x="namespace">identity</lf11> </cont1>
+     */
+    @Test
+    public void testIdentityrefDefaultNmspcInParrentElement() {
+        testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-default-nmspc-in-parrent-element.xml",
+                "/xml-to-cnsn/identityref", "identityref-module", "cont", 2, "iden", "identityref:module");
+    }
+
+    /**
+     * 
+     * Test case like <cont1 xmlns="namespace1" xmlns:x="namespace">
+     * <lf11>x:identity</lf11> </cont1>
+     */
+    @Test
+    public void testIdentityrefNmspcInParrentElement() {
+        testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-nmspc-in-parrent-element.xml",
+                "/xml-to-cnsn/identityref", "identityref-module", "cont", 2, "iden", "z:namespace");
+
+    }
+
+    /**
+     * 
+     * Test case like (without namespace in xml) <cont1> <lf11>x:identity</lf11>
+     * </cont1>
+     */
+    @Test
+    public void testIdentityrefNoNmspcValueWithPrefix() {
+        testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-no-nmspc-value-with-prefix.xml",
+                "/xml-to-cnsn/identityref", "identityref-module", "cont", 2, "x:iden", "identityref:module");
+    }
+
+    /**
+     * 
+     * Test case like (without namespace in xml) <cont1> <lf11>identity</lf11>
+     * </cont1>
+     */
+    @Test
+    public void testIdentityrefNoNmspcValueWithoutPrefix() {
+        testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-no-nmspc-value-without-prefix.xml",
+                "/xml-to-cnsn/identityref", "identityref-module", "cont", 2, "iden", "identityref:module");
+    }
+
+    private void verifyCommonPartAOfXml(CompositeNode compNode, String suf, String nameSpace) {
+        SimpleNode<?> lf1suf = null;
+        SimpleNode<?> lflst1suf_1 = null;
+        SimpleNode<?> lflst1suf_2 = null;
+        SimpleNode<?> lflst1suf_3 = null;
+        CompositeNode cont1suf = null;
+        CompositeNode lst1suf = null;
+
+        int lflstCount = 0;
+
+        for (Node<?> node : compNode.getChildren()) {
+            String localName = node.getNodeType().getLocalName();
+            if (localName.equals("lf1" + suf)) {
+                assertTrue(node instanceof SimpleNode<?>);
+                lf1suf = (SimpleNode<?>) node;
+            } else if (localName.equals("lflst1" + suf)) {
+                assertTrue(node instanceof SimpleNode<?>);
+                switch (lflstCount++) {
+                case 0:
+                    lflst1suf_1 = (SimpleNode<?>) node;
+                    break;
+                case 1:
+                    lflst1suf_2 = (SimpleNode<?>) node;
+                    break;
+                case 2:
+                    lflst1suf_3 = (SimpleNode<?>) node;
+                    break;
+                }
+            } else if (localName.equals("lst1" + suf)) {
+                assertTrue(node instanceof CompositeNode);
+                lst1suf = (CompositeNode) node;
+            } else if (localName.equals("cont1" + suf)) {
+                assertTrue(node instanceof CompositeNode);
+                cont1suf = (CompositeNode) node;
+            }
+            assertEquals(nameSpace, node.getNodeType().getNamespace().toString());
+        }
+
+        assertNotNull(lf1suf);
+        assertNotNull(lflst1suf_1);
+        assertNotNull(lflst1suf_2);
+        assertNotNull(lflst1suf_3);
+        assertNotNull(lst1suf);
+        assertNotNull(cont1suf);
+
+        assertEquals("str0", lf1suf.getValue());
+        assertEquals("121", lflst1suf_1.getValue());
+        assertEquals("131", lflst1suf_2.getValue());
+        assertEquals("str1", lflst1suf_3.getValue());
+
+        assertEquals(1, lst1suf.getChildren().size());
+
+        assertTrue(lst1suf.getChildren().get(0) instanceof SimpleNode<?>);
+        SimpleNode<?> lst11_lf11 = (SimpleNode<?>) lst1suf.getChildren().get(0);
+        assertEquals(nameSpace, lst11_lf11.getNodeType().getNamespace().toString());
+        assertEquals("lf11" + suf, lst11_lf11.getNodeType().getLocalName());
+        assertEquals("str2", lst11_lf11.getValue());
+
+        assertTrue(cont1suf.getChildren().get(0) instanceof SimpleNode<?>);
+        SimpleNode<?> cont1_lf11 = (SimpleNode<?>) cont1suf.getChildren().get(0);
+        assertEquals(nameSpace, cont1_lf11.getNodeType().getNamespace().toString());
+        assertEquals("lf11" + suf, cont1_lf11.getNodeType().getLocalName());
+        assertEquals((short) 100, cont1_lf11.getValue());
+    }
+
+    private void testIdentityrefToCnSn(String xmlPath, String yangPath, String moduleName, String schemaName,
+            int moduleCount, String resultLocalName, String resultNamespace) {
+        CompositeNode compositeNode = TestUtils.readInputToCnSn(xmlPath, false, XmlToCompositeNodeProvider.INSTANCE);
+        assertNotNull(compositeNode);
+
+        Set<Module> modules = TestUtils.loadModulesFrom(yangPath);
+        assertEquals(moduleCount, modules.size());
+
+        TestUtils.normalizeCompositeNode(compositeNode, modules, moduleName + ":" + schemaName);
+
+        SimpleNode<?> lf11 = getLf11(compositeNode);
+        assertTrue(lf11.getValue() instanceof QName);
+        QName qName = (QName) lf11.getValue();
+        assertEquals(resultLocalName, qName.getLocalName());
+        assertEquals(resultNamespace, qName.getNamespace().toString());
+    }
+
+    private SimpleNode<?> getLf11(CompositeNode compositeNode) {
+        assertEquals("cont", compositeNode.getNodeType().getLocalName());
+
+        List<Node<?>> childs = compositeNode.getChildren();
+        assertEquals(1, childs.size());
+        Node<?> nd = childs.iterator().next();
+        assertTrue(nd instanceof CompositeNode);
+        assertEquals("cont1", nd.getNodeType().getLocalName());
+
+        childs = ((CompositeNode) nd).getChildren();
+        SimpleNode<?> lf11 = null;
+        for (Node<?> child : childs) {
+            assertTrue(child instanceof SimpleNode);
+            if (child.getNodeType().getLocalName().equals("lf11")) {
+                lf11 = (SimpleNode<?>) child;
+            }
+        }
+        assertNotNull(lf11);
+        return lf11;
+    }
+
+}
index 50ab0857b79534ea1e61b956b58391d6fde87897..7c7df56133abd44e67a9a912a2e603bc817b9ed4 100644 (file)
@@ -2,391 +2,43 @@ package org.opendaylight.controller.sal.restconf.impl.xml.to.cnsn.test;
 
 import static org.junit.Assert.*;
 
-import java.io.*;
-import java.net.URISyntaxException;
-import java.util.List;
-import java.util.Set;
-
-import javax.ws.rs.WebApplicationException;
-
+import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
 import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
 import org.opendaylight.yangtools.yang.data.api.*;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class XmlToCnSnTest {
-    private static final Logger LOG = LoggerFactory.getLogger(XmlToCnSnTest.class);
-
-    /**
-     * top level element represents container. second level element is list with
-     * two elements.
-     */
-    @Test
-    public void testXmlDataContainer() {
-        CompositeNode compNode = compositeNodeFromXml("/xml-to-cnsn/data-container.xml", false);
-        assertNotNull(compNode);
-        DataSchemaNode dataSchemaNode = null;
-        try {
-            dataSchemaNode = TestUtils.obtainSchemaFromYang("/xml-to-cnsn/data-container-yang");
-        } catch (FileNotFoundException e) {
-            LOG.error(e.getMessage());
-            assertTrue(false);
-        }
-
-        assertNotNull(dataSchemaNode);
-        TestUtils.supplementNamespace(dataSchemaNode, compNode);
-
-        String nameSpace = "data:container:yang";
-        assertEquals(nameSpace, compNode.getNodeType().getNamespace().toString());
-
-        verifyNullAndEmptyStringSingleNode(compNode, nameSpace);
-        verifyCommonPartAOfXml(compNode, "", nameSpace);
-    }
-
-    private void verifyNullAndEmptyStringSingleNode(CompositeNode compNode, String nameSpace) {
-        assertEquals("cont", compNode.getNodeType().getLocalName());
 
-        SimpleNode<?> lf2 = null;
-        SimpleNode<?> lf3 = null;
-        int found = 0;
-        for (Node<?> child : compNode.getChildren()) {
-            if (found == 0x3)
-                break;
-            if (child instanceof SimpleNode<?>) {
-                SimpleNode<?> childSimple = (SimpleNode<?>) child;
-                if (childSimple.getNodeType().getLocalName().equals("lf3")) {
-                    lf3 = childSimple;
-                    found = found | (1 << 0);
-                } else if (childSimple.getNodeType().getLocalName().equals("lf2")) {
-                    lf2 = childSimple;
-                    found = found | (1 << 1);
-                }
-            }
-            assertEquals(nameSpace, child.getNodeType().getNamespace().toString());
-        }
+public class XmlToCnSnTest extends YangAndXmlAndDataSchemaLoader {
 
-        assertEquals("", lf2.getValue());
-        assertEquals(null, lf3.getValue());
+    @BeforeClass
+    public static void initialize() {
+        dataLoad("/xml-to-cnsn/leafref");
     }
 
     @Test
-    public void testXmlDataList() {
-        CompositeNode compNode = compositeNodeFromXml("/xml-to-cnsn/data-list.xml", false);
-        assertNotNull(compNode);
-
-        DataSchemaNode dataSchemaNode = null;
-        try {
-            dataSchemaNode = TestUtils.obtainSchemaFromYang("/xml-to-cnsn/data-list-yang", "data-container-yang");
-        } catch (FileNotFoundException e) {
-            LOG.error(e.getMessage());
-        }
+    public void testXmlLeafrefToCnSn() {
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/xml-to-cnsn/leafref/xml/data.xml", false,
+                XmlToCompositeNodeProvider.INSTANCE);
+        assertNotNull(compositeNode);
         assertNotNull(dataSchemaNode);
-        TestUtils.supplementNamespace(dataSchemaNode, compNode);
-
-        String nameSpaceList = "data:list:yang";
-        String nameSpaceCont = "data:container:yang";
-        assertEquals(nameSpaceCont, compNode.getNodeType().getNamespace().toString());
-        assertEquals("cont", compNode.getNodeType().getLocalName());
-        assertEquals(3, compNode.getChildren().size());
-        CompositeNode lst1_1 = null;
-        CompositeNode lst1_2 = null;
-        int loopCount = 0;
-        for (Node<?> node : compNode.getChildren()) {
-            if (node.getNodeType().getLocalName().equals("lf1")) {
-                assertEquals(nameSpaceList, node.getNodeType().getNamespace().toString());
-                assertTrue(node instanceof SimpleNode<?>);
-                assertEquals("lf1", node.getValue());
-            } else {
-                assertTrue(node instanceof CompositeNode);
-                switch (loopCount++) {
-                case 0:
-                    lst1_1 = (CompositeNode) node;
-                    break;
-                case 1:
-                    lst1_2 = (CompositeNode) node;
-                    break;
-                }
-                assertEquals(nameSpaceCont, node.getNodeType().getNamespace().toString());
-            }
-        }
-        // lst1_1
-        verifyCommonPartAOfXml(lst1_1, "1", nameSpaceCont);
-        // :lst1_1
-
-        // lst1_2
-        SimpleNode<?> lflst11 = null;
-        CompositeNode cont11 = null;
-        for (Node<?> node : lst1_2.getChildren()) {
-            String nodeName = node.getNodeType().getLocalName();
-            if (nodeName.equals("lflst11")) {
-                assertTrue(node instanceof SimpleNode<?>);
-                lflst11 = (SimpleNode<?>) node;
-
-            } else if (nodeName.equals("cont11")) {
-                assertTrue(node instanceof CompositeNode);
-                cont11 = (CompositeNode) node;
-            }
-            assertEquals(nameSpaceCont, compNode.getNodeType().getNamespace().toString());
-        }
-        assertEquals("221", lflst11.getValue());
-
-        assertEquals(1, cont11.getChildren().size());
-        assertTrue(cont11.getChildren().get(0) instanceof SimpleNode<?>);
-        SimpleNode<?> cont11_lf111 = (SimpleNode<?>) cont11.getChildren().get(0);
-        assertEquals(nameSpaceCont, cont11_lf111.getNodeType().getNamespace().toString());
-        assertEquals("lf111", cont11_lf111.getNodeType().getLocalName());
-        assertEquals((short) 100, cont11_lf111.getValue());
-        // :lst1_2
-
-    }
-
-    @Test
-    public void testXmlEmptyData() {
-        CompositeNode compNode = compositeNodeFromXml("/xml-to-cnsn/empty-data.xml", true);
-        assertEquals("cont", compNode.getNodeType().getLocalName());
-        SimpleNode<?> lf1 = null;
-        SimpleNode<?> lflst1_1 = null;
-        SimpleNode<?> lflst1_2 = null;
-        CompositeNode lst1 = null;
-        int lflst1Count = 0;
-        for (Node<?> node : compNode.getChildren()) {
-            if (node.getNodeType().getLocalName().equals("lf1")) {
-                assertTrue(node instanceof SimpleNode<?>);
-                lf1 = (SimpleNode<?>) node;
-            } else if (node.getNodeType().getLocalName().equals("lflst1")) {
-                assertTrue(node instanceof SimpleNode<?>);
-
-                switch (lflst1Count++) {
-                case 0:
-                    lflst1_1 = (SimpleNode<?>) node;
-                    break;
-                case 1:
-                    lflst1_2 = (SimpleNode<?>) node;
-                    break;
-                }
-            } else if (node.getNodeType().getLocalName().equals("lst1")) {
-                assertTrue(node instanceof CompositeNode);
-                lst1 = (CompositeNode) node;
-            }
-        }
-
-        assertNotNull(lf1);
-        assertNotNull(lflst1_1);
-        assertNotNull(lflst1_2);
-        assertNotNull(lst1);
-
-        assertEquals("", lf1.getValue());
-        assertEquals("", lflst1_1.getValue());
-        assertEquals("", lflst1_2.getValue());
-        assertEquals(1, lst1.getChildren().size());
-        assertEquals("lf11", lst1.getChildren().get(0).getNodeType().getLocalName());
-
-        assertTrue(lst1.getChildren().get(0) instanceof SimpleNode<?>);
-        assertEquals("", lst1.getChildren().get(0).getValue());
-
-    }
-
-    /**
-     * Test case like this <lf11 xmlns:x="namespace">x:identity</lf11>
-     */
-    @Test
-    public void testIdentityrefNmspcInElement() {
-        testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-nmspc-in-element.xml", "/xml-to-cnsn/identityref",
-                "identityref-module", "cont", 2, "iden", "identity:module");
-    }
+        TestUtils.normalizeCompositeNode(compositeNode, modules, schemaNodePath);
 
-    /**
-     * 
-     * Test case like <lf11 xmlns="namespace1"
-     * xmlns:x="namespace">identity</lf11>
-     */
-
-    @Test
-    public void testIdentityrefDefaultNmspcInElement() {
-        testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-default-nmspc-in-element.xml",
-                "/xml-to-cnsn/identityref/yang-augments", "general-module", "cont", 3, "iden", "identityref:module");
-    }
-
-    /**
-     * 
-     * Test case like <cont1 xmlns="namespace1"> <lf11
-     * xmlns:x="namespace">identity</lf11> </cont1>
-     */
-    @Test
-    public void testIdentityrefDefaultNmspcInParrentElement() {
-        testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-default-nmspc-in-parrent-element.xml",
-                "/xml-to-cnsn/identityref", "identityref-module", "cont", 2, "iden", "identityref:module");
-    }
-
-    /**
-     * 
-     * Test case like <cont1 xmlns="namespace1" xmlns:x="namespace">
-     * <lf11>x:identity</lf11> </cont1>
-     */
-    @Test
-    public void testIdentityrefNmspcInParrentElement() {
-        testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-nmspc-in-parrent-element.xml",
-                "/xml-to-cnsn/identityref", "identityref-module", "cont", 2, "iden", "z:namespace");
-
-    }
-
-    /**
-     * 
-     * Test case like (without namespace in xml) <cont1> <lf11>x:identity</lf11>
-     * </cont1>
-     */
-    @Test
-    public void testIdentityrefNoNmspcValueWithPrefix() {
-        testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-no-nmspc-value-with-prefix.xml",
-                "/xml-to-cnsn/identityref", "identityref-module", "cont", 2, "x:iden", "identityref:module");
-    }
-
-    /**
-     * 
-     * Test case like (without namespace in xml) <cont1> <lf11>identity</lf11>
-     * </cont1>
-     */
-    @Test
-    public void testIdentityrefNoNmspcValueWithoutPrefix() {
-        testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-no-nmspc-value-without-prefix.xml",
-                "/xml-to-cnsn/identityref", "identityref-module", "cont", 2, "iden", "identityref:module");
-    }
-
-    private void verifyCommonPartAOfXml(CompositeNode compNode, String suf, String nameSpace) {
-        SimpleNode<?> lf1suf = null;
-        SimpleNode<?> lflst1suf_1 = null;
-        SimpleNode<?> lflst1suf_2 = null;
-        SimpleNode<?> lflst1suf_3 = null;
-        CompositeNode cont1suf = null;
-        CompositeNode lst1suf = null;
-
-        int lflstCount = 0;
+        assertEquals("cont", compositeNode.getNodeType().getLocalName());
 
-        for (Node<?> node : compNode.getChildren()) {
-            String localName = node.getNodeType().getLocalName();
-            if (localName.equals("lf1" + suf)) {
-                assertTrue(node instanceof SimpleNode<?>);
-                lf1suf = (SimpleNode<?>) node;
-            } else if (localName.equals("lflst1" + suf)) {
-                assertTrue(node instanceof SimpleNode<?>);
-                switch (lflstCount++) {
-                case 0:
-                    lflst1suf_1 = (SimpleNode<?>) node;
-                    break;
-                case 1:
-                    lflst1suf_2 = (SimpleNode<?>) node;
-                    break;
-                case 2:
-                    lflst1suf_3 = (SimpleNode<?>) node;
+        SimpleNode<?> lf2 = null;
+        for (Node<?> childNode : compositeNode.getChildren()) {
+            if (childNode instanceof SimpleNode) {
+                if (childNode.getNodeType().getLocalName().equals("lf2")) {
+                    lf2 = (SimpleNode<?>) childNode;
                     break;
                 }
-            } else if (localName.equals("lst1" + suf)) {
-                assertTrue(node instanceof CompositeNode);
-                lst1suf = (CompositeNode) node;
-            } else if (localName.equals("cont1" + suf)) {
-                assertTrue(node instanceof CompositeNode);
-                cont1suf = (CompositeNode) node;
             }
-            assertEquals(nameSpace, node.getNodeType().getNamespace().toString());
         }
 
-        assertNotNull(lf1suf);
-        assertNotNull(lflst1suf_1);
-        assertNotNull(lflst1suf_2);
-        assertNotNull(lflst1suf_3);
-        assertNotNull(lst1suf);
-        assertNotNull(cont1suf);
-
-        assertEquals("str0", lf1suf.getValue());
-        assertEquals("121", lflst1suf_1.getValue());
-        assertEquals("131", lflst1suf_2.getValue());
-        assertEquals("str1", lflst1suf_3.getValue());
-
-        assertEquals(1, lst1suf.getChildren().size());
-
-        assertTrue(lst1suf.getChildren().get(0) instanceof SimpleNode<?>);
-        SimpleNode<?> lst11_lf11 = (SimpleNode<?>) lst1suf.getChildren().get(0);
-        assertEquals(nameSpace, lst11_lf11.getNodeType().getNamespace().toString());
-        assertEquals("lf11" + suf, lst11_lf11.getNodeType().getLocalName());
-        assertEquals("str2", lst11_lf11.getValue());
-
-        assertTrue(cont1suf.getChildren().get(0) instanceof SimpleNode<?>);
-        SimpleNode<?> cont1_lf11 = (SimpleNode<?>) cont1suf.getChildren().get(0);
-        assertEquals(nameSpace, cont1_lf11.getNodeType().getNamespace().toString());
-        assertEquals("lf11" + suf, cont1_lf11.getNodeType().getLocalName());
-        assertEquals((short) 100, cont1_lf11.getValue());
-    }
-
-    private CompositeNode compositeNodeFromXml(String xmlPath, boolean dummyNamespaces) {
-        XmlToCompositeNodeProvider xmlToCompositeNodeProvider = XmlToCompositeNodeProvider.INSTANCE;
-        try {
-            InputStream xmlStream = XmlToCnSnTest.class.getResourceAsStream(xmlPath);
-            CompositeNode compositeNode = xmlToCompositeNodeProvider.readFrom(null, null, null, null, null, xmlStream);
-            if (dummyNamespaces) {
-                try {
-                    TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) compositeNode);
-                    return ((CompositeNodeWrapper) compositeNode).unwrap();
-                } catch (URISyntaxException e) {
-                    LOG.error(e.getMessage());
-                    assertTrue(e.getMessage(), false);
-                }
-            }
-            return compositeNode;
-
-        } catch (WebApplicationException | IOException e) {
-            LOG.error(e.getMessage());
-            assertTrue(false);
-        }
-        return null;
-    }
-
-    private void testIdentityrefToCnSn(String xmlPath, String yangPath, String moduleName, String schemaName,
-            int moduleCount, String resultLocalName, String resultNamespace) {
-        CompositeNode compositeNode = compositeNodeFromXml(xmlPath, false);
-        assertNotNull(compositeNode);
-
-        Set<Module> modules = TestUtils.resolveModules(yangPath);
-        assertEquals(moduleCount, modules.size());
-        Module module = TestUtils.resolveModule(moduleName, modules);
-        assertNotNull(module);
-        DataSchemaNode dataSchemaNode = TestUtils.resolveDataSchemaNode(module, null);
-        assertNotNull(dataSchemaNode);
-
-        TestUtils.normalizeCompositeNode(compositeNode, modules, dataSchemaNode, moduleName + ":" + schemaName);
-
-        SimpleNode<?> lf11 = getLf11(compositeNode);
-        assertTrue(lf11.getValue() instanceof QName);
-        QName qName = (QName) lf11.getValue();
-        assertEquals(resultLocalName, qName.getLocalName());
-        assertEquals(resultNamespace, qName.getNamespace().toString());
-
-    }
-
-    private SimpleNode<?> getLf11(CompositeNode compositeNode) {
-        assertEquals("cont", compositeNode.getNodeType().getLocalName());
-
-        List<Node<?>> childs = compositeNode.getChildren();
-        assertEquals(1, childs.size());
-        Node<?> nd = childs.iterator().next();
-        assertTrue(nd instanceof CompositeNode);
-        assertEquals("cont1", nd.getNodeType().getLocalName());
-
-        childs = ((CompositeNode) nd).getChildren();
-        SimpleNode<?> lf11 = null;
-        for (Node<?> child : childs) {
-            assertTrue(child instanceof SimpleNode);
-            if (child.getNodeType().getLocalName().equals("lf11")) {
-                lf11 = (SimpleNode<?>) child;
-            }
-        }
-        assertNotNull(lf11);
-        return lf11;
+        assertNotNull(lf2);
+        assertTrue(lf2.getValue() instanceof String);
+        assertEquals("121", (String) lf2.getValue());
     }
 
 }
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/invalid-top-level-element/invalid-top-level-element.yang b/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/invalid-top-level-element/invalid-top-level-element.yang
new file mode 100644 (file)
index 0000000..a9df486
--- /dev/null
@@ -0,0 +1,13 @@
+module invalid-top-level-element {
+  namespace "invalid:top:level:element";  
+
+  prefix "intoleel";
+   revision 2013-12-17 {    
+  }
+  
+
+    leaf lf {
+        type string;
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/list/list-types-module b/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/list/list-types-module
new file mode 100644 (file)
index 0000000..9bdea81
--- /dev/null
@@ -0,0 +1,274 @@
+module simple-data-types {
+  namespace "simple:data:types";  
+
+  prefix "smpdtp";
+  revision 2013-11-12 {    
+  }
+  
+  identity iden {
+  }
+  
+  typedef tpdfempty {
+       type empty;
+  }
+  
+  typedef tpdfbit {
+       type bits {
+               bit b1;
+               bit b2;
+               bit b3;
+       }
+  }
+  
+  typedef tpdfun4 {
+       type boolean;
+  }
+  
+  typedef tpdfun3 {
+       type union {
+               type tpdfbit;
+               type tpdfempty;
+       }
+  }  
+  
+  typedef tpdfun2 {
+       type union {
+               type tpdfun3;
+               type tpdfun4;
+       }
+  }
+  
+  typedef tpdfun1 {
+       type union {
+               type uint8;
+               type decimal64 {
+                       fraction-digits 2;
+               }
+       }
+  }
+  
+  container cont {
+         leaf lfnint8Min {
+               type int8; 
+         }
+         leaf lfnint8Max {
+               type int8; 
+         }
+         leaf lfnint16Min {
+               type int16; 
+         }
+         leaf lfnint16Max {
+               type int16; 
+         }
+         leaf lfnint32Min {
+               type int32; 
+         }
+         leaf lfnint32Max {
+               type int32; 
+         }
+         leaf lfnint64Min {
+               type int64; 
+         }
+         leaf lfnint64Max {
+               type int64; 
+         }
+         
+         leaf lfnuint8Max {
+               type uint8; 
+         }
+         leaf lfnuint16Max {
+               type uint16; 
+         }
+         leaf lfnuint32Max {
+               type uint32; 
+         }
+         leaf lfuint64Max {
+               type uint64; 
+         }
+         leaf lfstr {
+               type string;
+         }       
+         leaf lfstr1 {
+               type string;
+         }       
+         leaf lfbool1 {
+               type boolean;
+         }       
+         leaf lfbool2 {
+               type boolean;
+         }       
+         leaf lfbool3 {
+               type boolean;
+         }       
+         leaf lfdecimal1 {
+               type decimal64 {
+                       fraction-digits 2;
+               }       
+         }       
+         leaf lfdecimal2 {
+               type decimal64 {
+                       fraction-digits 2;
+               }       
+         }       
+         leaf lfdecimal3 {
+               type decimal64 {
+                       fraction-digits 2;
+               }       
+         }      
+          
+         leaf lfdecimal4 {
+               type decimal64 {
+                       fraction-digits 2;
+               }       
+         }
+                 
+         
+         leaf lfdecimal6 {
+               type decimal64 {
+                       fraction-digits 2;
+               }       
+         }       
+
+    leaf lfenum {
+      type enumeration {
+        enum enum1;
+        enum enum2;
+        enum enum3;
+        enum enum4;
+      }
+    }
+
+    leaf lfbits {
+      type bits {
+        bit bit1;
+        bit bit2;
+        bit bit3;
+        bit bit4;
+      }
+    }  
+    
+    leaf lfbinary {
+       type binary;
+    }  
+    
+    leaf lfref1 {                  //reference to string type
+       type leafref {
+               path "../lfstr";
+       }
+    }
+    
+    leaf lfref2 {                  //reference to number type
+       type leafref {
+               path "../lfnint8Max";
+       }
+    }
+    
+    leaf lfempty {
+       type empty;
+    }
+    
+    leaf lfunion1 {
+       type union {
+               type uint16;
+               type string;
+       }
+    }
+    leaf lfunion2 {
+       type union {
+               type decimal64 {
+                               fraction-digits 2;              
+               }
+               type string;
+       }
+    }
+    
+    leaf lfunion3 {
+       type union {
+               type empty;
+               type string;
+       }
+    }
+    
+    leaf lfunion4 {
+       type union {
+               type boolean;
+               type string;
+       }
+    }
+    
+    leaf lfunion5 {
+       type union {
+               type uint16;
+               type string;
+       }
+    }
+    
+    leaf lfunion6 {
+       type union {
+               type uint16;
+               type empty;
+       }
+    }
+    
+    leaf lfunion7 {
+               type tpdfun3;
+    }
+    
+    leaf lfunion8 {
+       type union {
+               type uint16;
+               type string;
+       }
+    }
+    
+    leaf lfunion9 {
+       type union {
+               type uint16;
+               type boolean;                   
+       }
+    }
+    
+    leaf lfunion10 {
+       type union {
+               type bits {
+                       bit bt1;
+                       bit bt2;
+               }
+               type boolean;                   
+       }
+    }
+    
+    leaf lfunion11 {
+               type union {
+                       type tpdfun1;
+                       type tpdfun2;
+               }
+    }
+    
+    leaf lfunion12 {
+               type tpdfun2;
+    }
+    
+    leaf lfunion13 {
+        type tpdfbit;    
+    }
+        
+    leaf lfunion14 {
+        type union {
+            type enumeration {
+                enum zero;
+                enum one;
+            }
+            type uint16;
+        }    
+    }    
+    
+    leaf identityref1 {
+        type identityref {
+            base iden;
+        }
+    }
+         
+         
+  }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-xml/choice/module-with-choice.yang b/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-xml/choice/module-with-choice.yang
new file mode 100644 (file)
index 0000000..8454784
--- /dev/null
@@ -0,0 +1,25 @@
+module module-with-choice {
+  namespace "module:with:choice";  
+
+  prefix "mowicho";
+  
+  revision 2013-12-18 {    
+  }
+  
+
+  container cont {
+    choice choA {
+        case caA1 {
+            leaf lf1 {
+                type string;
+            }
+        }
+        case caA2 {
+            leaf lf2 {
+                type string;
+            }
+        } 
+    }
+  }    
+         
+}
\ No newline at end of file
index 7023c94f2f0df55d00efaf6c675629a184deba78..81d77329c69eaa74d28c19d942ec1b2593a538ec 100644 (file)
@@ -91,6 +91,12 @@ module basic-module {
                  }
                }
                
+               leaf lfLfref {
+                 type leafref {
+                     path "/cont/lfBoolean";
+                 }    
+               }
+               
        }
          
 }
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/leafref/json/data.json b/opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/leafref/json/data.json
new file mode 100644 (file)
index 0000000..235666e
--- /dev/null
@@ -0,0 +1,6 @@
+{
+    "cont":{
+        "lf1":121,
+        "lf2":121
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/leafref/leafref-module b/opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/leafref/leafref-module
new file mode 100644 (file)
index 0000000..8ca9f09
--- /dev/null
@@ -0,0 +1,19 @@
+module leafref-module {
+  namespace "leafref:module";  
+
+  prefix "lfrfmo";
+  revision 2013-11-18 {    
+  }
+
+    container cont {
+        leaf lf1 {
+            type int32;
+        }
+        leaf lf2 {
+            type leafref {
+                path "/cont/lf1"; 
+            }
+        }
+    }
+  
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/unsupported-json-format.json b/opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/unsupported-json-format.json
new file mode 100644 (file)
index 0000000..abc6267
--- /dev/null
@@ -0,0 +1 @@
+fffff
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/leafref-module b/opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/leafref-module
new file mode 100644 (file)
index 0000000..8ca9f09
--- /dev/null
@@ -0,0 +1,19 @@
+module leafref-module {
+  namespace "leafref:module";  
+
+  prefix "lfrfmo";
+  revision 2013-11-18 {    
+  }
+
+    container cont {
+        leaf lf1 {
+            type int32;
+        }
+        leaf lf2 {
+            type leafref {
+                path "/cont/lf1"; 
+            }
+        }
+    }
+  
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/xml/data.xml b/opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/xml/data.xml
new file mode 100644 (file)
index 0000000..06200a6
--- /dev/null
@@ -0,0 +1,4 @@
+<cont>
+    <lf1>121</lf1>
+    <lf2>121</lf2>
+</cont>
\ No newline at end of file
index 30f98cedd330ee1fac7933824e3fb8da46e57de8..aa6e99a03f978a4604fe72ea4ba36307a6bdaa80 100644 (file)
@@ -847,9 +847,7 @@ public class StatisticsUpdateCommiter implements OpendaylightGroupStatisticsList
         }
         if (storedFlow.getInPort()== null) {
             if (statsFlow.getInPort() != null) {
-                if(statsFlow.getInPort()!= 0){
-                    return false;
-                }
+                return false;
             }
         } else if(!storedFlow.getInPort().equals(statsFlow.getInPort())) {
             return false;
index d5dee32e40ef74e49fb80fb9e9eba284917a6c2b..c0bcbaa8ad1684daa531f7594898f016d154069d 100644 (file)
@@ -1,7 +1,6 @@
 package org.opendaylight.md.controller.topology.lldp.utils;
 
 import java.nio.charset.Charset;
-import java.util.List;
 
 import org.opendaylight.controller.sal.packet.Ethernet;
 import org.opendaylight.controller.sal.packet.LLDP;
@@ -46,10 +45,6 @@ public class LLDPDiscoveryUtils {
             LLDP lldp = (LLDP) ethPkt.getPayload();
     
             try {
-                List<LLDPTLV> optionalTLVList = lldp.getOptionalTLVList();
-                if (optionalTLVList == null) {
-                    return null;
-                }
                 NodeId srcNodeId = null;
                 NodeConnectorId srcNodeConnectorId = null;
                 for (LLDPTLV lldptlv : lldp.getOptionalTLVList()) {
@@ -61,12 +56,13 @@ public class LLDPDiscoveryUtils {
                         srcNodeId = new NodeId(srcNodeIdString);
                     }
                 }
-                
-                InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
-                        .child(Node.class,new NodeKey(srcNodeId))
-                        .child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
-                        .toInstance();
-                return new NodeConnectorRef(srcInstanceId);
+                if(srcNodeId != null && srcNodeConnectorId != null) {
+                    InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
+                            .child(Node.class,new NodeKey(srcNodeId))
+                            .child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
+                            .toInstance();
+                    return new NodeConnectorRef(srcInstanceId);
+                }
             } catch (Exception e) {
                 LOG.warn("Caught exception ", e);
             }
index 1d4211a9267e25a1399f48d99c145cdb6bf5b6fa..ca37f4b7c19658ca14facf9af29d6d83d2cd07cb 100644 (file)
@@ -8,8 +8,10 @@
 
 package org.opendaylight.controller.web;
 
+import java.io.FileInputStream;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Properties;
 import java.util.Set;
 
 import javax.servlet.http.HttpServletRequest;
@@ -28,6 +30,7 @@ import org.opendaylight.controller.sal.utils.StatusCode;
 import org.opendaylight.controller.usermanager.IUserManager;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.ResponseBody;
@@ -52,6 +55,23 @@ public class DaylightWeb {
         return "main";
     }
 
+    /**
+     * Read the version.properties file for the property
+     *
+     * @param request
+     * @return String value configured in the version.properties file
+     */
+    @RequestMapping(value="/versionProperty/{property}", method = RequestMethod.GET)
+    @ResponseBody
+    public String getVersion(HttpServletRequest request, @PathVariable("property") String property) {
+        Properties prop = new Properties();
+        try {
+            prop.load(new FileInputStream("version.properties"));
+            return prop.getProperty(property+".version");
+        } catch (Exception e) {
+            return null;
+        }
+    }
     @RequestMapping(value = "web.json")
     @ResponseBody
     public Map<String, Map<String, Object>> bundles(HttpServletRequest request) {
index 89812af53df5447ef4426dd49ce312aff6f87a43..072f08f581eadb4b6b9290c92e93776f7b560c87 100644 (file)
@@ -46,6 +46,7 @@
              <url-pattern>/images/*</url-pattern>
              <url-pattern>/css/*</url-pattern>
              <url-pattern>/favicon.ico</url-pattern>
+             <url-pattern>/versionProperty/*</url-pattern>
           </web-resource-collection>
         </security-constraint>