Merge "Bug 1303: BindingIndependentConnector splitted."
authorTony Tkacik <ttkacik@cisco.com>
Tue, 15 Jul 2014 10:35:27 +0000 (10:35 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Tue, 15 Jul 2014 10:35:27 +0000 (10:35 +0000)
89 files changed:
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/Bug1125RegressionTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/listener/NetconfDeviceCommunicator.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceSalProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/Draft02.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfService.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/package-info.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/gson/JsonParser.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/JsonToCompositeNodeProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeReader.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestUtil.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfApplication.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfDocumentedExceptionMapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToJsonProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.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/rest/impl/XmlToCompositeNodeReader.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/package-info.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/CompositeNodeWrapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/EmptyNodeWrapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/IdentityValuesDTO.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/InstanceIdWithSchemaNode.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/NodeWrapper.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/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfDocumentedException.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfError.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/SimpleNodeWrapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/package-info.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/AbstractRpcExecutor.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/BrokerRpcExecutor.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/MountPointRpcExecutor.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/RpcExecutor.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/Notificator.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServer.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerHandler.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerInitializer.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonBasicYangTypesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonChoiceCaseTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIdentityrefTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonNotExistingLeafTypeTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithDataFromSeveralModulesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnInstanceIdentifierToXmlTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlNotExistingLeafTypeTest.java
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
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithDataFromSeveralModulesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.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
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java
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/BrokerFacadeTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CodecsExceptionsCatchingTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyFuture.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyRpcResult.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java
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/MultipleEqualNamesForDataNodesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/NormalizeNodeTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestCodecExceptionsTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestDeleteOperationTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetAugmentedElementWhenEqualNamesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPostOperationTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfDocumentedExceptionMapperTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfErrorTest.java
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/URITest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnInstanceIdentifierTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.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/test/structures/LstItem.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/client/WebSocketClient.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/client/WebSocketClientHandler.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/test/RestStream.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlAugmentedElementToCnSnTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java
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/full-versions/test-module/test-module
opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/AbstractNetconfSessionNegotiator.java

diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/Bug1125RegressionTest.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/Bug1125RegressionTest.java
new file mode 100644 (file)
index 0000000..9f1ae38
--- /dev/null
@@ -0,0 +1,99 @@
+package org.opendaylight.controller.md.sal.binding.impl.test;
+
+import static org.opendaylight.controller.md.sal.binding.test.AssertCollections.assertContains;
+import static org.opendaylight.controller.md.sal.binding.test.AssertCollections.assertEmpty;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.TOP_FOO_KEY;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.path;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.topLevelList;
+
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.binding.test.AbstractDataChangeListenerTest;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeComplexUsesAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeComplexUsesAugmentBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.complex.from.grouping.ContainerWithUsesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.TopBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+/**
+ * Regression test suite for Bug 1125 - Can't detect switch disconnection
+ * https://bugs.opendaylight.org/show_bug.cgi?id=1125
+ */
+public class Bug1125RegressionTest extends AbstractDataChangeListenerTest {
+
+    private static final InstanceIdentifier<Top> TOP_PATH = InstanceIdentifier
+            .create(Top.class);
+    private static final InstanceIdentifier<TopLevelList> TOP_FOO_PATH = TOP_PATH
+            .child(TopLevelList.class, TOP_FOO_KEY);
+
+    private static final InstanceIdentifier<TreeComplexUsesAugment> FOO_AUGMENT_PATH = TOP_FOO_PATH
+            .augmentation(TreeComplexUsesAugment.class);
+
+    private static final InstanceIdentifier<TreeComplexUsesAugment> WILDCARDED_AUGMENT_PATH = TOP_PATH
+            .child(TopLevelList.class).augmentation(
+                    TreeComplexUsesAugment.class);
+
+    private void writeInitialState() {
+        WriteTransaction initialTx = getDataBroker().newWriteOnlyTransaction();
+        initialTx.put(LogicalDatastoreType.OPERATIONAL, TOP_PATH,
+                new TopBuilder().build());
+        TreeComplexUsesAugment fooAugment = new TreeComplexUsesAugmentBuilder()
+                .setContainerWithUses(
+                        new ContainerWithUsesBuilder().setLeafFromGrouping(
+                                "foo").build()).build();
+        initialTx.put(LogicalDatastoreType.OPERATIONAL, path(TOP_FOO_KEY),
+                topLevelList(TOP_FOO_KEY, fooAugment));
+        assertCommit(initialTx.commit());
+    }
+
+    private void delete(final InstanceIdentifier<?> path) {
+        WriteTransaction tx = getDataBroker().newWriteOnlyTransaction();
+        tx.delete(LogicalDatastoreType.OPERATIONAL, path);
+        assertCommit(tx.commit());
+    }
+
+    private void verifyRemoved(
+            final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event) {
+        assertEmpty(event.getCreatedData());
+        assertEmpty(event.getUpdatedData());
+        assertContains(event.getRemovedPaths(), FOO_AUGMENT_PATH);
+    }
+
+    private void deleteAndListenAugment(final DataChangeScope scope,
+            final InstanceIdentifier<?> path) {
+        writeInitialState();
+        TestListener listener = createListener(
+                LogicalDatastoreType.OPERATIONAL, WILDCARDED_AUGMENT_PATH,
+                scope);
+        delete(path);
+        verifyRemoved(listener.event());
+    }
+
+    @Test
+    public void deleteAndListenAugment() {
+
+        deleteAndListenAugment(DataChangeScope.ONE, TOP_PATH);
+
+        deleteAndListenAugment(DataChangeScope.BASE, TOP_PATH);
+
+        deleteAndListenAugment(DataChangeScope.SUBTREE, TOP_PATH);
+
+        deleteAndListenAugment(DataChangeScope.BASE, TOP_FOO_PATH);
+
+        deleteAndListenAugment(DataChangeScope.ONE, TOP_FOO_PATH);
+
+        deleteAndListenAugment(DataChangeScope.SUBTREE, TOP_FOO_PATH);
+
+        deleteAndListenAugment(DataChangeScope.BASE, FOO_AUGMENT_PATH);
+
+        deleteAndListenAugment(DataChangeScope.ONE, FOO_AUGMENT_PATH);
+
+        deleteAndListenAugment(DataChangeScope.SUBTREE, FOO_AUGMENT_PATH);
+    }
+}
index 9fa68eeea6f87c7f1a4cb4634b0759a61cc2f83e..f36ad9abcbabb397358e80a07bb38f70996b3afa 100644 (file)
@@ -86,9 +86,9 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
                                            final NetconfClientConfiguration config) {
         if(config instanceof NetconfReconnectingClientConfiguration) {
             dispatch.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
+        } else {
+            dispatch.createClient(config);
         }
-
-        dispatch.createClient(config);
     }
 
     private void tearDown( String reason ) {
index 01af84c9acf72057ec02b4b9123525f81cf00cd7..fc54bfbc3d8f0b93ec58d9df664b26815a500184 100644 (file)
@@ -7,9 +7,9 @@
  */
 package org.opendaylight.controller.sal.connect.netconf.sal;
 
+import com.google.common.base.Preconditions;
 import java.util.Collection;
 import java.util.Collections;
-
 import java.util.concurrent.ExecutorService;
 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
 import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
@@ -23,8 +23,6 @@ import org.opendaylight.yangtools.yang.binding.RpcService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Preconditions;
-
 final class NetconfDeviceSalProvider implements AutoCloseable, Provider, BindingAwareProvider {
 
     private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceSalProvider.class);
@@ -41,13 +39,13 @@ final class NetconfDeviceSalProvider implements AutoCloseable, Provider, Binding
 
     public MountProvisionInstance getMountInstance() {
         Preconditions.checkState(mountInstance != null,
-                "%s: Sal provider was not initialized by sal. Cannot publish notification", id);
+                "%s: Sal provider was not initialized by sal. Cannot get mount instance", id);
         return mountInstance;
     }
 
     public NetconfDeviceDatastoreAdapter getDatastoreAdapter() {
         Preconditions.checkState(datastoreAdapter != null,
-                "%s: Sal provider %s was not initialized by sal. Cannot publish notification", id);
+                "%s: Sal provider %s was not initialized by sal. Cannot get datastore adapter", id);
         return datastoreAdapter;
     }
 
index af763cce0d20e0b03a76a1321580dcd71571446c..51ac43be7c7e27c1a8d32ef12f675e910309f725 100644 (file)
@@ -47,26 +47,24 @@ public class Draft02 {
 
         String ERROR_LIST_SCHEMA_NODE = "error";
 
-        QName IETF_RESTCONF_QNAME = QName.create( Draft02.RestConfModule.NAMESPACE,
-                                                  Draft02.RestConfModule.REVISION,
-                                                  Draft02.RestConfModule.NAME );
+        QName IETF_RESTCONF_QNAME = QName.create(Draft02.RestConfModule.NAMESPACE, Draft02.RestConfModule.REVISION,
+                Draft02.RestConfModule.NAME);
 
-        QName ERRORS_CONTAINER_QNAME = QName.create( IETF_RESTCONF_QNAME, ERRORS_CONTAINER_SCHEMA_NODE );
+        QName ERRORS_CONTAINER_QNAME = QName.create(IETF_RESTCONF_QNAME, ERRORS_CONTAINER_SCHEMA_NODE);
 
-        QName ERROR_LIST_QNAME = QName.create( IETF_RESTCONF_QNAME, ERROR_LIST_SCHEMA_NODE );
+        QName ERROR_LIST_QNAME = QName.create(IETF_RESTCONF_QNAME, ERROR_LIST_SCHEMA_NODE);
 
-        QName ERROR_TYPE_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-type" );
+        QName ERROR_TYPE_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-type");
 
-        QName ERROR_TAG_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-tag" );
+        QName ERROR_TAG_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-tag");
 
-        QName ERROR_APP_TAG_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-app-tag" );
+        QName ERROR_APP_TAG_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-app-tag");
 
-        QName ERROR_MESSAGE_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-message" );
+        QName ERROR_MESSAGE_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-message");
 
-        QName ERROR_INFO_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-info" );
+        QName ERROR_INFO_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-info");
     }
 
-
     public static interface Paths {
 
     }
index 2f11d8ed7d72d40282c37ac437de530351efc151..a6c4ea5ab8d7877930983ed782d4cbc318def278 100644 (file)
@@ -25,23 +25,20 @@ import org.opendaylight.controller.sal.restconf.impl.StructuredData;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
 /**
- * The URI hierarchy for the RESTCONF resources consists of an entry point
- * container, 4 top-level resources, and 1 field.
+ * The URI hierarchy for the RESTCONF resources consists of an entry point container, 4 top-level resources, and 1
+ * field.
  * <ul>
  * <li><b>/restconf</b> - {@link #getRoot()}
  * <ul>
- * <li><b>/config</b> - {@link #readConfigurationData(String)}
- * {@link #updateConfigurationData(String, CompositeNode)}
- * {@link #createConfigurationData(CompositeNode)}
- * {@link #createConfigurationData(String, CompositeNode)}
+ * <li><b>/config</b> - {@link #readConfigurationData(String)} {@link #updateConfigurationData(String, CompositeNode)}
+ * {@link #createConfigurationData(CompositeNode)} {@link #createConfigurationData(String, CompositeNode)}
  * {@link #deleteConfigurationData(String)}
  * <li><b>/operational</b> - {@link #readOperationalData(String)}
  * <li>/modules - {@link #getModules()}
  * <ul>
  * <li>/module
  * </ul>
- * <li><b>/operations</b> - {@link #invokeRpc(String, CompositeNode)}
- * {@link #invokeRpc(String, CompositeNode)}
+ * <li><b>/operations</b> - {@link #invokeRpc(String, CompositeNode)} {@link #invokeRpc(String, CompositeNode)}
  * <li>/version (field)
  * </ul>
  * </ul>
@@ -93,7 +90,8 @@ public interface RestconfService {
     @Consumes({ Draft02.MediaTypes.OPERATION + JSON, Draft02.MediaTypes.OPERATION + XML,
             Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
             MediaType.APPLICATION_XML, MediaType.TEXT_XML })
-    public StructuredData invokeRpc(@Encoded @PathParam("identifier") String identifier, CompositeNode payload, @Context UriInfo uriInfo);
+    public StructuredData invokeRpc(@Encoded @PathParam("identifier") String identifier, CompositeNode payload,
+            @Context UriInfo uriInfo);
 
     @POST
     @Path("/operations/{identifier:.+}")
@@ -114,7 +112,8 @@ public interface RestconfService {
     @Path("/operational/{identifier:.+}")
     @Produces({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
             MediaType.APPLICATION_XML, MediaType.TEXT_XML })
-    public StructuredData readOperationalData(@Encoded @PathParam("identifier") String identifier, @Context UriInfo uriInfo);
+    public StructuredData readOperationalData(@Encoded @PathParam("identifier") String identifier,
+            @Context UriInfo uriInfo);
 
     @PUT
     @Path("/config/{identifier:.+}")
index f3b61de45768aaf63a992e883c0cbf19b25fec74..a784be2adca3128cfc74134a3dcd9267528f5538 100644 (file)
@@ -22,8 +22,8 @@ import java.io.EOFException;
 import java.io.IOException;
 
 /**
- * This class parses JSON elements from a gson JsonReader. It disallows multiple
- * elements of the same name unlike the default gson JsonParser."
+ * This class parses JSON elements from a gson JsonReader. It disallows multiple elements of the same name unlike the
+ * default gson JsonParser."
  */
 public class JsonParser {
     public JsonElement parse(JsonReader reader) throws JsonIOException, JsonSyntaxException {
index 85b4b2dee071aff3be08fb82b11690a8793d7014..4b4cef9f70873b2c34858de93e529d91d0ea7a5e 100644 (file)
@@ -11,16 +11,13 @@ import static com.google.common.base.Preconditions.checkNotNull;
 
 import com.google.common.base.Preconditions;
 import com.google.gson.stream.JsonWriter;
-
 import java.io.IOException;
 import java.net.URI;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
-
 import javax.activation.UnsupportedDataTypeException;
-
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
@@ -80,100 +77,95 @@ class JsonMapper {
         writer.endObject();
     }
 
-    private void writeChildrenOfParent(final JsonWriter writer, final CompositeNode parent, final DataNodeContainer parentSchema)
-            throws IOException {
+    private void writeChildrenOfParent(final JsonWriter writer, final CompositeNode parent,
+            final DataNodeContainer parentSchema) throws IOException {
         checkNotNull(parent);
 
         final Set<QName> foundLists = new HashSet<>();
 
-        Set<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ?
-                Collections.<DataSchemaNode>emptySet() : parentSchema.getChildNodes();
-
+        Set<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ? Collections.<DataSchemaNode> emptySet()
+                : parentSchema.getChildNodes();
 
-                for (Node<?> child : parent.getValue()) {
-                    DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes);
+        for (Node<?> child : parent.getValue()) {
+            DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes);
 
-                    if (childSchema == null) {
-                        // Node may not conform to schema or allows "anyxml" - we'll process it.
+            if (childSchema == null) {
+                // Node may not conform to schema or allows "anyxml" - we'll process it.
 
-                        LOG.debug("No schema found for data node \"{}\"", child.getNodeType());
+                LOG.debug("No schema found for data node \"{}\"", child.getNodeType());
 
-                        if( !foundLists.contains( child.getNodeType() ) ) {
-                            handleNoSchemaFound( writer, child, parent );
+                if (!foundLists.contains(child.getNodeType())) {
+                    handleNoSchemaFound(writer, child, parent);
 
-                            // Since we don't have a schema, we don't know which nodes are supposed to be
-                            // lists so treat every one as a potential list to avoid outputting duplicates.
+                    // Since we don't have a schema, we don't know which nodes are supposed to be
+                    // lists so treat every one as a potential list to avoid outputting duplicates.
 
-                            foundLists.add( child.getNodeType() );
-                        }
-                    }
-                    else if (childSchema instanceof ContainerSchemaNode) {
-                        Preconditions.checkState(child instanceof CompositeNode,
-                                "Data representation of Container should be CompositeNode - %s", child.getNodeType());
-                        writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema);
-                    } else if (childSchema instanceof ListSchemaNode) {
-                        if (!foundLists.contains( child.getNodeType() ) ) {
-                            Preconditions.checkState(child instanceof CompositeNode,
-                                    "Data representation of List should be CompositeNode - %s", child.getNodeType());
-                            foundLists.add( child.getNodeType() );
-                            writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema);
-                        }
-                    } else if (childSchema instanceof LeafListSchemaNode) {
-                        if (!foundLists.contains( child.getNodeType() ) ) {
-                            Preconditions.checkState(child instanceof SimpleNode<?>,
-                                    "Data representation of LeafList should be SimpleNode - %s", child.getNodeType());
-                            foundLists.add( child.getNodeType() );
-                            writeLeafList(writer, parent, (SimpleNode<?>) child, (LeafListSchemaNode) childSchema);
-                        }
-                    } else if (childSchema instanceof LeafSchemaNode) {
-                        Preconditions.checkState(child instanceof SimpleNode<?>,
-                                "Data representation of LeafList should be SimpleNode - %s", child.getNodeType());
-                        writeLeaf(writer, (SimpleNode<?>) child, (LeafSchemaNode) childSchema);
-                    } else if (childSchema instanceof AnyXmlSchemaNode) {
-                        if( child instanceof CompositeNode ) {
-                            writeContainer(writer, (CompositeNode) child, null);
-                        }
-                        else {
-                            handleNoSchemaFound( writer, child, parent );
-                        }
-                    } else {
-                        throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
-                                + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
-                    }
+                    foundLists.add(child.getNodeType());
+                }
+            } else if (childSchema instanceof ContainerSchemaNode) {
+                Preconditions.checkState(child instanceof CompositeNode,
+                        "Data representation of Container should be CompositeNode - %s", child.getNodeType());
+                writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema);
+            } else if (childSchema instanceof ListSchemaNode) {
+                if (!foundLists.contains(child.getNodeType())) {
+                    Preconditions.checkState(child instanceof CompositeNode,
+                            "Data representation of List should be CompositeNode - %s", child.getNodeType());
+                    foundLists.add(child.getNodeType());
+                    writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema);
+                }
+            } else if (childSchema instanceof LeafListSchemaNode) {
+                if (!foundLists.contains(child.getNodeType())) {
+                    Preconditions.checkState(child instanceof SimpleNode<?>,
+                            "Data representation of LeafList should be SimpleNode - %s", child.getNodeType());
+                    foundLists.add(child.getNodeType());
+                    writeLeafList(writer, parent, (SimpleNode<?>) child, (LeafListSchemaNode) childSchema);
+                }
+            } else if (childSchema instanceof LeafSchemaNode) {
+                Preconditions.checkState(child instanceof SimpleNode<?>,
+                        "Data representation of LeafList should be SimpleNode - %s", child.getNodeType());
+                writeLeaf(writer, (SimpleNode<?>) child, (LeafSchemaNode) childSchema);
+            } else if (childSchema instanceof AnyXmlSchemaNode) {
+                if (child instanceof CompositeNode) {
+                    writeContainer(writer, (CompositeNode) child, null);
+                } else {
+                    handleNoSchemaFound(writer, child, parent);
                 }
+            } else {
+                throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
+                        + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
+            }
+        }
     }
 
     private static void writeValue(final JsonWriter writer, final Object value) throws IOException {
         writer.value(value == null ? "" : String.valueOf(value));
     }
 
-    private void handleNoSchemaFound( final JsonWriter writer, final Node<?> node,
-            final CompositeNode parent ) throws IOException {
-        if( node instanceof SimpleNode<?> ) {
-            List<SimpleNode<?>> nodeLeafList = parent.getSimpleNodesByName( node.getNodeType() );
-            if( nodeLeafList.size() == 1 ) {
-                writeName( node, null, writer );
-                writeValue( writer, node.getValue() );
-            }
-            else { // more than 1, write as a json array
-                writeName( node, null, writer );
+    private void handleNoSchemaFound(final JsonWriter writer, final Node<?> node, final CompositeNode parent)
+            throws IOException {
+        if (node instanceof SimpleNode<?>) {
+            List<SimpleNode<?>> nodeLeafList = parent.getSimpleNodesByName(node.getNodeType());
+            if (nodeLeafList.size() == 1) {
+                writeName(node, null, writer);
+                writeValue(writer, node.getValue());
+            } else { // more than 1, write as a json array
+                writeName(node, null, writer);
                 writer.beginArray();
-                for( SimpleNode<?> leafNode: nodeLeafList ) {
-                    writeValue( writer, leafNode.getValue() );
+                for (SimpleNode<?> leafNode : nodeLeafList) {
+                    writeValue(writer, leafNode.getValue());
                 }
 
                 writer.endArray();
             }
         } else { // CompositeNode
-            Preconditions.checkState( node instanceof CompositeNode,
+            Preconditions.checkState(node instanceof CompositeNode,
                     "Data representation of Container should be CompositeNode - %s", node.getNodeType());
 
-            List<CompositeNode> nodeList = parent.getCompositesByName( node.getNodeType() );
-            if( nodeList.size() == 1 ) {
-                writeContainer( writer, (CompositeNode) node, null );
-            }
-            else { // more than 1, write as a json array
-                writeList( writer, parent, (CompositeNode) node, null );
+            List<CompositeNode> nodeList = parent.getCompositesByName(node.getNodeType());
+            if (nodeList.size() == 1) {
+                writeContainer(writer, (CompositeNode) node, null);
+            } else { // more than 1, write as a json array
+                writeList(writer, parent, (CompositeNode) node, null);
             }
         }
     }
@@ -195,15 +187,16 @@ class JsonMapper {
         return null;
     }
 
-    private void writeContainer(final JsonWriter writer, final CompositeNode node, final ContainerSchemaNode schema) throws IOException {
+    private void writeContainer(final JsonWriter writer, final CompositeNode node, final ContainerSchemaNode schema)
+            throws IOException {
         writeName(node, schema, writer);
         writer.beginObject();
         writeChildrenOfParent(writer, node, schema);
         writer.endObject();
     }
 
-    private void writeList(final JsonWriter writer, final CompositeNode nodeParent, final CompositeNode node, final ListSchemaNode schema)
-            throws IOException {
+    private void writeList(final JsonWriter writer, final CompositeNode nodeParent, final CompositeNode node,
+            final ListSchemaNode schema) throws IOException {
         writeName(node, schema, writer);
         writer.beginArray();
 
@@ -235,19 +228,20 @@ class JsonMapper {
         writer.endArray();
     }
 
-    private void writeLeaf(final JsonWriter writer, final SimpleNode<?> node, final LeafSchemaNode schema) throws IOException {
+    private void writeLeaf(final JsonWriter writer, final SimpleNode<?> node, final LeafSchemaNode schema)
+            throws IOException {
         writeName(node, schema, writer);
         writeValueOfNodeByType(writer, node, schema.getType(), schema);
     }
 
-    private void writeValueOfNodeByType(final JsonWriter writer, final SimpleNode<?> node, final TypeDefinition<?> type,
-            final DataSchemaNode schema) throws IOException {
+    private void writeValueOfNodeByType(final JsonWriter writer, final SimpleNode<?> node,
+            final TypeDefinition<?> type, final DataSchemaNode schema) throws IOException {
 
         TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(type);
 
         if (node.getValue() == null && !(baseType instanceof EmptyTypeDefinition)) {
-            LOG.debug("While generationg JSON output null value was found for type {}.",
-                    baseType.getClass().getSimpleName());
+            LOG.debug("While generationg JSON output null value was found for type {}.", baseType.getClass()
+                    .getSimpleName());
         }
 
         if (baseType instanceof IdentityrefTypeDefinition) {
@@ -292,7 +286,8 @@ class JsonMapper {
         }
     }
 
-    private static void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO) throws IOException {
+    private static void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO)
+            throws IOException {
         StringBuilder result = new StringBuilder();
         for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) {
             result.append('/');
@@ -327,12 +322,11 @@ class JsonMapper {
         result.append(identityValue.getValue());
     }
 
-    private static void writeStringRepresentation(final JsonWriter writer, final SimpleNode<?> node, final TypeDefinition<?> baseType,
-            final Class<?> requiredType) throws IOException {
+    private static void writeStringRepresentation(final JsonWriter writer, final SimpleNode<?> node,
+            final TypeDefinition<?> baseType, final Class<?> requiredType) throws IOException {
         Object value = node.getValue();
-        LOG.debug("Value of {}:{} is not instance of {} but is {}",
-                baseType.getQName().getNamespace(), baseType.getQName().getLocalName(),
-                requiredType.getClass(), node.getValue().getClass());
+        LOG.debug("Value of {}:{} is not instance of {} but is {}", baseType.getQName().getNamespace(), baseType
+                .getQName().getLocalName(), requiredType.getClass(), node.getValue().getClass());
         if (value == null) {
             writer.value("");
         } else {
@@ -348,7 +342,7 @@ class JsonMapper {
 
     private void writeName(final Node<?> node, final DataSchemaNode schema, final JsonWriter writer) throws IOException {
         String nameForOutput = node.getNodeType().getLocalName();
-        if ( schema != null && schema.isAugmenting()) {
+        if (schema != null && schema.isAugmenting()) {
             ControllerContext contContext = ControllerContext.getInstance();
             CharSequence moduleName = null;
             if (mountPoint == null) {
index 211e7e818a90bf2b3af9af67a5c693d86fb32ab7..2f3499e26968e17e9fa5f662ab66063965657815 100644 (file)
@@ -28,32 +28,30 @@ import org.slf4j.LoggerFactory;
 
 @Provider
 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
-    MediaType.APPLICATION_JSON })
+        MediaType.APPLICATION_JSON })
 public enum JsonToCompositeNodeProvider implements MessageBodyReader<CompositeNode> {
     INSTANCE;
 
     private final static Logger LOG = LoggerFactory.getLogger(JsonToCompositeNodeProvider.class);
 
     @Override
-    public boolean isReadable(final Class<?> type, final Type genericType,
-                              final Annotation[] annotations, final MediaType mediaType) {
+    public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+            final MediaType mediaType) {
         return true;
     }
 
     @Override
     public CompositeNode readFrom(final Class<CompositeNode> type, final Type genericType,
-                                  final Annotation[] annotations, final MediaType mediaType,
-                                  final MultivaluedMap<String, String> httpHeaders,
-                                  final InputStream entityStream)
-                                          throws IOException, WebApplicationException {
+            final Annotation[] annotations, final MediaType mediaType,
+            final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
+            WebApplicationException {
         try {
             return JsonToCompositeNodeReader.read(entityStream);
         } catch (Exception e) {
-            LOG.debug( "Error parsing json input", e);
+            LOG.debug("Error parsing json input", e);
 
-            throw new RestconfDocumentedException(
-                    "Error parsing input: " + e.getMessage(),
-                    ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
+            throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
+                    ErrorTag.MALFORMED_MESSAGE);
         }
     }
 }
index 082675b6d135e4fa3be05017a34a2ff584da9008..5fbb60555814f11267bba0012a650adf4b040b0d 100644 (file)
@@ -13,14 +13,12 @@ import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
 import com.google.gson.JsonPrimitive;
 import com.google.gson.stream.JsonReader;
-
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.URI;
-import java.util.Map.Entry;
 import java.util.Iterator;
+import java.util.Map.Entry;
 import java.util.Set;
-
 import org.opendaylight.controller.sal.rest.gson.JsonParser;
 import org.opendaylight.controller.sal.rest.impl.RestUtil.PrefixMapingFromJson;
 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
@@ -38,12 +36,10 @@ class JsonToCompositeNodeReader {
 
     }
 
-    public static CompositeNodeWrapper read(final InputStream entityStream)
-                                                      throws UnsupportedFormatException {
+    public static CompositeNodeWrapper read(final InputStream entityStream) throws UnsupportedFormatException {
         JsonParser parser = new JsonParser();
 
-        JsonElement rootElement = parser.parse(new JsonReader(
-                                                    new InputStreamReader(entityStream)));
+        JsonElement rootElement = parser.parse(new JsonReader(new InputStreamReader(entityStream)));
         if (rootElement.isJsonNull()) {
             // no content, so return null to indicate no input
             return null;
@@ -53,8 +49,7 @@ class JsonToCompositeNodeReader {
             throw new UnsupportedFormatException("Root element of Json has to be Object");
         }
 
-        Set<Entry<String, JsonElement>> entrySetsOfRootJsonObject =
-                                                  rootElement.getAsJsonObject().entrySet();
+        Set<Entry<String, JsonElement>> entrySetsOfRootJsonObject = rootElement.getAsJsonObject().entrySet();
         if (entrySetsOfRootJsonObject.size() != 1) {
             throw new UnsupportedFormatException("Json Object should contain one element");
         }
@@ -81,8 +76,7 @@ class JsonToCompositeNodeReader {
                 "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet.");
     }
 
-    private static CompositeNodeWrapper createStructureWithRoot(final String rootObjectName,
-                                                                final JsonObject rootObject) {
+    private static CompositeNodeWrapper createStructureWithRoot(final String rootObjectName, final JsonObject rootObject) {
         CompositeNodeWrapper firstNode = new CompositeNodeWrapper(getNamespaceFor(rootObjectName),
                 getLocalNameFor(rootObjectName));
         for (Entry<String, JsonElement> childOfFirstNode : rootObject.entrySet()) {
@@ -92,7 +86,7 @@ class JsonToCompositeNodeReader {
     }
 
     private static void addChildToParent(final String childName, final JsonElement childType,
-                                         final CompositeNodeWrapper parent) {
+            final CompositeNodeWrapper parent) {
         if (childType.isJsonObject()) {
             CompositeNodeWrapper child = new CompositeNodeWrapper(getNamespaceFor(childName),
                     getLocalNameFor(childName));
index cd263d3c55b0a56ce40feca32690749bd489ed6e..7890931a27fea2585de986ce524718f9df5db6a2 100644 (file)
@@ -11,9 +11,7 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
 import javax.xml.stream.events.StartElement;
-
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue;
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.Predicate;
@@ -106,8 +104,7 @@ public final class RestUtil {
                     }
                     result.add(new Predicate(null, predicateValue));
                 } else {
-                    IdentityValue identityValue = toIdentity(predicate.substring(0, indexOfEqualityMark),
-                            prefixMap);
+                    IdentityValue identityValue = toIdentity(predicate.substring(0, indexOfEqualityMark), prefixMap);
                     if (identityValue == null || predicateValue == null) {
                         return null;
                     }
index a5fd7bdaab2646f35e7463f9698f15ca217de11f..b4b2a1f9ef7249734e128456a33876abc3862ae8 100644 (file)
@@ -7,22 +7,19 @@
  */
 package org.opendaylight.controller.sal.rest.impl;
 
+import com.google.common.collect.ImmutableSet;
 import java.util.HashSet;
 import java.util.Set;
-
 import javax.ws.rs.core.Application;
-
 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 com.google.common.collect.ImmutableSet;
-
 public class RestconfApplication extends Application {
 
     @Override
     public Set<Class<?>> getClasses() {
-        return ImmutableSet.<Class<?>>of( RestconfDocumentedExceptionMapper.class );
+        return ImmutableSet.<Class<?>> of(RestconfDocumentedExceptionMapper.class);
     }
 
     @Override
@@ -43,5 +40,4 @@ public class RestconfApplication extends Application {
         return singletons;
     }
 
-
 }
index 0854ca71673465e76e7659bfa9479afc3fb1962f..63a5b1b54055a81cd3f8f3f736365c4e99e1d8b8 100644 (file)
@@ -21,7 +21,6 @@ import com.google.common.base.Charsets;
 import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableList;
 import com.google.gson.stream.JsonWriter;
-
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.OutputStreamWriter;
@@ -29,7 +28,6 @@ import java.io.StringReader;
 import java.io.UnsupportedEncodingException;
 import java.util.List;
 import java.util.Map.Entry;
-
 import javax.activation.UnsupportedDataTypeException;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.HttpHeaders;
@@ -46,7 +44,6 @@ import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.TransformerFactoryConfigurationError;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
-
 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
 import org.opendaylight.controller.sal.restconf.impl.RestconfError;
@@ -63,24 +60,23 @@ import org.w3c.dom.Document;
 import org.xml.sax.InputSource;
 
 /**
- * This class defines an ExceptionMapper that handles RestconfDocumentedExceptions thrown by
- * resource implementations and translates appropriately to restconf error response as defined in
- * the RESTCONF RFC draft.
+ * This class defines an ExceptionMapper that handles RestconfDocumentedExceptions thrown by resource implementations
+ * and translates appropriately to restconf error response as defined in the RESTCONF RFC draft.
  *
  * @author Thomas Pantelis
  */
 @Provider
 public class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
 
-    private final static Logger LOG = LoggerFactory.getLogger( RestconfDocumentedExceptionMapper.class );
+    private final static Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
 
     @Context
     private HttpHeaders headers;
 
     @Override
-    public Response toResponse( final RestconfDocumentedException exception ) {
+    public Response toResponse(final RestconfDocumentedException exception) {
 
-        LOG.debug( "In toResponse: {}", exception.getMessage() );
+        LOG.debug("In toResponse: {}", exception.getMessage());
 
         // Default to the content type if there's no Accept header
 
@@ -88,169 +84,158 @@ public class RestconfDocumentedExceptionMapper implements ExceptionMapper<Restco
 
         List<MediaType> accepts = headers.getAcceptableMediaTypes();
 
-        LOG.debug( "Accept headers: {}", accepts );
+        LOG.debug("Accept headers: {}", accepts);
 
-        if( accepts != null && accepts.size() > 0 ) {
-            mediaType = accepts.get( 0 ); // just pick the first one
+        if (accepts != null && accepts.size() > 0) {
+            mediaType = accepts.get(0); // just pick the first one
         }
 
-        LOG.debug( "Using MediaType: {}",  mediaType );
+        LOG.debug("Using MediaType: {}", mediaType);
 
         List<RestconfError> errors = exception.getErrors();
-        if( errors.isEmpty() ) {
+        if (errors.isEmpty()) {
             // We don't actually want to send any content but, if we don't set any content here,
             // the tomcat front-end will send back an html error report. To prevent that, set a
             // single space char in the entity.
 
-            return Response.status( exception.getStatus() )
-                    .type( MediaType.TEXT_PLAIN_TYPE )
-                    .entity( " " ).build();
+            return Response.status(exception.getStatus()).type(MediaType.TEXT_PLAIN_TYPE).entity(" ").build();
         }
 
         int status = errors.iterator().next().getErrorTag().getStatusCode();
 
         ControllerContext context = ControllerContext.getInstance();
-        DataNodeContainer errorsSchemaNode = (DataNodeContainer)context.getRestconfModuleErrorsSchemaNode();
+        DataNodeContainer errorsSchemaNode = (DataNodeContainer) context.getRestconfModuleErrorsSchemaNode();
 
-        if( errorsSchemaNode == null ) {
-            return Response.status( status )
-                    .type( MediaType.TEXT_PLAIN_TYPE )
-                    .entity( exception.getMessage() ).build();
+        if (errorsSchemaNode == null) {
+            return Response.status(status).type(MediaType.TEXT_PLAIN_TYPE).entity(exception.getMessage()).build();
         }
 
         ImmutableList.Builder<Node<?>> errorNodes = ImmutableList.<Node<?>> builder();
-        for( RestconfError error: errors ) {
-            errorNodes.add( toDomNode( error ) );
+        for (RestconfError error : errors) {
+            errorNodes.add(toDomNode(error));
         }
 
-        ImmutableCompositeNode errorsNode =
-                ImmutableCompositeNode.create( ERRORS_CONTAINER_QNAME, errorNodes.build() );
+        ImmutableCompositeNode errorsNode = ImmutableCompositeNode.create(ERRORS_CONTAINER_QNAME, errorNodes.build());
 
         Object responseBody;
-        if( mediaType.getSubtype().endsWith( "json" ) ) {
-            responseBody = toJsonResponseBody( errorsNode, errorsSchemaNode );
-        }
-        else {
-            responseBody = toXMLResponseBody( errorsNode, errorsSchemaNode );
+        if (mediaType.getSubtype().endsWith("json")) {
+            responseBody = toJsonResponseBody(errorsNode, errorsSchemaNode);
+        } else {
+            responseBody = toXMLResponseBody(errorsNode, errorsSchemaNode);
         }
 
-        return Response.status( status ).type( mediaType ).entity( responseBody ).build();
+        return Response.status(status).type(mediaType).entity(responseBody).build();
     }
 
-    private Object toJsonResponseBody( final ImmutableCompositeNode errorsNode,
-            final DataNodeContainer errorsSchemaNode ) {
+    private Object toJsonResponseBody(final ImmutableCompositeNode errorsNode, final DataNodeContainer errorsSchemaNode) {
 
         JsonMapper jsonMapper = new JsonMapper(null);
 
         Object responseBody = null;
         try {
             ByteArrayOutputStream outStream = new ByteArrayOutputStream();
-            JsonWriter writer = new JsonWriter(new OutputStreamWriter( outStream, Charsets.UTF_8));
-            writer.setIndent( "    " );
+            JsonWriter writer = new JsonWriter(new OutputStreamWriter(outStream, Charsets.UTF_8));
+            writer.setIndent("    ");
 
-            jsonMapper.write( writer, errorsNode, errorsSchemaNode);
+            jsonMapper.write(writer, errorsNode, errorsSchemaNode);
             writer.flush();
 
-            responseBody = outStream.toString( "UTF-8" );
-        } catch( IOException e ) {
-            LOG.error( "Error writing error response body", e );
+            responseBody = outStream.toString("UTF-8");
+        } catch (IOException e) {
+            LOG.error("Error writing error response body", e);
         }
 
         return responseBody;
     }
 
-    private Object toXMLResponseBody( final ImmutableCompositeNode errorsNode,
-            final DataNodeContainer errorsSchemaNode ) {
+    private Object toXMLResponseBody(final ImmutableCompositeNode errorsNode, final DataNodeContainer errorsSchemaNode) {
 
         XmlMapper xmlMapper = new XmlMapper();
 
         Object responseBody = null;
         try {
-            Document xmlDoc = xmlMapper.write( errorsNode, errorsSchemaNode );
+            Document xmlDoc = xmlMapper.write(errorsNode, errorsSchemaNode);
 
-            responseBody = documentToString( xmlDoc );
-        }
-        catch( TransformerException | UnsupportedDataTypeException | UnsupportedEncodingException e ) {
-            LOG.error( "Error writing error response body", e );
+            responseBody = documentToString(xmlDoc);
+        } catch (TransformerException | UnsupportedDataTypeException | UnsupportedEncodingException e) {
+            LOG.error("Error writing error response body", e);
         }
 
         return responseBody;
     }
 
-    private String documentToString( final Document doc ) throws TransformerException, UnsupportedEncodingException {
+    private String documentToString(final Document doc) throws TransformerException, UnsupportedEncodingException {
         Transformer transformer = createTransformer();
         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
 
-        transformer.transform( new DOMSource( doc ), new StreamResult( outStream ) );
+        transformer.transform(new DOMSource(doc), new StreamResult(outStream));
 
-        return outStream.toString( "UTF-8" );
+        return outStream.toString("UTF-8");
     }
 
     private Transformer createTransformer() throws TransformerFactoryConfigurationError,
-    TransformerConfigurationException {
+            TransformerConfigurationException {
         TransformerFactory tf = TransformerFactory.newInstance();
         Transformer transformer = tf.newTransformer();
-        transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "no" );
-        transformer.setOutputProperty( OutputKeys.METHOD, "xml" );
-        transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
-        transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );
-        transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "4" );
+        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
+        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
+        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
         return transformer;
     }
 
-    private Node<?> toDomNode( final RestconfError error ) {
+    private Node<?> toDomNode(final RestconfError error) {
 
         CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
-        builder.setQName( ERROR_LIST_QNAME );
+        builder.setQName(ERROR_LIST_QNAME);
 
-        addLeaf( builder, ERROR_TYPE_QNAME, error.getErrorType().getErrorTypeTag() );
-        addLeaf( builder, ERROR_TAG_QNAME, error.getErrorTag().getTagValue() );
-        addLeaf( builder, ERROR_MESSAGE_QNAME, error.getErrorMessage() );
-        addLeaf( builder, ERROR_APP_TAG_QNAME, error.getErrorAppTag() );
+        addLeaf(builder, ERROR_TYPE_QNAME, error.getErrorType().getErrorTypeTag());
+        addLeaf(builder, ERROR_TAG_QNAME, error.getErrorTag().getTagValue());
+        addLeaf(builder, ERROR_MESSAGE_QNAME, error.getErrorMessage());
+        addLeaf(builder, ERROR_APP_TAG_QNAME, error.getErrorAppTag());
 
-        Node<?> errorInfoNode = parseErrorInfo( error.getErrorInfo() );
-        if( errorInfoNode != null ) {
-            builder.add( errorInfoNode );
+        Node<?> errorInfoNode = parseErrorInfo(error.getErrorInfo());
+        if (errorInfoNode != null) {
+            builder.add(errorInfoNode);
         }
 
         return builder.toInstance();
     }
 
-    private Node<?> parseErrorInfo( final String errorInfo ) {
-        if( Strings.isNullOrEmpty( errorInfo ) ) {
+    private Node<?> parseErrorInfo(final String errorInfo) {
+        if (Strings.isNullOrEmpty(errorInfo)) {
             return null;
         }
 
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
-        factory.setNamespaceAware( true );
-        factory.setCoalescing( true );
-        factory.setIgnoringElementContentWhitespace( true );
-        factory.setIgnoringComments( true );
+        factory.setNamespaceAware(true);
+        factory.setCoalescing(true);
+        factory.setIgnoringElementContentWhitespace(true);
+        factory.setIgnoringComments(true);
 
         // Wrap the error info content in a root <error-info> element so it can be parsed
         // as XML. The error info content may or may not be XML. If not then it will be
         // parsed as text content of the <error-info> element.
 
-        String errorInfoWithRoot =
-                new StringBuilder( "<error-info xmlns=\"" ).append( NAMESPACE ).append( "\">" )
-                .append( errorInfo ).append( "</error-info>" ).toString();
+        String errorInfoWithRoot = new StringBuilder("<error-info xmlns=\"").append(NAMESPACE).append("\">")
+                .append(errorInfo).append("</error-info>").toString();
 
         Document doc = null;
         try {
-            doc = factory.newDocumentBuilder().parse(
-                    new InputSource( new StringReader( errorInfoWithRoot ) ) );
-        } catch( Exception e ) {
-            // TODO: what if the content is text that happens to contain invalid markup? Could
-            // wrap in CDATA and try again.
+            doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(errorInfoWithRoot)));
+        } catch (Exception e) {
+            // TODO: what if the content is text that happens to contain invalid markup?
+            // Could wrap in CDATA and try again.
 
-            LOG.warn( "Error parsing restconf error-info, \"{}\", as XML", errorInfo, e);
+            LOG.warn("Error parsing restconf error-info, \"{}\", as XML", errorInfo, e);
             return null;
         }
 
-        Node<?> errorInfoNode = XmlDocumentUtils.toDomNode( doc );
+        Node<?> errorInfoNode = XmlDocumentUtils.toDomNode(doc);
 
-        if( errorInfoNode instanceof CompositeNode ) {
-            CompositeNode compositeNode = (CompositeNode)XmlDocumentUtils.toDomNode( doc );
+        if (errorInfoNode instanceof CompositeNode) {
+            CompositeNode compositeNode = (CompositeNode) XmlDocumentUtils.toDomNode(doc);
 
             // At this point the QName for the "error-info" CompositeNode doesn't contain the revision
             // as it isn't present in the XML. So we'll copy all the child nodes and create a new
@@ -258,20 +243,20 @@ public class RestconfDocumentedExceptionMapper implements ExceptionMapper<Restco
             // locate the schema.
 
             ImmutableList.Builder<Node<?>> childNodes = ImmutableList.builder();
-            for( Entry<QName, List<Node<?>>> entry: compositeNode.entrySet() ) {
-                childNodes.addAll( entry.getValue() );
+            for (Entry<QName, List<Node<?>>> entry : compositeNode.entrySet()) {
+                childNodes.addAll(entry.getValue());
             }
 
-            errorInfoNode = ImmutableCompositeNode.create( ERROR_INFO_QNAME, childNodes.build() );
+            errorInfoNode = ImmutableCompositeNode.create(ERROR_INFO_QNAME, childNodes.build());
         }
 
         return errorInfoNode;
     }
 
-    private void addLeaf( final CompositeNodeBuilder<ImmutableCompositeNode> builder, final QName qname,
-            final String value ) {
-        if( !Strings.isNullOrEmpty( value ) ) {
-            builder.addLeaf( qname, value );
+    private void addLeaf(final CompositeNodeBuilder<ImmutableCompositeNode> builder, final QName qname,
+            final String value) {
+        if (!Strings.isNullOrEmpty(value)) {
+            builder.addLeaf(qname, value);
         }
     }
 }
index 1c95f1327b7ee5fa9cd4219ec6dad4a11a6b843a..1f1d0eb83147533d1171a4e81a36a73d7f72acd0 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.controller.sal.rest.impl;
 
 import java.util.Collection;
 import java.util.Collections;
-
 import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
 import org.opendaylight.controller.sal.core.api.Provider;
@@ -52,8 +51,8 @@ public class RestconfProvider implements BundleActivator, Provider, ServiceTrack
     @Override
     public void start(BundleContext context) throws Exception {
         String websocketPortStr = context.getProperty(WebSocketServer.WEBSOCKET_SERVER_CONFIG_PROPERTY);
-        int websocketPort = (websocketPortStr != null && !"".equals(websocketPortStr))
-                ? Integer.parseInt(websocketPortStr) :  WebSocketServer.DEFAULT_PORT;
+        int websocketPort = (websocketPortStr != null && !"".equals(websocketPortStr)) ? Integer
+                .parseInt(websocketPortStr) : WebSocketServer.DEFAULT_PORT;
         bundleContext = context;
         webSocketServerThread = new Thread(WebSocketServer.createInstance(websocketPort));
         webSocketServerThread.setName("Web socket server");
index 063d2f51afffdd0c7094d7363d95795182b5cd8e..933ed0f849e7171b7c16c423c5462aa8de1bb25a 100644 (file)
@@ -30,24 +30,27 @@ import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 
 @Provider
 @Produces({ Draft02.MediaTypes.API + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
-    Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON })
+        Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON })
 public enum StructuredDataToJsonProvider implements MessageBodyWriter<StructuredData> {
     INSTANCE;
 
     @Override
-    public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
+    public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+            final MediaType mediaType) {
         return type.equals(StructuredData.class);
     }
 
     @Override
-    public long getSize(final StructuredData t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
+    public long getSize(final StructuredData t, final Class<?> type, final Type genericType,
+            final Annotation[] annotations, final MediaType mediaType) {
         return -1;
     }
 
     @Override
-    public void writeTo(final StructuredData t, final Class<?> type, final Type genericType, final Annotation[] annotations,
-            final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream)
-                    throws IOException, WebApplicationException {
+    public void writeTo(final StructuredData t, final Class<?> type, final Type genericType,
+            final Annotation[] annotations, final MediaType mediaType,
+            final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
+            WebApplicationException {
         CompositeNode data = t.getData();
         if (data == null) {
             throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
index 3a235ced858a4be9af6dc24d9152602ff806bc09..703a2a463476bcfd4704c34419cc17c73a6af3fc 100644 (file)
@@ -39,7 +39,7 @@ import org.w3c.dom.Document;
 
 @Provider
 @Produces({ Draft02.MediaTypes.API + RestconfService.XML, Draft02.MediaTypes.DATA + RestconfService.XML,
-    Draft02.MediaTypes.OPERATION + RestconfService.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+        Draft02.MediaTypes.OPERATION + RestconfService.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
 public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredData> {
     INSTANCE;
 
@@ -67,19 +67,22 @@ public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredD
     };
 
     @Override
-    public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
+    public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+            final MediaType mediaType) {
         return type.equals(StructuredData.class);
     }
 
     @Override
-    public long getSize(final StructuredData t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
+    public long getSize(final StructuredData t, final Class<?> type, final Type genericType,
+            final Annotation[] annotations, final MediaType mediaType) {
         return -1;
     }
 
     @Override
-    public void writeTo(final StructuredData t, final Class<?> type, final Type genericType, final Annotation[] annotations,
-            final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream)
-                    throws IOException, WebApplicationException {
+    public void writeTo(final StructuredData t, final Class<?> type, final Type genericType,
+            final Annotation[] annotations, final MediaType mediaType,
+            final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
+            WebApplicationException {
         CompositeNode data = t.getData();
         if (data == null) {
             throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
@@ -94,8 +97,7 @@ public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredD
                 trans.setOutputProperty(OutputKeys.INDENT, "no");
             }
         } catch (RuntimeException e) {
-            throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT,
-                    ErrorTag.OPERATION_FAILED);
+            throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED);
         }
 
         // FIXME: BUG-1281: eliminate the intermediate Document
@@ -104,8 +106,7 @@ public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredD
             trans.transform(new DOMSource(domTree), new StreamResult(entityStream));
         } catch (TransformerException e) {
             LOG.error("Error during translation of Document to OutputStream", e);
-            throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT,
-                    ErrorTag.OPERATION_FAILED);
+            throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED);
         }
     }
 
index e76e1962a058bea7c0bdb8a22b6a2c7285e785cd..b0b2cc5e2f0898dd0bc0d7572ec480884b3f9308 100644 (file)
@@ -7,8 +7,8 @@
  */
 package org.opendaylight.controller.sal.rest.impl;
 
+import com.google.common.base.Optional;
 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;
@@ -20,8 +20,6 @@ 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());
index 7d0690cdc27e0a6754a354f187b88317e558720f..413823f52081ebb235cc33db3530e2bdbbf7c149 100644 (file)
@@ -36,8 +36,7 @@ public class XmlToCompositeNodeReader {
     public CompositeNodeWrapper read(InputStream entityStream) throws XMLStreamException, UnsupportedFormatException,
             IOException {
         // Get an XML stream which can be marked, and reset, so we can check and
-        // see if there is
-        // any content being provided.
+        // see if there is any content being provided.
         entityStream = getMarkableStream(entityStream);
 
         if (isInputStreamEmpty(entityStream)) {
@@ -103,9 +102,8 @@ public class XmlToCompositeNodeReader {
     }
 
     /**
-     * If the input stream is not markable, then it wraps the input stream with
-     * a buffered stream, which is mark able. That way we can check if the
-     * stream is empty safely.
+     * If the input stream is not markable, then it wraps the input stream with a buffered stream, which is mark able.
+     * That way we can check if the stream is empty safely.
      *
      * @param entityStream
      * @return
index 62afdbd10df31df5f5a577f3520dec8ab8b59dcd..9560333e711b3e56224f5ca7dab6118bedcb6d7a 100644 (file)
@@ -5,4 +5,4 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-package org.opendaylight.controller.sal.rest.impl;
+package org.opendaylight.controller.sal.rest.impl;
\ No newline at end of file
index 3d047dd07f53e47a4000a5de137fcc52e3affa75..a2c228788f3a27659ae5a2db56f31dfb136d8886 100644 (file)
@@ -32,7 +32,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class BrokerFacade implements DataReader<InstanceIdentifier, CompositeNode> {
-    private final static Logger LOG = LoggerFactory.getLogger( BrokerFacade.class );
+    private final static Logger LOG = LoggerFactory.getLogger(BrokerFacade.class);
 
     private final static BrokerFacade INSTANCE = new BrokerFacade();
 
@@ -42,11 +42,11 @@ public class BrokerFacade implements DataReader<InstanceIdentifier, CompositeNod
     private BrokerFacade() {
     }
 
-    public void setContext( final ConsumerSession context ) {
+    public void setContext(final ConsumerSession context) {
         this.context = context;
     }
 
-    public void setDataService( final DataBrokerService dataService ) {
+    public void setDataService(final DataBrokerService dataService) {
         this.dataService = dataService;
     }
 
@@ -55,120 +55,120 @@ public class BrokerFacade implements DataReader<InstanceIdentifier, CompositeNod
     }
 
     private void checkPreconditions() {
-        if( context == null || dataService == null ) {
-            throw new RestconfDocumentedException( Status.SERVICE_UNAVAILABLE );
+        if (context == null || dataService == null) {
+            throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
         }
     }
 
     @Override
-    public CompositeNode readConfigurationData( final InstanceIdentifier path ) {
+    public CompositeNode readConfigurationData(final InstanceIdentifier path) {
         this.checkPreconditions();
 
-        LOG.trace( "Read Configuration via Restconf: {}", path );
+        LOG.trace("Read Configuration via Restconf: {}", path);
 
-        return dataService.readConfigurationData( path );
+        return dataService.readConfigurationData(path);
     }
 
-    public CompositeNode readConfigurationDataBehindMountPoint( final MountInstance mountPoint,
-                                                                final InstanceIdentifier path ) {
+    public CompositeNode readConfigurationDataBehindMountPoint(final MountInstance mountPoint,
+            final InstanceIdentifier path) {
         this.checkPreconditions();
 
-        LOG.trace( "Read Configuration via Restconf: {}", path );
+        LOG.trace("Read Configuration via Restconf: {}", path);
 
-        return mountPoint.readConfigurationData( path );
+        return mountPoint.readConfigurationData(path);
     }
 
     @Override
-    public CompositeNode readOperationalData( final InstanceIdentifier path ) {
+    public CompositeNode readOperationalData(final InstanceIdentifier path) {
         this.checkPreconditions();
 
-        BrokerFacade.LOG.trace( "Read Operational via Restconf: {}", path );
+        BrokerFacade.LOG.trace("Read Operational via Restconf: {}", path);
 
-        return dataService.readOperationalData( path );
+        return dataService.readOperationalData(path);
     }
 
-    public CompositeNode readOperationalDataBehindMountPoint( final MountInstance mountPoint,
-                                                              final InstanceIdentifier path ) {
+    public CompositeNode readOperationalDataBehindMountPoint(final MountInstance mountPoint,
+            final InstanceIdentifier path) {
         this.checkPreconditions();
 
-        BrokerFacade.LOG.trace( "Read Operational via Restconf: {}", path );
+        BrokerFacade.LOG.trace("Read Operational via Restconf: {}", path);
 
-        return mountPoint.readOperationalData( path );
+        return mountPoint.readOperationalData(path);
     }
 
-    public Future<RpcResult<CompositeNode>> invokeRpc( final QName type, final CompositeNode payload ) {
+    public Future<RpcResult<CompositeNode>> invokeRpc(final QName type, final CompositeNode payload) {
         this.checkPreconditions();
 
-        return context.rpc( type, payload );
+        return context.rpc(type, payload);
     }
 
-    public Future<RpcResult<TransactionStatus>> commitConfigurationDataPut( final InstanceIdentifier path,
-                                                                            final CompositeNode payload ) {
+    public Future<RpcResult<TransactionStatus>> commitConfigurationDataPut(final InstanceIdentifier path,
+            final CompositeNode payload) {
         this.checkPreconditions();
 
         final DataModificationTransaction transaction = dataService.beginTransaction();
-        BrokerFacade.LOG.trace( "Put Configuration via Restconf: {}", path );
-        transaction.putConfigurationData( path, payload );
+        BrokerFacade.LOG.trace("Put Configuration via Restconf: {}", path);
+        transaction.putConfigurationData(path, payload);
         return transaction.commit();
     }
 
     public Future<RpcResult<TransactionStatus>> commitConfigurationDataPutBehindMountPoint(
-            final MountInstance mountPoint, final InstanceIdentifier path, final CompositeNode payload ) {
+            final MountInstance mountPoint, final InstanceIdentifier path, final CompositeNode payload) {
         this.checkPreconditions();
 
         final DataModificationTransaction transaction = mountPoint.beginTransaction();
-        BrokerFacade.LOG.trace( "Put Configuration via Restconf: {}", path );
-        transaction.putConfigurationData( path, payload );
+        BrokerFacade.LOG.trace("Put Configuration via Restconf: {}", path);
+        transaction.putConfigurationData(path, payload);
         return transaction.commit();
     }
 
-    public Future<RpcResult<TransactionStatus>> commitConfigurationDataPost( final InstanceIdentifier path,
-                                                                             final CompositeNode payload) {
+    public Future<RpcResult<TransactionStatus>> commitConfigurationDataPost(final InstanceIdentifier path,
+            final CompositeNode payload) {
         this.checkPreconditions();
 
         final DataModificationTransaction transaction = dataService.beginTransaction();
         /* check for available Node in Configuration DataStore by path */
-        CompositeNode availableNode = transaction.readConfigurationData( path );
+        CompositeNode availableNode = transaction.readConfigurationData(path);
         if (availableNode != null) {
             String errMsg = "Post Configuration via Restconf was not executed because data already exists";
             BrokerFacade.LOG.warn((new StringBuilder(errMsg)).append(" : ").append(path).toString());
 
-            throw new RestconfDocumentedException(
-                    "Data already exists for path: " + path, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS );
+            throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL,
+                    ErrorTag.DATA_EXISTS);
         }
-        BrokerFacade.LOG.trace( "Post Configuration via Restconf: {}", path );
-        transaction.putConfigurationData( path, payload );
+        BrokerFacade.LOG.trace("Post Configuration via Restconf: {}", path);
+        transaction.putConfigurationData(path, payload);
         return transaction.commit();
     }
 
     public Future<RpcResult<TransactionStatus>> commitConfigurationDataPostBehindMountPoint(
-            final MountInstance mountPoint, final InstanceIdentifier path, final CompositeNode payload ) {
+            final MountInstance mountPoint, final InstanceIdentifier path, final CompositeNode payload) {
         this.checkPreconditions();
 
         final DataModificationTransaction transaction = mountPoint.beginTransaction();
         /* check for available Node in Configuration DataStore by path */
-        CompositeNode availableNode = transaction.readConfigurationData( path );
+        CompositeNode availableNode = transaction.readConfigurationData(path);
         if (availableNode != null) {
             String errMsg = "Post Configuration via Restconf was not executed because data already exists";
             BrokerFacade.LOG.warn((new StringBuilder(errMsg)).append(" : ").append(path).toString());
 
-            throw new RestconfDocumentedException(
-                    "Data already exists for path: " + path, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS );
+            throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL,
+                    ErrorTag.DATA_EXISTS);
         }
-        BrokerFacade.LOG.trace( "Post Configuration via Restconf: {}", path );
-        transaction.putConfigurationData( path, payload );
+        BrokerFacade.LOG.trace("Post Configuration via Restconf: {}", path);
+        transaction.putConfigurationData(path, payload);
         return transaction.commit();
     }
 
-    public Future<RpcResult<TransactionStatus>> commitConfigurationDataDelete( final InstanceIdentifier path ) {
+    public Future<RpcResult<TransactionStatus>> commitConfigurationDataDelete(final InstanceIdentifier path) {
         this.checkPreconditions();
-        return deleteDataAtTarget(path,dataService.beginTransaction());
+        return deleteDataAtTarget(path, dataService.beginTransaction());
     }
 
     public Future<RpcResult<TransactionStatus>> commitConfigurationDataDeleteBehindMountPoint(
-                                          final MountInstance mountPoint, final InstanceIdentifier path ) {
+            final MountInstance mountPoint, final InstanceIdentifier path) {
         this.checkPreconditions();
-        return deleteDataAtTarget(path,mountPoint.beginTransaction());
+        return deleteDataAtTarget(path, mountPoint.beginTransaction());
     }
 
     private Future<RpcResult<TransactionStatus>> deleteDataAtTarget(final InstanceIdentifier path,
@@ -183,17 +183,17 @@ public class BrokerFacade implements DataReader<InstanceIdentifier, CompositeNod
         return transaction.commit();
     }
 
-    public void registerToListenDataChanges( final ListenerAdapter listener ) {
+    public void registerToListenDataChanges(final ListenerAdapter listener) {
         this.checkPreconditions();
 
-        if( listener.isListening() ) {
+        if (listener.isListening()) {
             return;
         }
 
         InstanceIdentifier path = listener.getPath();
-        final ListenerRegistration<DataChangeListener> registration =
-                                             dataService.registerDataChangeListener( path, listener );
+        final ListenerRegistration<DataChangeListener> registration = dataService.registerDataChangeListener(path,
+                listener);
 
-        listener.setRegistration( registration );
+        listener.setRegistration(registration);
     }
 }
index 69b975dab7e5ef15bb7e5ad4cf389ed55f0ef9c8..206dbdeab60a20dff4d13f9fbd3c96c68ac45b4d 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.controller.sal.restconf.impl;
 
 import com.google.common.base.Preconditions;
-
 import java.net.URI;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -16,7 +15,6 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
index 85c8e595396e9463b8fb7bf93437510041306b09..29672f39d47c4222b297972be5b1dbeef3f1d6fe 100644 (file)
@@ -18,7 +18,6 @@ import com.google.common.collect.BiMap;
 import com.google.common.collect.FluentIterable;
 import com.google.common.collect.HashBiMap;
 import com.google.common.collect.Iterables;
-
 import java.io.UnsupportedEncodingException;
 import java.net.URI;
 import java.net.URLDecoder;
@@ -32,9 +31,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
-
 import javax.ws.rs.core.Response.Status;
-
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.controller.sal.core.api.mount.MountService;
 import org.opendaylight.controller.sal.rest.api.Draft02;
@@ -68,7 +65,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class ControllerContext implements SchemaContextListener {
-    private final static Logger LOG = LoggerFactory.getLogger( ControllerContext.class );
+    private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
 
     private final static ControllerContext INSTANCE = new ControllerContext();
 
@@ -95,11 +92,11 @@ public class ControllerContext implements SchemaContextListener {
     private volatile SchemaContext globalSchema;
     private volatile MountService mountService;
 
-    public void setGlobalSchema( final SchemaContext globalSchema ) {
+    public void setGlobalSchema(final SchemaContext globalSchema) {
         this.globalSchema = globalSchema;
     }
 
-    public void setMountService( final MountService mountService ) {
+    public void setMountService(final MountService mountService) {
         this.mountService = mountService;
     }
 
@@ -111,162 +108,157 @@ public class ControllerContext implements SchemaContextListener {
     }
 
     private void checkPreconditions() {
-        if( globalSchema == null ) {
-            throw new RestconfDocumentedException( Status.SERVICE_UNAVAILABLE );
+        if (globalSchema == null) {
+            throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
         }
     }
 
-    public void setSchemas( final SchemaContext schemas ) {
-        this.onGlobalContextUpdated( schemas );
+    public void setSchemas(final SchemaContext schemas) {
+        this.onGlobalContextUpdated(schemas);
     }
 
-    public InstanceIdWithSchemaNode toInstanceIdentifier( final String restconfInstance ) {
-        return this.toIdentifier( restconfInstance, false );
+    public InstanceIdWithSchemaNode toInstanceIdentifier(final String restconfInstance) {
+        return this.toIdentifier(restconfInstance, false);
     }
 
-    public InstanceIdWithSchemaNode toMountPointIdentifier( final String restconfInstance ) {
-        return this.toIdentifier( restconfInstance, true );
+    public InstanceIdWithSchemaNode toMountPointIdentifier(final String restconfInstance) {
+        return this.toIdentifier(restconfInstance, true);
     }
 
-    private InstanceIdWithSchemaNode toIdentifier( final String restconfInstance,
-            final boolean toMountPointIdentifier ) {
+    private InstanceIdWithSchemaNode toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
         this.checkPreconditions();
 
-        final List<String> pathArgs = urlPathArgsDecode( SLASH_SPLITTER.split( restconfInstance ) );
-        omitFirstAndLastEmptyString( pathArgs );
-        if( pathArgs.isEmpty() ) {
+        final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
+        omitFirstAndLastEmptyString(pathArgs);
+        if (pathArgs.isEmpty()) {
             return null;
         }
 
         String first = pathArgs.iterator().next();
-        final String startModule = ControllerContext.toModuleName( first );
-        if( startModule == null ) {
-            throw new RestconfDocumentedException(
-                    "First node in URI has to be in format \"moduleName:nodeName\"",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        final String startModule = ControllerContext.toModuleName(first);
+        if (startModule == null) {
+            throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         InstanceIdentifierBuilder builder = InstanceIdentifier.builder();
-        Module latestModule = this.getLatestModule( globalSchema, startModule );
-        InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments( builder, pathArgs,
-                latestModule, null, toMountPointIdentifier );
+        Module latestModule = this.getLatestModule(globalSchema, startModule);
+        InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments(builder, pathArgs, latestModule, null,
+                toMountPointIdentifier);
 
-        if( iiWithSchemaNode == null ) {
-            throw new RestconfDocumentedException(
-                    "URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        if (iiWithSchemaNode == null) {
+            throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         return iiWithSchemaNode;
     }
 
-    private static List<String> omitFirstAndLastEmptyString( final List<String> list ) {
-        if( list.isEmpty() ) {
+    private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
+        if (list.isEmpty()) {
             return list;
         }
 
         String head = list.iterator().next();
-        if( head.isEmpty() ) {
-            list.remove( 0 );
+        if (head.isEmpty()) {
+            list.remove(0);
         }
 
-        if( list.isEmpty() ) {
+        if (list.isEmpty()) {
             return list;
         }
 
-        String last = list.get( list.size() - 1 );
-        if( last.isEmpty() ) {
-            list.remove( list.size() - 1 );
+        String last = list.get(list.size() - 1);
+        if (last.isEmpty()) {
+            list.remove(list.size() - 1);
         }
 
         return list;
     }
 
-    private Module getLatestModule( final SchemaContext schema, final String moduleName ) {
-        Preconditions.checkArgument( schema != null );
-        Preconditions.checkArgument( moduleName != null && !moduleName.isEmpty() );
+    private Module getLatestModule(final SchemaContext schema, final String moduleName) {
+        Preconditions.checkArgument(schema != null);
+        Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
 
         Predicate<Module> filter = new Predicate<Module>() {
             @Override
-            public boolean apply( final Module m ) {
-                return Objects.equal( m.getName(), moduleName );
+            public boolean apply(final Module m) {
+                return Objects.equal(m.getName(), moduleName);
             }
         };
 
-        Iterable<Module> modules = Iterables.filter( schema.getModules(), filter );
-        return this.filterLatestModule( modules );
+        Iterable<Module> modules = Iterables.filter(schema.getModules(), filter);
+        return this.filterLatestModule(modules);
     }
 
-    private Module filterLatestModule( final Iterable<Module> modules ) {
+    private Module filterLatestModule(final Iterable<Module> modules) {
         Module latestModule = modules.iterator().hasNext() ? modules.iterator().next() : null;
-        for( final Module module : modules ) {
-            if( module.getRevision().after( latestModule.getRevision() ) ) {
+        for (final Module module : modules) {
+            if (module.getRevision().after(latestModule.getRevision())) {
                 latestModule = module;
             }
         }
         return latestModule;
     }
 
-    public Module findModuleByName( final String moduleName ) {
+    public Module findModuleByName(final String moduleName) {
         this.checkPreconditions();
-        Preconditions.checkArgument( moduleName != null && !moduleName.isEmpty() );
-        return this.getLatestModule( globalSchema, moduleName );
+        Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
+        return this.getLatestModule(globalSchema, moduleName);
     }
 
-    public Module findModuleByName( final MountInstance mountPoint, final String moduleName ) {
-        Preconditions.checkArgument( moduleName != null && mountPoint != null );
+    public Module findModuleByName(final MountInstance mountPoint, final String moduleName) {
+        Preconditions.checkArgument(moduleName != null && mountPoint != null);
 
         final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
-        return mountPointSchema == null ? null : this.getLatestModule( mountPointSchema, moduleName );
+        return mountPointSchema == null ? null : this.getLatestModule(mountPointSchema, moduleName);
     }
 
-    public Module findModuleByNamespace( final URI namespace ) {
+    public Module findModuleByNamespace(final URI namespace) {
         this.checkPreconditions();
-        Preconditions.checkArgument( namespace != null );
+        Preconditions.checkArgument(namespace != null);
 
-        final Set<Module> moduleSchemas = globalSchema.findModuleByNamespace( namespace );
-        return moduleSchemas == null ? null : this.filterLatestModule( moduleSchemas );
+        final Set<Module> moduleSchemas = globalSchema.findModuleByNamespace(namespace);
+        return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
     }
 
-    public Module findModuleByNamespace( final MountInstance mountPoint, final URI namespace ) {
-        Preconditions.checkArgument( namespace != null && mountPoint != null );
+    public Module findModuleByNamespace(final MountInstance mountPoint, final URI namespace) {
+        Preconditions.checkArgument(namespace != null && mountPoint != null);
 
         final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
-        Set<Module> moduleSchemas = mountPointSchema == null ? null :
-            mountPointSchema.findModuleByNamespace( namespace );
-        return moduleSchemas == null ? null : this.filterLatestModule( moduleSchemas );
+        Set<Module> moduleSchemas = mountPointSchema == null ? null : mountPointSchema.findModuleByNamespace(namespace);
+        return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
     }
 
-    public Module findModuleByNameAndRevision( final QName module ) {
+    public Module findModuleByNameAndRevision(final QName module) {
         this.checkPreconditions();
-        Preconditions.checkArgument( module != null && module.getLocalName() != null &&
-                module.getRevision() != null );
+        Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
 
-        return globalSchema.findModuleByName( module.getLocalName(), module.getRevision() );
+        return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
     }
 
-    public Module findModuleByNameAndRevision( final MountInstance mountPoint, final QName module ) {
+    public Module findModuleByNameAndRevision(final MountInstance mountPoint, final QName module) {
         this.checkPreconditions();
-        Preconditions.checkArgument( module != null && module.getLocalName() != null &&
-                module.getRevision() != null && mountPoint != null );
+        Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
+                && mountPoint != null);
 
         SchemaContext schemaContext = mountPoint.getSchemaContext();
-        return schemaContext == null ? null :
-            schemaContext.findModuleByName( module.getLocalName(), module.getRevision() );
+        return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
+                module.getRevision());
     }
 
-    public DataNodeContainer getDataNodeContainerFor( final InstanceIdentifier path ) {
+    public DataNodeContainer getDataNodeContainerFor(final InstanceIdentifier path) {
         this.checkPreconditions();
 
         final Iterable<PathArgument> elements = path.getPathArguments();
         PathArgument head = elements.iterator().next();
         final QName startQName = head.getNodeType();
-        final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(
-                startQName.getNamespace(), startQName.getRevision() );
+        final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
+                startQName.getRevision());
         DataNodeContainer node = initialModule;
-        for( final PathArgument element : elements ) {
+        for (final PathArgument element : elements) {
             QName _nodeType = element.getNodeType();
-            final DataSchemaNode potentialNode = ControllerContext.childByQName( node, _nodeType );
-            if( potentialNode == null || !this.isListOrContainer( potentialNode ) ) {
+            final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
+            if (potentialNode == null || !this.isListOrContainer(potentialNode)) {
                 return null;
             }
             node = (DataNodeContainer) potentialNode;
@@ -275,68 +267,68 @@ public class ControllerContext implements SchemaContextListener {
         return node;
     }
 
-    public String toFullRestconfIdentifier( final InstanceIdentifier path ) {
+    public String toFullRestconfIdentifier(final InstanceIdentifier path) {
         this.checkPreconditions();
 
         final Iterable<PathArgument> elements = path.getPathArguments();
         final StringBuilder builder = new StringBuilder();
         PathArgument head = elements.iterator().next();
         final QName startQName = head.getNodeType();
-        final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(
-                startQName.getNamespace(), startQName.getRevision() );
+        final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
+                startQName.getRevision());
         DataNodeContainer node = initialModule;
-        for( final PathArgument element : elements ) {
+        for (final PathArgument element : elements) {
             QName _nodeType = element.getNodeType();
-            final DataSchemaNode potentialNode = ControllerContext.childByQName( node, _nodeType );
-            if( !this.isListOrContainer( potentialNode ) ) {
+            final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
+            if (!this.isListOrContainer(potentialNode)) {
                 return null;
             }
             node = ((DataNodeContainer) potentialNode);
-            builder.append( this.convertToRestconfIdentifier( element, node ) );
+            builder.append(this.convertToRestconfIdentifier(element, node));
         }
 
         return builder.toString();
     }
 
-    public String findModuleNameByNamespace( final URI namespace ) {
+    public String findModuleNameByNamespace(final URI namespace) {
         this.checkPreconditions();
 
-        String moduleName = this.uriToModuleName.get( namespace );
-        if( moduleName == null ) {
-            final Module module = this.findModuleByNamespace( namespace );
-            if( module != null ) {
+        String moduleName = this.uriToModuleName.get(namespace);
+        if (moduleName == null) {
+            final Module module = this.findModuleByNamespace(namespace);
+            if (module != null) {
                 moduleName = module.getName();
-                this.uriToModuleName.put( namespace, moduleName );
+                this.uriToModuleName.put(namespace, moduleName);
             }
         }
 
         return moduleName;
     }
 
-    public String findModuleNameByNamespace( final MountInstance mountPoint, final URI namespace ) {
-        final Module module = this.findModuleByNamespace( mountPoint, namespace );
+    public String findModuleNameByNamespace(final MountInstance mountPoint, final URI namespace) {
+        final Module module = this.findModuleByNamespace(mountPoint, namespace);
         return module == null ? null : module.getName();
     }
 
-    public URI findNamespaceByModuleName( final String moduleName ) {
-        URI namespace = this.moduleNameToUri.get( moduleName );
-        if( namespace == null ) {
-            Module module = this.findModuleByName( moduleName );
-            if( module != null ) {
+    public URI findNamespaceByModuleName(final String moduleName) {
+        URI namespace = this.moduleNameToUri.get(moduleName);
+        if (namespace == null) {
+            Module module = this.findModuleByName(moduleName);
+            if (module != null) {
                 URI _namespace = module.getNamespace();
                 namespace = _namespace;
-                this.uriToModuleName.put( namespace, moduleName );
+                this.uriToModuleName.put(namespace, moduleName);
             }
         }
         return namespace;
     }
 
-    public URI findNamespaceByModuleName( final MountInstance mountPoint, final String moduleName ) {
-        final Module module = this.findModuleByName( mountPoint, moduleName );
+    public URI findNamespaceByModuleName(final MountInstance mountPoint, final String moduleName) {
+        final Module module = this.findModuleByName(mountPoint, moduleName);
         return module == null ? null : module.getNamespace();
     }
 
-    public Set<Module> getAllModules( final MountInstance mountPoint ) {
+    public Set<Module> getAllModules(final MountInstance mountPoint) {
         this.checkPreconditions();
 
         SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
@@ -348,55 +340,55 @@ public class ControllerContext implements SchemaContextListener {
         return globalSchema.getModules();
     }
 
-    public CharSequence toRestconfIdentifier( final QName qname ) {
+    public CharSequence toRestconfIdentifier(final QName qname) {
         this.checkPreconditions();
 
-        String module = this.uriToModuleName.get( qname.getNamespace() );
-        if( module == null ) {
-            final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(
-                    qname.getNamespace(), qname.getRevision() );
-            if( moduleSchema == null ) {
+        String module = this.uriToModuleName.get(qname.getNamespace());
+        if (module == null) {
+            final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(),
+                    qname.getRevision());
+            if (moduleSchema == null) {
                 return null;
             }
 
-            this.uriToModuleName.put( qname.getNamespace(), moduleSchema.getName() );
+            this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName());
             module = moduleSchema.getName();
         }
 
         StringBuilder builder = new StringBuilder();
-        builder.append( module );
-        builder.append( ":" );
-        builder.append( qname.getLocalName() );
+        builder.append(module);
+        builder.append(":");
+        builder.append(qname.getLocalName());
         return builder.toString();
     }
 
-    public CharSequence toRestconfIdentifier( final MountInstance mountPoint, final QName qname ) {
-        if( mountPoint == null ) {
+    public CharSequence toRestconfIdentifier(final MountInstance mountPoint, final QName qname) {
+        if (mountPoint == null) {
             return null;
         }
 
         SchemaContext schemaContext = mountPoint.getSchemaContext();
 
-        final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(
-                qname.getNamespace(), qname.getRevision() );
-        if( moduleSchema == null ) {
+        final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
+                qname.getRevision());
+        if (moduleSchema == null) {
             return null;
         }
 
         StringBuilder builder = new StringBuilder();
-        builder.append( moduleSchema.getName() );
-        builder.append( ":" );
-        builder.append( qname.getLocalName() );
+        builder.append(moduleSchema.getName());
+        builder.append(":");
+        builder.append(qname.getLocalName());
         return builder.toString();
     }
 
     public Module getRestconfModule() {
-        return findModuleByNameAndRevision( Draft02.RestConfModule.IETF_RESTCONF_QNAME );
+        return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
     }
 
     public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
         Module restconfModule = getRestconfModule();
-        if( restconfModule == null ) {
+        if (restconfModule == null) {
             return null;
         }
 
@@ -405,8 +397,7 @@ public class ControllerContext implements SchemaContextListener {
         final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
             @Override
             public boolean apply(final GroupingDefinition g) {
-                return Objects.equal(g.getQName().getLocalName(),
-                        Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE);
+                return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE);
             }
         };
 
@@ -414,20 +405,18 @@ public class ControllerContext implements SchemaContextListener {
 
         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
 
-        List<DataSchemaNode> instanceDataChildrenByName =
-                this.findInstanceDataChildrenByName(restconfGrouping,
-                        Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
+        List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
+                Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
         return Iterables.getFirst(instanceDataChildrenByName, null);
     }
 
-    public DataSchemaNode getRestconfModuleRestConfSchemaNode( final Module inRestconfModule,
-            final String schemaNodeName ) {
+    public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
         Module restconfModule = inRestconfModule;
-        if( restconfModule == null ) {
+        if (restconfModule == null) {
             restconfModule = getRestconfModule();
         }
 
-        if( restconfModule == null ) {
+        if (restconfModule == null) {
             return null;
         }
 
@@ -436,8 +425,7 @@ public class ControllerContext implements SchemaContextListener {
         final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
             @Override
             public boolean apply(final GroupingDefinition g) {
-                return Objects.equal(g.getQName().getLocalName(),
-                        Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
+                return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
             }
         };
 
@@ -445,61 +433,49 @@ public class ControllerContext implements SchemaContextListener {
 
         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
 
-        List<DataSchemaNode> instanceDataChildrenByName =
-                this.findInstanceDataChildrenByName(restconfGrouping,
-                        Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
+        List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
+                Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
         final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
 
         if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
-            List<DataSchemaNode> instances =
-                    this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
-                            Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
+            List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
+                    ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
             return Iterables.getFirst(instances, null);
-        }
-        else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
-            List<DataSchemaNode> instances =
-                    this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
-                            Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+        } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
+            List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
+                    ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
             return Iterables.getFirst(instances, null);
-        }
-        else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
-            List<DataSchemaNode> instances =
-                    this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
-                            Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+        } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
+            List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
+                    ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
             final DataSchemaNode modules = Iterables.getFirst(instances, null);
             instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
                     Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
             return Iterables.getFirst(instances, null);
-        }
-        else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
-            List<DataSchemaNode> instances =
-                    this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
-                            Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
+        } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
+            List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
+                    ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
             return Iterables.getFirst(instances, null);
-        }
-        else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
-            List<DataSchemaNode> instances =
-                    this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
-                            Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
+        } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
+            List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
+                    ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
             final DataSchemaNode modules = Iterables.getFirst(instances, null);
             instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
                     Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
             return Iterables.getFirst(instances, null);
-        }
-        else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
-            List<DataSchemaNode> instances =
-                    this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
-                            Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+        } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
+            List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
+                    ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
             return Iterables.getFirst(instances, null);
         }
 
         return null;
     }
 
-    private static DataSchemaNode childByQName( final ChoiceNode container, final QName name ) {
-        for( final ChoiceCaseNode caze : container.getCases() ) {
-            final DataSchemaNode ret = ControllerContext.childByQName( caze, name );
-            if( ret != null ) {
+    private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
+        for (final ChoiceCaseNode caze : container.getCases()) {
+            final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
+            if (ret != null) {
                 return ret;
             }
         }
@@ -507,34 +483,34 @@ public class ControllerContext implements SchemaContextListener {
         return null;
     }
 
-    private static DataSchemaNode childByQName( final ChoiceCaseNode container, final QName name ) {
-        return container.getDataChildByName( name );
+    private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
+        return container.getDataChildByName(name);
     }
 
-    private static DataSchemaNode childByQName( final ContainerSchemaNode container, final QName name ) {
-        return ControllerContext.dataNodeChildByQName( container, name );
+    private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
+        return ControllerContext.dataNodeChildByQName(container, name);
     }
 
-    private static DataSchemaNode childByQName( final ListSchemaNode container, final QName name ) {
-        return ControllerContext.dataNodeChildByQName( container, name );
+    private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
+        return ControllerContext.dataNodeChildByQName(container, name);
     }
 
-    private static DataSchemaNode childByQName( final Module container, final QName name ) {
-        return ControllerContext.dataNodeChildByQName( container, name );
+    private static DataSchemaNode childByQName(final Module container, final QName name) {
+        return ControllerContext.dataNodeChildByQName(container, name);
     }
 
-    private static DataSchemaNode childByQName( final DataSchemaNode container, final QName name ) {
+    private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
         return null;
     }
 
-    private static DataSchemaNode dataNodeChildByQName( final DataNodeContainer container, final QName name ) {
-        DataSchemaNode ret = container.getDataChildByName( name );
-        if( ret == null ) {
-            for( final DataSchemaNode node : container.getChildNodes() ) {
-                if( (node instanceof ChoiceCaseNode) ) {
+    private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
+        DataSchemaNode ret = container.getDataChildByName(name);
+        if (ret == null) {
+            for (final DataSchemaNode node : container.getChildNodes()) {
+                if ((node instanceof ChoiceCaseNode)) {
                     final ChoiceCaseNode caseNode = ((ChoiceCaseNode) node);
-                    DataSchemaNode childByQName = ControllerContext.childByQName( caseNode, name );
-                    if( childByQName != null ) {
+                    DataSchemaNode childByQName = ControllerContext.childByQName(caseNode, name);
+                    if (childByQName != null) {
                         return childByQName;
                     }
                 }
@@ -543,463 +519,427 @@ public class ControllerContext implements SchemaContextListener {
         return ret;
     }
 
-    private String toUriString( final Object object ) throws UnsupportedEncodingException {
-        return object == null ? "" :
-            URLEncoder.encode( object.toString(), ControllerContext.URI_ENCODING_CHAR_SET );
+    private String toUriString(final Object object) throws UnsupportedEncodingException {
+        return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
     }
 
-    private InstanceIdWithSchemaNode collectPathArguments( final InstanceIdentifierBuilder builder,
+    private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
             final List<String> strings, final DataNodeContainer parentNode, final MountInstance mountPoint,
-            final boolean returnJustMountPoint ) {
-        Preconditions.<List<String>> checkNotNull( strings );
+            final boolean returnJustMountPoint) {
+        Preconditions.<List<String>> checkNotNull(strings);
 
-        if( parentNode == null ) {
+        if (parentNode == null) {
             return null;
         }
 
-        if( strings.isEmpty() ) {
-            return new InstanceIdWithSchemaNode( builder.toInstance(),
-                    ((DataSchemaNode) parentNode), mountPoint );
+        if (strings.isEmpty()) {
+            return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
         }
 
         String head = strings.iterator().next();
-        final String nodeName = toNodeName( head );
-        final String moduleName = ControllerContext.toModuleName( head );
+        final String nodeName = toNodeName(head);
+        final String moduleName = ControllerContext.toModuleName(head);
 
         DataSchemaNode targetNode = null;
-        if( !Strings.isNullOrEmpty( moduleName ) ) {
-            if( Objects.equal( moduleName, ControllerContext.MOUNT_MODULE ) &&
-                    Objects.equal( nodeName, ControllerContext.MOUNT_NODE ) ) {
-                if( mountPoint != null ) {
-                    throw new RestconfDocumentedException(
-                            "Restconf supports just one mount point in URI.",
-                            ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED );
+        if (!Strings.isNullOrEmpty(moduleName)) {
+            if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
+                    && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
+                if (mountPoint != null) {
+                    throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
+                            ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
                 }
 
-                if( mountService == null ) {
+                if (mountService == null) {
                     throw new RestconfDocumentedException(
                             "MountService was not found. Finding behind mount points does not work.",
-                            ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED );
+                            ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
                 }
 
                 final InstanceIdentifier partialPath = builder.toInstance();
-                final MountInstance mount = mountService.getMountPoint( partialPath );
-                if( mount == null ) {
-                    LOG.debug( "Instance identifier to missing mount point: {}", partialPath );
-                    throw new RestconfDocumentedException(
-                            "Mount point does not exist.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+                final MountInstance mount = mountService.getMountPoint(partialPath);
+                if (mount == null) {
+                    LOG.debug("Instance identifier to missing mount point: {}", partialPath);
+                    throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
+                            ErrorTag.UNKNOWN_ELEMENT);
                 }
 
                 final SchemaContext mountPointSchema = mount.getSchemaContext();
-                if( mountPointSchema == null ) {
-                    throw new RestconfDocumentedException(
-                            "Mount point does not contain any schema with modules.",
-                            ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT );
+                if (mountPointSchema == null) {
+                    throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
+                            ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
                 }
 
-                if( returnJustMountPoint ) {
+                if (returnJustMountPoint) {
                     InstanceIdentifier instance = InstanceIdentifier.builder().toInstance();
-                    return new InstanceIdWithSchemaNode( instance, mountPointSchema, mount );
+                    return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
                 }
 
-                if( strings.size() == 1 ) {
+                if (strings.size() == 1) {
                     InstanceIdentifier instance = InstanceIdentifier.builder().toInstance();
-                    return new InstanceIdWithSchemaNode( instance, mountPointSchema, mount );
+                    return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
                 }
 
-                final String moduleNameBehindMountPoint = toModuleName(  strings.get( 1 ) );
-                if( moduleNameBehindMountPoint == null ) {
+                final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
+                if (moduleNameBehindMountPoint == null) {
                     throw new RestconfDocumentedException(
                             "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
-                            ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                            ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
                 }
 
-                final Module moduleBehindMountPoint = this.getLatestModule( mountPointSchema,
-                        moduleNameBehindMountPoint );
-                if( moduleBehindMountPoint == null ) {
-                    throw new RestconfDocumentedException(
-                            "\"" +moduleName + "\" module does not exist in mount point.",
-                            ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+                final Module moduleBehindMountPoint = this
+                        .getLatestModule(mountPointSchema, moduleNameBehindMountPoint);
+                if (moduleBehindMountPoint == null) {
+                    throw new RestconfDocumentedException("\"" + moduleName
+                            + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
                 }
 
-                List<String> subList = strings.subList( 1, strings.size() );
-                return this.collectPathArguments( InstanceIdentifier.builder(), subList, moduleBehindMountPoint,
-                        mount, returnJustMountPoint );
+                List<String> subList = strings.subList(1, strings.size());
+                return this.collectPathArguments(InstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
+                        returnJustMountPoint);
             }
 
             Module module = null;
-            if( mountPoint == null ) {
-                module = this.getLatestModule( globalSchema, moduleName );
-                if( module == null ) {
-                    throw new RestconfDocumentedException(
-                            "\"" + moduleName + "\" module does not exist.",
-                            ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+            if (mountPoint == null) {
+                module = this.getLatestModule(globalSchema, moduleName);
+                if (module == null) {
+                    throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
+                            ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
                 }
-            }
-            else {
+            } else {
                 SchemaContext schemaContext = mountPoint.getSchemaContext();
-                module = schemaContext == null ? null :
-                    this.getLatestModule( schemaContext, moduleName );
-                if( module == null ) {
-                    throw new RestconfDocumentedException(
-                            "\"" + moduleName + "\" module does not exist in mount point.",
-                            ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+                module = schemaContext == null ? null : this.getLatestModule(schemaContext, moduleName);
+                if (module == null) {
+                    throw new RestconfDocumentedException("\"" + moduleName
+                            + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
                 }
             }
 
-            targetNode = this.findInstanceDataChildByNameAndNamespace(
-                    parentNode, nodeName, module.getNamespace() );
-            if( targetNode == null ) {
-                throw new RestconfDocumentedException(
-                        "URI has bad format. Possible reasons:\n" +
-                                " 1. \"" + head + "\" was not found in parent data node.\n" +
-                                " 2. \"" + head + "\" is behind mount point. Then it should be in format \"/" +
-                                MOUNT + "/" + head + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
+            if (targetNode == null) {
+                throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
+                        + "\" was not found in parent data node.\n" + " 2. \"" + head
+                        + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
+                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
             }
         } else {
-            final List<DataSchemaNode> potentialSchemaNodes =
-                    this.findInstanceDataChildrenByName( parentNode, nodeName );
-            if( potentialSchemaNodes.size() > 1 ) {
+            final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
+            if (potentialSchemaNodes.size() > 1) {
                 final StringBuilder strBuilder = new StringBuilder();
-                for( final DataSchemaNode potentialNodeSchema : potentialSchemaNodes ) {
-                    strBuilder.append( "   " )
-                    .append( potentialNodeSchema.getQName().getNamespace() )
-                    .append( "\n" );
+                for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
+                    strBuilder.append("   ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
                 }
 
                 throw new RestconfDocumentedException(
-                        "URI has bad format. Node \"" + nodeName +
-                        "\" is added as augment from more than one module. " +
-                        "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"." +
-                        "\nThe node is added as augment from modules with namespaces:\n" +
-                        strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                        "URI has bad format. Node \""
+                                + nodeName
+                                + "\" is added as augment from more than one module. "
+                                + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
+                                + "\nThe node is added as augment from modules with namespaces:\n"
+                                + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
             }
 
-            if( potentialSchemaNodes.isEmpty() ) {
-                throw new RestconfDocumentedException(
-                        "\"" + nodeName + "\" in URI was not found in parent data node",
-                        ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+            if (potentialSchemaNodes.isEmpty()) {
+                throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
+                        ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
             }
 
             targetNode = potentialSchemaNodes.iterator().next();
         }
 
-        if( !this.isListOrContainer( targetNode ) ) {
-            throw new RestconfDocumentedException(
-                    "URI has bad format. Node \"" + head + "\" must be Container or List yang type.",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        if (!this.isListOrContainer(targetNode)) {
+            throw new RestconfDocumentedException("URI has bad format. Node \"" + head
+                    + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         int consumed = 1;
-        if( (targetNode instanceof ListSchemaNode) ) {
+        if ((targetNode instanceof ListSchemaNode)) {
             final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
             final int keysSize = listNode.getKeyDefinition().size();
-            if( (strings.size() - consumed) < keysSize ) {
-                throw new RestconfDocumentedException(
-                        "Missing key for list \"" + listNode.getQName().getLocalName() + "\".",
-                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            if ((strings.size() - consumed) < keysSize) {
+                throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
+                        + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
             }
 
-            final List<String> uriKeyValues = strings.subList( consumed, consumed + keysSize );
+            final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
             final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
             int i = 0;
-            for( final QName key : listNode.getKeyDefinition() ) {
+            for (final QName key : listNode.getKeyDefinition()) {
                 {
-                    final String uriKeyValue = uriKeyValues.get( i );
-                    if( uriKeyValue.equals( NULL_VALUE ) ) {
-                        throw new RestconfDocumentedException(
-                                "URI has bad format. List \"" + listNode.getQName().getLocalName() +
-                                "\" cannot contain \"null\" value as a key.",
-                                ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                    final String uriKeyValue = uriKeyValues.get(i);
+                    if (uriKeyValue.equals(NULL_VALUE)) {
+                        throw new RestconfDocumentedException("URI has bad format. List \""
+                                + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
+                                ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
                     }
 
-                    this.addKeyValue( keyValues, listNode.getDataChildByName( key ),
-                            uriKeyValue, mountPoint );
+                    this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
                     i++;
                 }
             }
 
             consumed = consumed + i;
-            builder.nodeWithKey( targetNode.getQName(), keyValues );
-        }
-        else {
-            builder.node( targetNode.getQName() );
+            builder.nodeWithKey(targetNode.getQName(), keyValues);
+        } else {
+            builder.node(targetNode.getQName());
         }
 
-        if( (targetNode instanceof DataNodeContainer) ) {
-            final List<String> remaining = strings.subList( consumed, strings.size() );
-            return this.collectPathArguments( builder, remaining,
-                    ((DataNodeContainer) targetNode), mountPoint, returnJustMountPoint );
+        if ((targetNode instanceof DataNodeContainer)) {
+            final List<String> remaining = strings.subList(consumed, strings.size());
+            return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
+                    returnJustMountPoint);
         }
 
-        return new InstanceIdWithSchemaNode( builder.toInstance(), targetNode, mountPoint );
+        return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
     }
 
-    public DataSchemaNode findInstanceDataChildByNameAndNamespace( final DataNodeContainer container,
-            final String name, final URI namespace ) {
-        Preconditions.<URI> checkNotNull( namespace );
+    public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
+            final URI namespace) {
+        Preconditions.<URI> checkNotNull(namespace);
 
-        final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName( container, name );
+        final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
 
         Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
             @Override
-            public boolean apply( final DataSchemaNode node ) {
-                return Objects.equal( node.getQName().getNamespace(), namespace );
+            public boolean apply(final DataSchemaNode node) {
+                return Objects.equal(node.getQName().getNamespace(), namespace);
             }
         };
 
-        Iterable<DataSchemaNode> result = Iterables.filter( potentialSchemaNodes, filter );
-        return Iterables.getFirst( result, null );
+        Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
+        return Iterables.getFirst(result, null);
     }
 
-    public List<DataSchemaNode> findInstanceDataChildrenByName( final DataNodeContainer container,
-            final String name ) {
-        Preconditions.<DataNodeContainer> checkNotNull( container );
-        Preconditions.<String> checkNotNull( name );
+    public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
+        Preconditions.<DataNodeContainer> checkNotNull(container);
+        Preconditions.<String> checkNotNull(name);
 
         List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
-        this.collectInstanceDataNodeContainers( instantiatedDataNodeContainers, container, name );
+        this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
         return instantiatedDataNodeContainers;
     }
 
-    private void collectInstanceDataNodeContainers( final List<DataSchemaNode> potentialSchemaNodes,
-            final DataNodeContainer container, final String name ) {
+    private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
+            final DataNodeContainer container, final String name) {
 
         Set<DataSchemaNode> childNodes = container.getChildNodes();
 
         Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
             @Override
-            public boolean apply( final DataSchemaNode node ) {
-                return Objects.equal( node.getQName().getLocalName(), name );
+            public boolean apply(final DataSchemaNode node) {
+                return Objects.equal(node.getQName().getLocalName(), name);
             }
         };
 
-        Iterable<DataSchemaNode> nodes = Iterables.filter( childNodes, filter );
+        Iterable<DataSchemaNode> nodes = Iterables.filter(childNodes, filter);
 
-        // Can't combine this loop with the filter above because the filter is lazily-applied
-        // by Iterables.filter.
-        for( final DataSchemaNode potentialNode : nodes ) {
-            if( this.isInstantiatedDataSchema( potentialNode ) ) {
-                potentialSchemaNodes.add( potentialNode );
+        // Can't combine this loop with the filter above because the filter is
+        // lazily-applied by Iterables.filter.
+        for (final DataSchemaNode potentialNode : nodes) {
+            if (this.isInstantiatedDataSchema(potentialNode)) {
+                potentialSchemaNodes.add(potentialNode);
             }
         }
 
-        Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter( container.getChildNodes(),
-                ChoiceNode.class );
+        Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter(container.getChildNodes(), ChoiceNode.class);
 
-        final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction =
-                new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
+        final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
             @Override
-            public Set<ChoiceCaseNode> apply( final ChoiceNode node ) {
+            public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
                 return node.getCases();
             }
         };
 
-        Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(
-                choiceNodes, choiceFunction );
+        Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(choiceNodes,
+                choiceFunction);
 
-        final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat( map );
-        for( final ChoiceCaseNode caze : allCases ) {
-            this.collectInstanceDataNodeContainers( potentialSchemaNodes, caze, name );
+        final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
+        for (final ChoiceCaseNode caze : allCases) {
+            this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
         }
     }
 
-    public boolean isInstantiatedDataSchema( final DataSchemaNode node ) {
-        return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode ||
-                node instanceof ContainerSchemaNode || node instanceof ListSchemaNode ||
-                node instanceof AnyXmlSchemaNode;
+    public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
+        return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
+                || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
+                || node instanceof AnyXmlSchemaNode;
     }
 
-    private void addKeyValue( final HashMap<QName, Object> map, final DataSchemaNode node,
-            final String uriValue, final MountInstance mountPoint ) {
-        Preconditions.<String> checkNotNull( uriValue );
-        Preconditions.checkArgument( (node instanceof LeafSchemaNode) );
+    private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
+            final MountInstance mountPoint) {
+        Preconditions.<String> checkNotNull(uriValue);
+        Preconditions.checkArgument((node instanceof LeafSchemaNode));
 
-        final String urlDecoded = urlPathArgDecode( uriValue );
+        final String urlDecoded = urlPathArgDecode(uriValue);
         final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
-        Codec<Object, Object> codec = RestCodec.from( typedef, mountPoint );
+        Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
 
-        Object decoded = codec == null ? null : codec.deserialize( urlDecoded );
+        Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
         String additionalInfo = "";
-        if( decoded == null ) {
-            TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom( typedef );
-            if( (baseType instanceof IdentityrefTypeDefinition) ) {
-                decoded = this.toQName( urlDecoded );
+        if (decoded == null) {
+            TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
+            if ((baseType instanceof IdentityrefTypeDefinition)) {
+                decoded = this.toQName(urlDecoded);
                 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
             }
         }
 
-        if( decoded == null ) {
-            throw new RestconfDocumentedException(
-                    uriValue + " from URI can't be resolved. " + additionalInfo,
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        if (decoded == null) {
+            throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
-        map.put( node.getQName(), decoded );
+        map.put(node.getQName(), decoded);
     }
 
-    private static String toModuleName( final String str ) {
-        Preconditions.<String> checkNotNull( str );
-        if( str.indexOf( ':' ) != -1 ) {
-            final Iterable<String> args = COLON_SPLITTER.split( str );
-            if( Iterables.size( args ) == 2 ) {
+    private static String toModuleName(final String str) {
+        Preconditions.<String> checkNotNull(str);
+        if (str.indexOf(':') != -1) {
+            final Iterable<String> args = COLON_SPLITTER.split(str);
+            if (Iterables.size(args) == 2) {
                 return args.iterator().next();
             }
         }
         return null;
     }
 
-    private static String toNodeName( final String str ) {
-        if( str.indexOf( ':' ) != -1 ) {
-            final Iterable<String> args = COLON_SPLITTER.split( str );
-            if( Iterables.size( args ) == 2 ) {
-                return Iterables.get( args, 1 );
+    private static String toNodeName(final String str) {
+        if (str.indexOf(':') != -1) {
+            final Iterable<String> args = COLON_SPLITTER.split(str);
+            if (Iterables.size(args) == 2) {
+                return Iterables.get(args, 1);
             }
         }
         return str;
     }
 
-    private QName toQName( final String name ) {
-        final String module = toModuleName( name );
-        final String node = toNodeName( name );
+    private QName toQName(final String name) {
+        final String module = toModuleName(name);
+        final String node = toNodeName(name);
         Set<Module> modules = globalSchema.getModules();
 
         final Comparator<Module> comparator = new Comparator<Module>() {
             @Override
-            public int compare( final Module o1, final Module o2 ) {
-                return o1.getRevision().compareTo( o2.getRevision() );
+            public int compare(final Module o1, final Module o2) {
+                return o1.getRevision().compareTo(o2.getRevision());
             }
         };
 
-        List<Module> sorted = new ArrayList<Module>( modules );
-        Collections.<Module> sort( new ArrayList<Module>( modules ), comparator );
+        List<Module> sorted = new ArrayList<Module>(modules);
+        Collections.<Module> sort(new ArrayList<Module>(modules), comparator);
 
         final Function<Module, QName> transform = new Function<Module, QName>() {
             @Override
-            public QName apply( final Module m ) {
-                return QName.create( m.getNamespace(), m.getRevision(), m.getName() );
+            public QName apply(final Module m) {
+                return QName.create(m.getNamespace(), m.getRevision(), m.getName());
             }
         };
 
         final Predicate<QName> findFirst = new Predicate<QName>() {
             @Override
-            public boolean apply( final QName qn ) {
-                return Objects.equal( module, qn.getLocalName() );
+            public boolean apply(final QName qn) {
+                return Objects.equal(module, qn.getLocalName());
             }
         };
 
-        Optional<QName> namespace = FluentIterable.from( sorted )
-                .transform( transform )
-                .firstMatch( findFirst );
-        return namespace.isPresent() ? QName.create( namespace.get(), node ) : null;
+        Optional<QName> namespace = FluentIterable.from(sorted).transform(transform).firstMatch(findFirst);
+        return namespace.isPresent() ? QName.create(namespace.get(), node) : null;
     }
 
-    private boolean isListOrContainer( final DataSchemaNode node ) {
+    private boolean isListOrContainer(final DataSchemaNode node) {
         return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
     }
 
-    public RpcDefinition getRpcDefinition( final String name ) {
-        final QName validName = this.toQName( name );
-        return validName == null ? null : this.qnameToRpc.get( validName );
+    public RpcDefinition getRpcDefinition(final String name) {
+        final QName validName = this.toQName(name);
+        return validName == null ? null : this.qnameToRpc.get(validName);
     }
 
     @Override
-    public void onGlobalContextUpdated( final SchemaContext context ) {
-        if( context != null ) {
+    public void onGlobalContextUpdated(final SchemaContext context) {
+        if (context != null) {
             this.qnameToRpc.clear();
-            this.setGlobalSchema( context );
+            this.setGlobalSchema(context);
             Set<RpcDefinition> _operations = context.getOperations();
-            for( final RpcDefinition operation : _operations ) {
+            for (final RpcDefinition operation : _operations) {
                 {
-                    this.qnameToRpc.put( operation.getQName(), operation );
+                    this.qnameToRpc.put(operation.getQName(), operation);
                 }
             }
         }
     }
 
-    public static List<String> urlPathArgsDecode( final Iterable<String> strings ) {
+    public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
         try {
             List<String> decodedPathArgs = new ArrayList<String>();
-            for( final String pathArg : strings ) {
-                String _decode = URLDecoder.decode( pathArg, URI_ENCODING_CHAR_SET );
-                decodedPathArgs.add( _decode );
+            for (final String pathArg : strings) {
+                String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
+                decodedPathArgs.add(_decode);
             }
             return decodedPathArgs;
-        }
-        catch( UnsupportedEncodingException e ) {
-            throw new RestconfDocumentedException(
-                    "Invalid URL path '" + strings + "': " + e.getMessage(),
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        } catch (UnsupportedEncodingException e) {
+            throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
     }
 
-    public String urlPathArgDecode( final String pathArg ) {
-        if( pathArg != null ) {
+    public String urlPathArgDecode(final String pathArg) {
+        if (pathArg != null) {
             try {
-                return URLDecoder.decode( pathArg, URI_ENCODING_CHAR_SET );
-            }
-            catch( UnsupportedEncodingException e ) {
-                throw new RestconfDocumentedException(
-                        "Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
-                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
+            } catch (UnsupportedEncodingException e) {
+                throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
+                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
             }
         }
 
         return null;
     }
 
-    private CharSequence convertToRestconfIdentifier( final PathArgument argument,
-            final DataNodeContainer node ) {
-        if( argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode ) {
-            return convertToRestconfIdentifier( (NodeIdentifier) argument, (ContainerSchemaNode) node );
-        }
-        else if( argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode ) {
-            return convertToRestconfIdentifier( (NodeIdentifierWithPredicates) argument, (ListSchemaNode) node );
-        }
-        else if( argument != null && node != null ) {
-            throw new IllegalArgumentException(
-                    "Conversion of generic path argument is not supported" );
-        }
-        else {
-            throw new IllegalArgumentException( "Unhandled parameter types: "
-                    + Arrays.<Object> asList( argument, node ).toString() );
+    private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
+        if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
+            return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
+        } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
+            return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
+        } else if (argument != null && node != null) {
+            throw new IllegalArgumentException("Conversion of generic path argument is not supported");
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: "
+                    + Arrays.<Object> asList(argument, node).toString());
         }
     }
 
-    private CharSequence convertToRestconfIdentifier( final NodeIdentifier argument,
-            final ContainerSchemaNode node ) {
+    private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
         StringBuilder builder = new StringBuilder();
-        builder.append( "/" );
+        builder.append("/");
         QName nodeType = argument.getNodeType();
-        builder.append( this.toRestconfIdentifier( nodeType ) );
+        builder.append(this.toRestconfIdentifier(nodeType));
         return builder.toString();
     }
 
-    private CharSequence convertToRestconfIdentifier( final NodeIdentifierWithPredicates argument,
-            final ListSchemaNode node ) {
+    private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
+            final ListSchemaNode node) {
         QName nodeType = argument.getNodeType();
-        final CharSequence nodeIdentifier = this.toRestconfIdentifier( nodeType );
+        final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
         final Map<QName, Object> keyValues = argument.getKeyValues();
 
         StringBuilder builder = new StringBuilder();
-        builder.append( "/" );
-        builder.append( nodeIdentifier );
-        builder.append( "/" );
+        builder.append("/");
+        builder.append(nodeIdentifier);
+        builder.append("/");
 
         List<QName> keyDefinition = node.getKeyDefinition();
         boolean hasElements = false;
-        for( final QName key : keyDefinition ) {
-            if( !hasElements ) {
+        for (final QName key : keyDefinition) {
+            if (!hasElements) {
                 hasElements = true;
-            }
-            else {
-                builder.append( "/" );
+            } else {
+                builder.append("/");
             }
 
             try {
-                builder.append( this.toUriString( keyValues.get( key ) ) );
-            } catch( UnsupportedEncodingException e ) {
-                LOG.error( "Error parsing URI: {}", keyValues.get( key ), e );
+                builder.append(this.toUriString(keyValues.get(key)));
+            } catch (UnsupportedEncodingException e) {
+                LOG.error("Error parsing URI: {}", keyValues.get(key), e);
                 return null;
             }
         }
@@ -1007,28 +947,22 @@ public class ControllerContext implements SchemaContextListener {
         return builder.toString();
     }
 
-    private static DataSchemaNode childByQName( final Object container, final QName name ) {
-        if( container instanceof ChoiceCaseNode ) {
-            return childByQName( (ChoiceCaseNode) container, name );
-        }
-        else if( container instanceof ChoiceNode ) {
-            return childByQName( (ChoiceNode) container, name );
-        }
-        else if( container instanceof ContainerSchemaNode ) {
-            return childByQName( (ContainerSchemaNode) container, name );
-        }
-        else if( container instanceof ListSchemaNode ) {
-            return childByQName( (ListSchemaNode) container, name );
-        }
-        else if( container instanceof DataSchemaNode ) {
-            return childByQName( (DataSchemaNode) container, name );
-        }
-        else if( container instanceof Module ) {
-            return childByQName( (Module) container, name );
-        }
-        else {
-            throw new IllegalArgumentException( "Unhandled parameter types: "
-                    + Arrays.<Object> asList( container, name ).toString() );
+    private static DataSchemaNode childByQName(final Object container, final QName name) {
+        if (container instanceof ChoiceCaseNode) {
+            return childByQName((ChoiceCaseNode) container, name);
+        } else if (container instanceof ChoiceNode) {
+            return childByQName((ChoiceNode) container, name);
+        } else if (container instanceof ContainerSchemaNode) {
+            return childByQName((ContainerSchemaNode) container, name);
+        } else if (container instanceof ListSchemaNode) {
+            return childByQName((ListSchemaNode) container, name);
+        } else if (container instanceof DataSchemaNode) {
+            return childByQName((DataSchemaNode) container, name);
+        } else if (container instanceof Module) {
+            return childByQName((Module) container, name);
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: "
+                    + Arrays.<Object> asList(container, name).toString());
         }
     }
 }
index f93a0aea70fa311a7dd0b6f8ba520d8153f03b89..a3d44d3572106232e10edaad73e91d1b4d46039a 100644 (file)
@@ -8,10 +8,8 @@
 package org.opendaylight.controller.sal.restconf.impl;
 
 import com.google.common.base.Preconditions;
-
 import java.net.URI;
 import java.util.Collections;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.Node;
@@ -85,8 +83,9 @@ public final class EmptyNodeWrapper implements NodeWrapper<Node<?>>, Node<Void>
                 Preconditions.checkNotNull(namespace);
                 name = new QName(namespace, localName);
             }
-            if(composite) {
-                unwrapped = NodeFactory.createImmutableCompositeNode(name, null, Collections.<Node<?>>emptyList(),null);
+            if (composite) {
+                unwrapped = NodeFactory.createImmutableCompositeNode(name, null, Collections.<Node<?>> emptyList(),
+                        null);
             } else {
                 unwrapped = NodeFactory.createImmutableSimpleNode(name, null, null);
             }
index d66e1610a58e62b07a1834b0c7b61197f49b2ab4..4e797d905739a6b894d2c6a9179b2219af621943 100644 (file)
@@ -16,7 +16,7 @@ public final class IdentityValuesDTO {
     private final List<IdentityValue> elementData = new ArrayList<>();
     private final String originValue;
 
-    public IdentityValuesDTO(String namespace, String value, String prefix,String originValue) {
+    public IdentityValuesDTO(String namespace, String value, String prefix, String originValue) {
         elementData.add(new IdentityValue(namespace, value, prefix));
         this.originValue = originValue;
     }
@@ -37,7 +37,6 @@ public final class IdentityValuesDTO {
         elementData.add(identityValue);
     }
 
-
     public List<IdentityValue> getValuesWithNamespaces() {
         return Collections.unmodifiableList(elementData);
     }
index 68135dea95f1e90e8574d230d7adb202355e8d4d..08e0ce1f24dcc5a8a68e0bd3513fb4bad093b030 100644 (file)
@@ -17,7 +17,8 @@ public class InstanceIdWithSchemaNode {
     private final DataSchemaNode schemaNode;
     private final MountInstance mountPoint;
 
-    public InstanceIdWithSchemaNode(InstanceIdentifier instanceIdentifier, DataSchemaNode schemaNode, MountInstance mountPoint) {
+    public InstanceIdWithSchemaNode(InstanceIdentifier instanceIdentifier, DataSchemaNode schemaNode,
+            MountInstance mountPoint) {
         this.instanceIdentifier = instanceIdentifier;
         this.schemaNode = schemaNode;
         this.mountPoint = mountPoint;
index 48fd1a3dfc49e4abf6d22ae040cf504781ff0bc8..9637a36268860e13e8ac296004089aed6c8ce825 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.controller.sal.restconf.impl;
 
 import java.net.URI;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.Node;
 
index 14b8282312d7accd1ba0c912a55178c72d3f317c..92a7014438cff009299fdd3a2cf37ae8959d0d6b 100644 (file)
@@ -12,7 +12,6 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.controller.sal.rest.impl.RestUtil;
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue;
@@ -47,7 +46,8 @@ public class RestCodec {
     private RestCodec() {
     }
 
-    public static final Codec<Object, Object> from(final TypeDefinition<?> typeDefinition, final MountInstance mountPoint) {
+    public static final Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
+            final MountInstance mountPoint) {
         return new ObjectCodec(typeDefinition, mountPoint);
     }
 
@@ -90,7 +90,7 @@ public class RestCodec {
                     return null;
                 } else if (type instanceof LeafrefTypeDefinition) {
                     if (input instanceof IdentityValuesDTO) {
-                        return LEAFREF_DEFAULT_CODEC.deserialize(((IdentityValuesDTO)input).getOriginValue());
+                        return LEAFREF_DEFAULT_CODEC.deserialize(((IdentityValuesDTO) input).getOriginValue());
                     }
                     return LEAFREF_DEFAULT_CODEC.deserialize(input);
                 } else if (type instanceof InstanceIdentifierTypeDefinition) {
@@ -106,7 +106,7 @@ public class RestCodec {
                             .from(type);
                     if (typeAwarecodec != null) {
                         if (input instanceof IdentityValuesDTO) {
-                            return typeAwarecodec.deserialize(((IdentityValuesDTO)input).getOriginValue());
+                            return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
                         }
                         return typeAwarecodec.deserialize(String.valueOf(input));
                     } else {
@@ -115,8 +115,7 @@ public class RestCodec {
                         return null;
                     }
                 }
-            } catch (ClassCastException e) { // TODO remove this catch when
-                // everyone use codecs
+            } 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);
@@ -145,8 +144,7 @@ public class RestCodec {
                         return null;
                     }
                 }
-            } catch (ClassCastException e) { // TODO remove this catch when
-                // everyone use codecs
+            } 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);
@@ -168,7 +166,7 @@ public class RestCodec {
 
         @Override
         public IdentityValuesDTO serialize(final QName data) {
-            return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), data.getPrefix(),null);
+            return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), data.getPrefix(), null);
         }
 
         @Override
@@ -234,8 +232,10 @@ public class RestCodec {
             IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
             Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
             if (module == null) {
-                logger.info("Module by namespace '{}' of first node in instance-identiefier was not found.", valueWithNamespace.getNamespace());
-                logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(valueWithNamespace.getValue()));
+                logger.info("Module by namespace '{}' of first node in instance-identiefier was not found.",
+                        valueWithNamespace.getNamespace());
+                logger.info("Instance-identifier will be translated as NULL for data - {}",
+                        String.valueOf(valueWithNamespace.getValue()));
                 return null;
             }
 
@@ -248,7 +248,8 @@ public class RestCodec {
                         parentContainer, identityValue.getValue(), validNamespace);
                 if (node == null) {
                     logger.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
-                    logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
+                    logger.info("Instance-identifier will be translated as NULL for data - {}",
+                            String.valueOf(identityValue.getValue()));
                     return null;
                 }
                 QName qName = node.getQName();
@@ -260,7 +261,8 @@ public class RestCodec {
                         Predicate leafListPredicate = identityValue.getPredicates().get(0);
                         if (!leafListPredicate.isLeafList()) {
                             logger.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
-                            logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
+                            logger.info("Instance-identifier will be translated as NULL for data - {}",
+                                    String.valueOf(identityValue.getValue()));
                             return null;
                         }
                         pathArgument = new NodeWithValue(qName, leafListPredicate.getValue());
@@ -269,24 +271,28 @@ public class RestCodec {
                         Map<QName, Object> predicatesMap = new HashMap<>();
                         for (Predicate predicate : identityValue.getPredicates()) {
                             validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), mountPoint);
-                            DataSchemaNode listKey = ControllerContext.getInstance().findInstanceDataChildByNameAndNamespace(
-                                    listNode, predicate.getName().getValue(), validNamespace);
+                            DataSchemaNode listKey = ControllerContext.getInstance()
+                                    .findInstanceDataChildByNameAndNamespace(listNode, predicate.getName().getValue(),
+                                            validNamespace);
                             predicatesMap.put(listKey.getQName(), predicate.getValue());
                         }
                         pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap);
                     } else {
                         logger.info("Node {} is not List or Leaf-list.", node);
-                        logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
+                        logger.info("Instance-identifier will be translated as NULL for data - {}",
+                                String.valueOf(identityValue.getValue()));
                         return null;
                     }
                 }
                 result.add(pathArgument);
-                if (i < identities.size() - 1) { // last element in instance-identifier can be other than DataNodeContainer
+                if (i < identities.size() - 1) { // last element in instance-identifier can be other than
+                                                 // DataNodeContainer
                     if (node instanceof DataNodeContainer) {
                         parentContainer = (DataNodeContainer) node;
                     } else {
                         logger.info("Node {} isn't instance of DataNodeContainer", node);
-                        logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
+                        logger.info("Instance-identifier will be translated as NULL for data - {}",
+                                String.valueOf(identityValue.getValue()));
                         return null;
                     }
                 }
index 0548e95044e081592ef9bb7d49513b8be7ab48bb..e3e0c3a2bdc49cbf8fca3bb8104e673fa2ea0b2c 100644 (file)
@@ -8,20 +8,17 @@
 
 package org.opendaylight.controller.sal.restconf.impl;
 
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
 import java.util.List;
-
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.Response.Status;
-
 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
 
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-
 /**
- * Unchecked exception to communicate error information, as defined in the ietf restcong draft,
- * to be sent to the client.
+ * Unchecked exception to communicate error information, as defined in the ietf restcong draft, to be sent to the
+ * client.
  *
  * @author Devin Avery
  * @author Thomas Pantelis
@@ -35,70 +32,76 @@ public class RestconfDocumentedException extends WebApplicationException {
     private final Status status;
 
     /**
-     * Constructs an instance with an error message. The error type defaults to APPLICATION and
-     * the error tag defaults to OPERATION_FAILED.
+     * Constructs an instance with an error message. The error type defaults to APPLICATION and the error tag defaults
+     * to OPERATION_FAILED.
      *
-     * @param message A string which provides a plain text string describing the error.
+     * @param message
+     *            A string which provides a plain text string describing the error.
      */
-    public RestconfDocumentedException( String message ) {
-        this( message, RestconfError.ErrorType.APPLICATION, RestconfError.ErrorTag.OPERATION_FAILED );
+    public RestconfDocumentedException(String message) {
+        this(message, RestconfError.ErrorType.APPLICATION, RestconfError.ErrorTag.OPERATION_FAILED);
     }
 
     /**
      * Constructs an instance with an error message, error type, and error tag.
      *
-     * @param message A string which provides a plain text string describing the error.
-     * @param errorType The enumerated type indicating the layer where the error occurred.
-     * @param errorTag The enumerated tag representing a more specific error cause.
+     * @param message
+     *            A string which provides a plain text string describing the error.
+     * @param errorType
+     *            The enumerated type indicating the layer where the error occurred.
+     * @param errorTag
+     *            The enumerated tag representing a more specific error cause.
      */
-    public RestconfDocumentedException( String message, ErrorType errorType, ErrorTag errorTag ) {
-        this( null, new RestconfError( errorType, errorTag, message ) );
+    public RestconfDocumentedException(String message, ErrorType errorType, ErrorTag errorTag) {
+        this(null, new RestconfError(errorType, errorTag, message));
     }
 
     /**
-     * Constructs an instance with an error message and exception cause. The stack trace of the
-     * exception is included in the error info.
+     * Constructs an instance with an error message and exception cause. The stack trace of the exception is included in
+     * the error info.
      *
-     * @param message A string which provides a plain text string describing the error.
-     * @param cause The underlying exception cause.
+     * @param message
+     *            A string which provides a plain text string describing the error.
+     * @param cause
+     *            The underlying exception cause.
      */
-    public RestconfDocumentedException( String message, Throwable cause ) {
-        this( cause, new RestconfError( RestconfError.ErrorType.APPLICATION,
-                                        RestconfError.ErrorTag.OPERATION_FAILED, message,
-                                        null, RestconfError.toErrorInfo( cause ) ) );
+    public RestconfDocumentedException(String message, Throwable cause) {
+        this(cause, new RestconfError(RestconfError.ErrorType.APPLICATION, RestconfError.ErrorTag.OPERATION_FAILED,
+                message, null, RestconfError.toErrorInfo(cause)));
     }
 
     /**
      * Constructs an instance with the given error.
      */
-    public RestconfDocumentedException( RestconfError error ) {
-        this( null, error );
+    public RestconfDocumentedException(RestconfError error) {
+        this(null, error);
     }
 
     /**
      * Constructs an instance with the given errors.
      */
-    public RestconfDocumentedException( List<RestconfError> errors ) {
-        this.errors = ImmutableList.copyOf( errors );
-        Preconditions.checkArgument( !this.errors.isEmpty(), "RestconfError list can't be empty" );
+    public RestconfDocumentedException(List<RestconfError> errors) {
+        this.errors = ImmutableList.copyOf(errors);
+        Preconditions.checkArgument(!this.errors.isEmpty(), "RestconfError list can't be empty");
         status = null;
     }
 
     /**
      * Constructs an instance with an HTTP status and no error information.
      *
-     * @param status the HTTP status.
+     * @param status
+     *            the HTTP status.
      */
-    public RestconfDocumentedException( Status status ) {
-        Preconditions.checkNotNull( status, "Status can't be null" );
+    public RestconfDocumentedException(Status status) {
+        Preconditions.checkNotNull(status, "Status can't be null");
         errors = ImmutableList.of();
         this.status = status;
     }
 
-    private RestconfDocumentedException( Throwable cause, RestconfError error ) {
-        super( cause );
-        Preconditions.checkNotNull( error, "RestconfError can't be null" );
-        errors = ImmutableList.of( error );
+    private RestconfDocumentedException(Throwable cause, RestconfError error) {
+        super(cause);
+        Preconditions.checkNotNull(error, "RestconfError can't be null");
+        errors = ImmutableList.of(error);
         status = null;
     }
 
@@ -110,7 +113,6 @@ public class RestconfDocumentedException extends WebApplicationException {
         return status;
     }
 
-
     @Override
     public String getMessage() {
         return "errors: " + errors + (status != null ? ", status: " + status : "");
index cc279cbd58e68cfc98634364a30002051f698441..ed20bd01a5047e4d746858ff4adde4fe7de0c701 100644 (file)
@@ -1,23 +1,23 @@
 /*
-* Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*/
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.sal.restconf.impl;
 
+import com.google.common.base.Preconditions;
 import java.io.PrintWriter;
 import java.io.StringWriter;
-
 import org.opendaylight.yangtools.yang.common.RpcError;
 
-import com.google.common.base.Preconditions;
-
 /**
  * Encapsulates a restconf error as defined in the ietf restconf draft.
  *
- * <br><br><b>Note:</b> Enumerations defined within are provided by the ietf restconf draft.
+ * <br>
+ * <br>
+ * <b>Note:</b> Enumerations defined within are provided by the ietf restconf draft.
  *
  * @author Devin Avery
  * @see {@link https://tools.ietf.org/html/draft-bierman-netconf-restconf-02}
@@ -38,37 +38,35 @@ public class RestconfError {
             return name().toLowerCase();
         }
 
-        public static ErrorType valueOfCaseInsensitive( String value )
-        {
+        public static ErrorType valueOfCaseInsensitive(String value) {
             try {
-                return ErrorType.valueOf( ErrorType.class, value.toUpperCase() );
-            }
-            catch( IllegalArgumentException e ) {
+                return ErrorType.valueOf(ErrorType.class, value.toUpperCase());
+            } catch (IllegalArgumentException e) {
                 return APPLICATION;
             }
         }
     }
 
     public static enum ErrorTag {
-        IN_USE( "in-use", 409 /*Conflict*/ ),
-        INVALID_VALUE( "invalid-value", 400 /*Bad Request*/ ),
-        TOO_BIG( "too-big", 413 /*Request Entity Too Large*/ ),
-        MISSING_ATTRIBUTE( "missing-attribute", 400 /*Bad Request*/ ),
-        BAD_ATTRIBUTE( "bad-attribute", 400 /*Bad Request*/ ),
-        UNKNOWN_ATTRIBUTE( "unknown-attribute", 400 /*Bad Request*/ ),
-        BAD_ELEMENT( "bad-element", 400 /*Bad Request*/ ),
-        UNKNOWN_ELEMENT( "unknown-element", 400 /*Bad Request*/ ),
-        UNKNOWN_NAMESPACE( "unknown-namespace", 400 /*Bad Request*/ ),
-        ACCESS_DENIED( "access-denied", 403 /*Forbidden*/ ),
-        LOCK_DENIED( "lock-denied", 409 /*Conflict*/ ),
-        RESOURCE_DENIED( "resource-denied", 409 /*Conflict*/ ),
-        ROLLBACK_FAILED( "rollback-failed", 500 /*INTERNAL_SERVER_ERROR*/ ),
-        DATA_EXISTS( "data-exists", 409 /*Conflict*/ ),
-        DATA_MISSING( "data-missing", 409 /*Conflict*/ ),
-        OPERATION_NOT_SUPPORTED( "operation-not-supported", 501 /*Not Implemented*/ ),
-        OPERATION_FAILED( "operation-failed", 500 /*INTERNAL_SERVER_ERROR*/ ),
-        PARTIAL_OPERATION( "partial-operation", 500 /*INTERNAL_SERVER_ERROR*/ ),
-        MALFORMED_MESSAGE( "malformed-message", 400 /*Bad Request*/ );
+        IN_USE("in-use", 409 /* Conflict */),
+        INVALID_VALUE("invalid-value", 400 /* Bad Request */),
+        TOO_BIG("too-big", 413 /* Request Entity Too Large */),
+        MISSING_ATTRIBUTE("missing-attribute", 400 /* Bad Request */),
+        BAD_ATTRIBUTE("bad-attribute", 400 /* Bad Request */),
+        UNKNOWN_ATTRIBUTE("unknown-attribute", 400 /* Bad Request */),
+        BAD_ELEMENT("bad-element", 400 /* Bad Request */),
+        UNKNOWN_ELEMENT("unknown-element", 400 /* Bad Request */),
+        UNKNOWN_NAMESPACE("unknown-namespace", 400 /* Bad Request */),
+        ACCESS_DENIED("access-denied", 403 /* Forbidden */),
+        LOCK_DENIED("lock-denied", 409 /* Conflict */),
+        RESOURCE_DENIED("resource-denied", 409 /* Conflict */),
+        ROLLBACK_FAILED("rollback-failed", 500 /* INTERNAL_SERVER_ERROR */),
+        DATA_EXISTS("data-exists", 409 /* Conflict */),
+        DATA_MISSING("data-missing", 409 /* Conflict */),
+        OPERATION_NOT_SUPPORTED("operation-not-supported", 501 /* Not Implemented */),
+        OPERATION_FAILED("operation-failed", 500 /* INTERNAL_SERVER_ERROR */),
+        PARTIAL_OPERATION("partial-operation", 500 /* INTERNAL_SERVER_ERROR */),
+        MALFORMED_MESSAGE("malformed-message", 400 /* Bad Request */);
 
         private final String tagValue;
         private final int statusCode;
@@ -82,12 +80,10 @@ public class RestconfError {
             return this.tagValue.toLowerCase();
         }
 
-        public static ErrorTag valueOfCaseInsensitive( String value )
-        {
+        public static ErrorTag valueOfCaseInsensitive(String value) {
             try {
-                return ErrorTag.valueOf( ErrorTag.class, value.toUpperCase().replaceAll( "-","_" ) );
-            }
-            catch( IllegalArgumentException e ) {
+                return ErrorTag.valueOf(ErrorTag.class, value.toUpperCase().replaceAll("-", "_"));
+            } catch (IllegalArgumentException e) {
                 return OPERATION_FAILED;
             }
         }
@@ -102,53 +98,63 @@ public class RestconfError {
     private final String errorInfo;
     private final String errorAppTag;
     private final String errorMessage;
-    //TODO: Add in the error-path concept as defined in the ietf draft.
 
-    static String toErrorInfo( Throwable cause ) {
+    // TODO: Add in the error-path concept as defined in the ietf draft.
+
+    static String toErrorInfo(Throwable cause) {
         StringWriter writer = new StringWriter();
-        cause.printStackTrace( new PrintWriter( writer ) );
+        cause.printStackTrace(new PrintWriter(writer));
         return writer.toString();
     }
 
     /**
      * Constructs a RestConfError
      *
-     * @param errorType The enumerated type indicating the layer where the error occurred.
-     * @param errorTag The enumerated tag representing a more specific error cause.
-     * @param errorMessage A string which provides a plain text string describing the error.
+     * @param errorType
+     *            The enumerated type indicating the layer where the error occurred.
+     * @param errorTag
+     *            The enumerated tag representing a more specific error cause.
+     * @param errorMessage
+     *            A string which provides a plain text string describing the error.
      */
     public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage) {
-        this( errorType, errorTag, errorMessage, null );
+        this(errorType, errorTag, errorMessage, null);
     }
 
     /**
      * Constructs a RestConfError object.
      *
-     * @param errorType The enumerated type indicating the layer where the error occurred.
-     * @param errorTag The enumerated tag representing a more specific error cause.
-     * @param errorMessage A string which provides a plain text string describing the error.
-     * @param errorAppTag A string which represents an application-specific error tag that further
-     *                    specifies the error cause.
+     * @param errorType
+     *            The enumerated type indicating the layer where the error occurred.
+     * @param errorTag
+     *            The enumerated tag representing a more specific error cause.
+     * @param errorMessage
+     *            A string which provides a plain text string describing the error.
+     * @param errorAppTag
+     *            A string which represents an application-specific error tag that further specifies the error cause.
      */
-    public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage,
-                         String errorAppTag) {
-        this( errorType, errorTag, errorMessage, errorAppTag, null );
+    public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage, String errorAppTag) {
+        this(errorType, errorTag, errorMessage, errorAppTag, null);
     }
 
     /**
      * Constructs a RestConfError object.
      *
-     * @param errorType The enumerated type indicating the layer where the error occurred.
-     * @param errorTag The enumerated tag representing a more specific error cause.
-     * @param errorMessage A string which provides a plain text string describing the error.
-     * @param errorAppTag A string which represents an application-specific error tag that further
-     *                    specifies the error cause.
-     * @param errorInfo A string, <b>formatted as XML</b>, which contains additional error information.
+     * @param errorType
+     *            The enumerated type indicating the layer where the error occurred.
+     * @param errorTag
+     *            The enumerated tag representing a more specific error cause.
+     * @param errorMessage
+     *            A string which provides a plain text string describing the error.
+     * @param errorAppTag
+     *            A string which represents an application-specific error tag that further specifies the error cause.
+     * @param errorInfo
+     *            A string, <b>formatted as XML</b>, which contains additional error information.
      */
-    public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage,
-                         String errorAppTag, String errorInfo) {
-        Preconditions.checkNotNull( errorType, "Error type is required for RestConfError" );
-        Preconditions.checkNotNull( errorTag, "Error tag is required for RestConfError");
+    public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage, String errorAppTag,
+            String errorInfo) {
+        Preconditions.checkNotNull(errorType, "Error type is required for RestConfError");
+        Preconditions.checkNotNull(errorTag, "Error tag is required for RestConfError");
         this.errorType = errorType;
         this.errorTag = errorTag;
         this.errorMessage = errorMessage;
@@ -159,28 +165,25 @@ public class RestconfError {
     /**
      * Constructs a RestConfError object from an RpcError.
      */
-    public RestconfError( RpcError rpcError ) {
+    public RestconfError(RpcError rpcError) {
 
-        this.errorType = rpcError.getErrorType() == null ? ErrorType.APPLICATION :
-                               ErrorType.valueOfCaseInsensitive( rpcError.getErrorType().name() );
+        this.errorType = rpcError.getErrorType() == null ? ErrorType.APPLICATION : ErrorType
+                .valueOfCaseInsensitive(rpcError.getErrorType().name());
 
-        this.errorTag = rpcError.getTag() == null ? ErrorTag.OPERATION_FAILED :
-                                    ErrorTag.valueOfCaseInsensitive( rpcError.getTag().toString() );
+        this.errorTag = rpcError.getTag() == null ? ErrorTag.OPERATION_FAILED : ErrorTag
+                .valueOfCaseInsensitive(rpcError.getTag().toString());
 
         this.errorMessage = rpcError.getMessage();
         this.errorAppTag = rpcError.getApplicationTag();
 
         String errorInfo = null;
-        if( rpcError.getInfo() == null ) {
-            if( rpcError.getCause() != null ) {
-                errorInfo = toErrorInfo( rpcError.getCause() );
+        if (rpcError.getInfo() == null) {
+            if (rpcError.getCause() != null) {
+                errorInfo = toErrorInfo(rpcError.getCause());
+            } else if (rpcError.getSeverity() != null) {
+                errorInfo = "<severity>" + rpcError.getSeverity().toString().toLowerCase() + "</severity>";
             }
-            else if( rpcError.getSeverity() != null ) {
-                errorInfo = "<severity>" + rpcError.getSeverity().toString().toLowerCase() +
-                            "</severity>";
-            }
-        }
-        else {
+        } else {
             errorInfo = rpcError.getInfo();
         }
 
@@ -209,8 +212,7 @@ public class RestconfError {
 
     @Override
     public String toString() {
-        return "error-type: " + errorType.getErrorTypeTag()
-                + ", error-tag: " + errorTag.getTagValue() + ", "
+        return "error-type: " + errorType.getErrorTypeTag() + ", error-tag: " + errorTag.getTagValue() + ", "
                 + (errorAppTag != null ? "error-app-tag: " + errorAppTag + ", " : "")
                 + (errorMessage != null ? "error-message: " + errorMessage : "")
                 + (errorInfo != null ? "error-info: " + errorInfo + ", " : "") + "]";
index c8440c0a1692066660b0a6b2025abee6476c28a6..bb7547d3302f1d172c1271416c08e0895ac46398 100644 (file)
@@ -52,6 +52,8 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
 import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
@@ -77,10 +79,11 @@ import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder
 
 public class RestconfImpl implements RestconfService {
     private enum UriParameters {
-        PRETTY_PRINT( "prettyPrint"),
-        DEPTH( "depth");
+        PRETTY_PRINT("prettyPrint"),
+        DEPTH("depth");
 
         private String uriParameterName;
+
         UriParameters(String uriParameterName) {
             this.uriParameterName = uriParameterName;
         }
@@ -97,7 +100,7 @@ public class RestconfImpl implements RestconfService {
 
     private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
 
-    private final static SimpleDateFormat REVISION_FORMAT =  new SimpleDateFormat("yyyy-MM-dd");
+    private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
 
     private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
 
@@ -127,8 +130,8 @@ public class RestconfImpl implements RestconfService {
         final Module restconfModule = this.getRestconfModule();
 
         final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
-        final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
+        final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
 
         Set<Module> allModules = this.controllerContext.getAllModules();
         for (final Module module : allModules) {
@@ -136,11 +139,11 @@ public class RestconfImpl implements RestconfService {
             modulesAsData.add(moduleCompositeNode);
         }
 
-        final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
+        final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
         QName qName = modulesSchemaNode.getQName();
         final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
-        return new StructuredData(modulesNode, modulesSchemaNode, null,parsePrettyPrintParameter( uriInfo ));
+        return new StructuredData(modulesNode, modulesSchemaNode, null, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
@@ -149,122 +152,115 @@ public class RestconfImpl implements RestconfService {
 
         final List<Node<?>> streamsAsData = new ArrayList<Node<?>>();
         Module restconfModule = this.getRestconfModule();
-        final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
+        final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
         for (final String streamName : availableStreams) {
             streamsAsData.add(this.toStreamCompositeNode(streamName, streamSchemaNode));
         }
 
-        final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+        final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
         QName qName = streamsSchemaNode.getQName();
         final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData);
-        return new StructuredData(streamsNode, streamsSchemaNode, null,parsePrettyPrintParameter( uriInfo ));
+        return new StructuredData(streamsNode, streamsSchemaNode, null, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
-    public StructuredData getModules(final String identifier,final UriInfo uriInfo) {
+    public StructuredData getModules(final String identifier, final UriInfo uriInfo) {
         Set<Module> modules = null;
         MountInstance mountPoint = null;
         if (identifier.contains(ControllerContext.MOUNT)) {
-            InstanceIdWithSchemaNode mountPointIdentifier =
-                    this.controllerContext.toMountPointIdentifier(identifier);
+            InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
             mountPoint = mountPointIdentifier.getMountPoint();
             modules = this.controllerContext.getAllModules(mountPoint);
-        }
-        else {
+        } else {
             throw new RestconfDocumentedException(
-                    "URI has bad format. If modules behind mount point should be showed, URI has to end with " +
-                            ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                    "URI has bad format. If modules behind mount point should be showed, URI has to end with "
+                            + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
         Module restconfModule = this.getRestconfModule();
-        final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
+        final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
 
         for (final Module module : modules) {
             modulesAsData.add(this.toModuleCompositeNode(module, moduleSchemaNode));
         }
 
-        final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
+        final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
         QName qName = modulesSchemaNode.getQName();
         final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
-        return new StructuredData(modulesNode, modulesSchemaNode, mountPoint,parsePrettyPrintParameter( uriInfo ));
+        return new StructuredData(modulesNode, modulesSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
-    public StructuredData getModule(final String identifier,final UriInfo uriInfo) {
+    public StructuredData getModule(final String identifier, final UriInfo uriInfo) {
         final QName moduleNameAndRevision = this.getModuleNameAndRevision(identifier);
         Module module = null;
         MountInstance mountPoint = null;
         if (identifier.contains(ControllerContext.MOUNT)) {
-            InstanceIdWithSchemaNode mountPointIdentifier =
-                    this.controllerContext.toMountPointIdentifier(identifier);
+            InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
             mountPoint = mountPointIdentifier.getMountPoint();
             module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
-        }
-        else {
+        } else {
             module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
         }
 
         if (module == null) {
-            throw new RestconfDocumentedException(
-                    "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '" +
-                            moduleNameAndRevision.getRevision() + "' was not found.",
-                            ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+            throw new RestconfDocumentedException("Module with name '" + moduleNameAndRevision.getLocalName()
+                    + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.",
+                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
         }
 
         Module restconfModule = this.getRestconfModule();
-        final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
+        final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
         final CompositeNode moduleNode = this.toModuleCompositeNode(module, moduleSchemaNode);
-        return new StructuredData(moduleNode, moduleSchemaNode, mountPoint,parsePrettyPrintParameter( uriInfo ));
+        return new StructuredData(moduleNode, moduleSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
     public StructuredData getOperations(final UriInfo uriInfo) {
         Set<Module> allModules = this.controllerContext.getAllModules();
-        return this.operationsFromModulesToStructuredData(allModules, null,parsePrettyPrintParameter(uriInfo));
+        return this.operationsFromModulesToStructuredData(allModules, null, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
-    public StructuredData getOperations(final String identifier,final UriInfo uriInfo) {
+    public StructuredData getOperations(final String identifier, final UriInfo uriInfo) {
         Set<Module> modules = null;
         MountInstance mountPoint = null;
         if (identifier.contains(ControllerContext.MOUNT)) {
-            InstanceIdWithSchemaNode mountPointIdentifier =
-                    this.controllerContext.toMountPointIdentifier(identifier);
+            InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
             mountPoint = mountPointIdentifier.getMountPoint();
             modules = this.controllerContext.getAllModules(mountPoint);
-        }
-        else {
+        } else {
             throw new RestconfDocumentedException(
-                    "URI has bad format. If operations behind mount point should be showed, URI has to end with " +
-                            ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                    "URI has bad format. If operations behind mount point should be showed, URI has to end with "
+                            + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
-        return this.operationsFromModulesToStructuredData(modules, mountPoint,parsePrettyPrintParameter(uriInfo));
+        return this.operationsFromModulesToStructuredData(modules, mountPoint, parsePrettyPrintParameter(uriInfo));
     }
 
     private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
-                                                                 final MountInstance mountPoint,boolean prettyPrint) {
+            final MountInstance mountPoint, boolean prettyPrint) {
         final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
         Module restconfModule = this.getRestconfModule();
         final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
                 restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
         QName qName = operationsSchemaNode.getQName();
         SchemaPath path = operationsSchemaNode.getPath();
-        ContainerSchemaNodeBuilder containerSchemaNodeBuilder =
-                new ContainerSchemaNodeBuilder(Draft02.RestConfModule.NAME, 0, qName, path);
+        ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder(
+                Draft02.RestConfModule.NAME, 0, qName, path);
         final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
         for (final Module module : modules) {
             Set<RpcDefinition> rpcs = module.getRpcs();
             for (final RpcDefinition rpc : rpcs) {
                 QName rpcQName = rpc.getQName();
-                SimpleNode<Object> immutableSimpleNode =
-                        NodeFactory.<Object>createImmutableSimpleNode(rpcQName, null, null);
+                SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
+                        null);
                 operationsAsData.add(immutableSimpleNode);
 
                 String name = module.getName();
@@ -279,18 +275,16 @@ public class RestconfImpl implements RestconfService {
             }
         }
 
-        final CompositeNode operationsNode =
-                NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
+        final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
         ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
-        return new StructuredData(operationsNode, schemaNode, mountPoint,prettyPrint);
+        return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint);
     }
 
     private Module getRestconfModule() {
         Module restconfModule = controllerContext.getRestconfModule();
         if (restconfModule == null) {
-            throw new RestconfDocumentedException(
-                    "ietf-restconf module was not found.", ErrorType.APPLICATION,
-                    ErrorTag.OPERATION_NOT_SUPPORTED );
+            throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
+                    ErrorTag.OPERATION_NOT_SUPPORTED);
         }
 
         return restconfModule;
@@ -301,95 +295,90 @@ public class RestconfImpl implements RestconfService {
         String moduleNameAndRevision = "";
         if (mountIndex >= 0) {
             moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
-        }
-        else {
+        } else {
             moduleNameAndRevision = identifier;
         }
 
         Splitter splitter = Splitter.on("/").omitEmptyStrings();
         Iterable<String> split = splitter.split(moduleNameAndRevision);
-        final List<String> pathArgs = Lists.<String>newArrayList(split);
+        final List<String> pathArgs = Lists.<String> newArrayList(split);
         if (pathArgs.size() < 2) {
             throw new RestconfDocumentedException(
-                    "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                    "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
+                    ErrorTag.INVALID_VALUE);
         }
 
         try {
-            final String moduleName = pathArgs.get( 0 );
+            final String moduleName = pathArgs.get(0);
             String revision = pathArgs.get(1);
             final Date moduleRevision = REVISION_FORMAT.parse(revision);
             return QName.create(null, moduleRevision, moduleName);
-        }
-        catch (ParseException e) {
-            throw new RestconfDocumentedException(
-                    "URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        } catch (ParseException e) {
+            throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
     }
 
     private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
         final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
-        List<DataSchemaNode> instanceDataChildrenByName =
-                this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) streamSchemaNode),
-                        "name");
+        List<DataSchemaNode> instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
+                ((DataNodeContainer) streamSchemaNode), "name");
         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(nameSchemaNode.getQName(), null,
-                streamName));
+        streamNodeValues
+                .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
                 ((DataNodeContainer) streamSchemaNode), "description");
         final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
+        streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
                 "DESCRIPTION_PLACEHOLDER"));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
                 ((DataNodeContainer) streamSchemaNode), "replay-support");
         final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<Boolean>createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
+        streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
                 Boolean.valueOf(true)));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
                 ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
         final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
+        streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
                 null, ""));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
                 ((DataNodeContainer) streamSchemaNode), "events");
         final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(eventsSchemaNode.getQName(),
-                null, ""));
+        streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
 
         return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
     }
 
     private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
         final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
-        List<DataSchemaNode> instanceDataChildrenByName =
-                this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) moduleSchemaNode), "name");
+        List<DataSchemaNode> instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
+                ((DataNodeContainer) moduleSchemaNode), "name");
         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(nameSchemaNode.getQName(),
-                null, module.getName()));
+        moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null,
+                module.getName()));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
                 ((DataNodeContainer) moduleSchemaNode), "revision");
         final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
         Date _revision = module.getRevision();
-        moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
+        moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
                 REVISION_FORMAT.format(_revision)));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
                 ((DataNodeContainer) moduleSchemaNode), "namespace");
         final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
+        moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
                 module.getNamespace().toString()));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
                 ((DataNodeContainer) moduleSchemaNode), "feature");
         final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
         for (final FeatureDefinition feature : module.getFeatures()) {
-            moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(featureSchemaNode.getQName(), null,
+            moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
                     feature.getQName().getLocalName()));
         }
 
@@ -402,53 +391,45 @@ public class RestconfImpl implements RestconfService {
     }
 
     @Override
-    public StructuredData invokeRpc(final String identifier, final CompositeNode payload,final UriInfo uriInfo) {
+    public StructuredData invokeRpc(final String identifier, final CompositeNode payload, final UriInfo uriInfo) {
         final RpcExecutor rpc = this.resolveIdentifierInInvokeRpc(identifier);
         QName rpcName = rpc.getRpcDefinition().getQName();
         URI rpcNamespace = rpcName.getNamespace();
-        if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE) &&
-                Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
-            return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(),parsePrettyPrintParameter(uriInfo));
+        if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE)
+                && Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
+            return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(), parsePrettyPrintParameter(uriInfo));
         }
 
-        validateInput( rpc.getRpcDefinition().getInput(), payload );
+        validateInput(rpc.getRpcDefinition().getInput(), payload);
 
-        return callRpc(rpc, payload,parsePrettyPrintParameter(uriInfo));
+        return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo));
     }
 
     private void validateInput(final DataSchemaNode inputSchema, final CompositeNode payload) {
-        if( inputSchema != null && payload == null )
-        {
-            //expected a non null payload
-            throw new RestconfDocumentedException( "Input is required.",
-                    ErrorType.PROTOCOL,
-                    ErrorTag.MALFORMED_MESSAGE );
-        }
-        else if( inputSchema == null && payload != null )
-        {
-            //did not expect any input
-            throw new RestconfDocumentedException( "No input expected.",
-                    ErrorType.PROTOCOL,
-                    ErrorTag.MALFORMED_MESSAGE );
-        }
-        //else
-        //{
-        //TODO: Validate "mandatory" and "config" values here??? Or should those be
+        if (inputSchema != null && payload == null) {
+            // expected a non null payload
+            throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
+        } else if (inputSchema == null && payload != null) {
+            // did not expect any input
+            throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
+        }
+        // else
+        // {
+        // TODO: Validate "mandatory" and "config" values here??? Or should those be
         // validate in a more central location inside MD-SAL core.
-        //}
+        // }
     }
 
-    private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload,
-                                                          final RpcDefinition rpc,final boolean prettyPrint) {
+    private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, final RpcDefinition rpc,
+            final boolean prettyPrint) {
         final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
-        final SimpleNode<? extends Object> pathNode = value == null ? null :
-            value.getFirstSimpleByName( QName.create(rpc.getQName(), "path") );
+        final SimpleNode<? extends Object> pathNode = value == null ? null : value.getFirstSimpleByName(QName.create(
+                rpc.getQName(), "path"));
         final Object pathValue = pathNode == null ? null : pathNode.getValue();
 
         if (!(pathValue instanceof InstanceIdentifier)) {
-            throw new RestconfDocumentedException(
-                    "Instance identifier was not normalized correctly.",
-                    ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED );
+            throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
+                    ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
         }
 
         final InstanceIdentifier pathIdentifier = ((InstanceIdentifier) pathValue);
@@ -461,31 +442,30 @@ public class RestconfImpl implements RestconfService {
         if (Strings.isNullOrEmpty(streamName)) {
             throw new RestconfDocumentedException(
                     "Path is empty or contains data node which is not Container or List build-in type.",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
-        final SimpleNode<String> streamNameNode = NodeFactory.<String>createImmutableSimpleNode(
+        final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
                 QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
         final List<Node<?>> output = new ArrayList<Node<?>>();
         output.add(streamNameNode);
 
-        final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(
-                rpc.getOutput().getQName(), null, output, null, null);
+        final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(),
+                null, output, null, null);
 
         if (!Notificator.existListenerFor(pathIdentifier)) {
             Notificator.createListener(pathIdentifier, streamName);
         }
 
-        return new StructuredData(responseData, rpc.getOutput(), null,prettyPrint);
+        return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
     }
 
     @Override
     public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
         if (StringUtils.isNotBlank(noPayload)) {
-            throw new RestconfDocumentedException(
-                    "Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
-        return invokeRpc( identifier, (CompositeNode)null,uriInfo);
+        return invokeRpc(identifier, (CompositeNode) null, uriInfo);
     }
 
     private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
@@ -493,8 +473,7 @@ public class RestconfImpl implements RestconfService {
         MountInstance mountPoint = null;
         if (identifier.contains(ControllerContext.MOUNT)) {
             // mounted RPC call - look up mount instance.
-            InstanceIdWithSchemaNode mountPointId = controllerContext
-                    .toMountPointIdentifier(identifier);
+            InstanceIdWithSchemaNode mountPointId = controllerContext.toMountPointIdentifier(identifier);
             mountPoint = mountPointId.getMountPoint();
 
             int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
@@ -503,12 +482,9 @@ public class RestconfImpl implements RestconfService {
             identifierEncoded = remoteRpcName;
 
         } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
-            final String slashErrorMsg = String
-                    .format("Identifier %n%s%ncan\'t contain slash "
-                            + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
-                            identifier);
-            throw new RestconfDocumentedException(
-                    slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
+                    + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
+            throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         } else {
             identifierEncoded = identifier;
         }
@@ -517,8 +493,7 @@ public class RestconfImpl implements RestconfService {
         RpcDefinition rpc = controllerContext.getRpcDefinition(identifierDecoded);
 
         if (rpc == null) {
-            throw new RestconfDocumentedException(
-                    "RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT );
+            throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
         }
 
         if (mountPoint == null) {
@@ -529,10 +504,9 @@ public class RestconfImpl implements RestconfService {
 
     }
 
-    private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload,boolean prettyPrint) {
+    private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, boolean prettyPrint) {
         if (rpcExecutor == null) {
-            throw new RestconfDocumentedException(
-                    "RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT );
+            throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
         }
 
         CompositeNode rpcRequest = null;
@@ -555,30 +529,29 @@ public class RestconfImpl implements RestconfService {
             return null;
         }
 
-        if( rpc.getOutput() == null )
-        {
-            return null; //no output, nothing to send back.
+        if (rpc.getOutput() == null) {
+            return null; // no output, nothing to send back.
         }
 
-        return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null,prettyPrint);
+        return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
     }
 
     private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
         if (rpcResult.isSuccessful() == false) {
 
             Collection<RpcError> rpcErrors = rpcResult.getErrors();
-            if( rpcErrors == null || rpcErrors.isEmpty() ) {
+            if (rpcErrors == null || rpcErrors.isEmpty()) {
                 throw new RestconfDocumentedException(
-                        "The operation was not successful and there were no RPC errors returned",
-                        ErrorType.RPC, ErrorTag.OPERATION_FAILED );
+                        "The operation was not successful and there were no RPC errors returned", ErrorType.RPC,
+                        ErrorTag.OPERATION_FAILED);
             }
 
             List<RestconfError> errorList = Lists.newArrayList();
-            for( RpcError rpcError: rpcErrors ) {
-                errorList.add( new RestconfError( rpcError ) );
+            for (RpcError rpcError : rpcErrors) {
+                errorList.add(new RestconfError(rpcError));
             }
 
-            throw new RestconfDocumentedException( errorList );
+            throw new RestconfDocumentedException(errorList);
         }
     }
 
@@ -589,58 +562,54 @@ public class RestconfImpl implements RestconfService {
         MountInstance mountPoint = iiWithData.getMountPoint();
         if (mountPoint != null) {
             data = broker.readConfigurationDataBehindMountPoint(mountPoint, iiWithData.getInstanceIdentifier());
-        }
-        else {
+        } else {
             data = broker.readConfigurationData(iiWithData.getInstanceIdentifier());
         }
 
-        data = pruneDataAtDepth( data, parseDepthParameter( uriInfo ) );
-        boolean prettyPrintMode = parsePrettyPrintParameter( uriInfo );
-        return new StructuredData(data, iiWithData.getSchemaNode(), iiWithData.getMountPoint(),prettyPrintMode);
+        data = pruneDataAtDepth(data, parseDepthParameter(uriInfo));
+        boolean prettyPrintMode = parsePrettyPrintParameter(uriInfo);
+        return new StructuredData(data, iiWithData.getSchemaNode(), iiWithData.getMountPoint(), prettyPrintMode);
     }
 
     @SuppressWarnings("unchecked")
-    private <T extends Node<?>> T pruneDataAtDepth( final T node, final Integer depth ) {
-        if( depth == null ) {
+    private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
+        if (depth == null) {
             return node;
         }
 
-        if( node instanceof CompositeNode ) {
+        if (node instanceof CompositeNode) {
             ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
-            if( depth > 1 ) {
-                for( Node<?> childNode: ((CompositeNode)node).getValue() ) {
-                    newChildNodes.add( pruneDataAtDepth( childNode, depth - 1 ) );
+            if (depth > 1) {
+                for (Node<?> childNode : ((CompositeNode) node).getValue()) {
+                    newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
                 }
             }
 
-            return (T) ImmutableCompositeNode.create( node.getNodeType(), newChildNodes.build() );
-        }
-        else { // SimpleNode
+            return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
+        } else { // SimpleNode
             return node;
         }
     }
 
-    private Integer parseDepthParameter( final UriInfo info ) {
-        String param = info.getQueryParameters( false ).getFirst( UriParameters.DEPTH.toString() );
-        if( Strings.isNullOrEmpty( param ) || "unbounded".equals( param ) ) {
+    private Integer parseDepthParameter(final UriInfo info) {
+        String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
+        if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
             return null;
         }
 
         try {
-            Integer depth = Integer.valueOf( param );
-            if( depth < 1 ) {
-                throw new RestconfDocumentedException( new RestconfError(
-                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, "Invalid depth parameter: " + depth,
-                        null, "The depth parameter must be an integer > 1 or \"unbounded\"" ) );
+            Integer depth = Integer.valueOf(param);
+            if (depth < 1) {
+                throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
+                        "Invalid depth parameter: " + depth, null,
+                        "The depth parameter must be an integer > 1 or \"unbounded\""));
             }
 
             return depth;
-        }
-        catch( NumberFormatException e ) {
-            throw new RestconfDocumentedException( new RestconfError(
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
-                    "Invalid depth parameter: " + e.getMessage(),
-                    null, "The depth parameter must be an integer > 1 or \"unbounded\"" ) );
+        } catch (NumberFormatException e) {
+            throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
+                    "Invalid depth parameter: " + e.getMessage(), null,
+                    "The depth parameter must be an integer > 1 or \"unbounded\""));
         }
     }
 
@@ -651,14 +620,13 @@ public class RestconfImpl implements RestconfService {
         MountInstance mountPoint = iiWithData.getMountPoint();
         if (mountPoint != null) {
             data = broker.readOperationalDataBehindMountPoint(mountPoint, iiWithData.getInstanceIdentifier());
-        }
-        else {
+        } else {
             data = broker.readOperationalData(iiWithData.getInstanceIdentifier());
         }
 
-        data = pruneDataAtDepth( data, parseDepthParameter( info ) );
-        boolean prettyPrintMode = parsePrettyPrintParameter( info );
-        return new StructuredData(data, iiWithData.getSchemaNode(), mountPoint,prettyPrintMode);
+        data = pruneDataAtDepth(data, parseDepthParameter(info));
+        boolean prettyPrintMode = parsePrettyPrintParameter(info);
+        return new StructuredData(data, iiWithData.getSchemaNode(), mountPoint, prettyPrintMode);
     }
 
     private boolean parsePrettyPrintParameter(UriInfo info) {
@@ -674,40 +642,83 @@ public class RestconfImpl implements RestconfService {
 
         MountInstance mountPoint = iiWithData.getMountPoint();
         final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint);
+        validateListKeysEqualityInPayloadAndUri(iiWithData, payload);
         RpcResult<TransactionStatus> status = null;
 
         try {
             if (mountPoint != null) {
-                status = broker.commitConfigurationDataPutBehindMountPoint(
-                        mountPoint, iiWithData.getInstanceIdentifier(), value).get();
+                status = broker.commitConfigurationDataPutBehindMountPoint(mountPoint,
+                        iiWithData.getInstanceIdentifier(), value).get();
             } else {
                 status = broker.commitConfigurationDataPut(iiWithData.getInstanceIdentifier(), value).get();
             }
-        }
-        catch( Exception e ) {
-            throw new RestconfDocumentedException( "Error updating data", e );
+        } catch (Exception e) {
+            throw new RestconfDocumentedException("Error updating data", e);
         }
 
-        if( status.getResult() == TransactionStatus.COMMITED ) {
+        if (status.getResult() == TransactionStatus.COMMITED) {
             return Response.status(Status.OK).build();
         }
 
         return Response.status(Status.INTERNAL_SERVER_ERROR).build();
     }
 
+    /**
+     * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
+     *
+     * @throws RestconfDocumentedException
+     *             if key values or key count in payload and URI isn't equal
+     *
+     */
+    private void validateListKeysEqualityInPayloadAndUri(final InstanceIdWithSchemaNode iiWithData,
+            final CompositeNode payload) {
+        if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
+            final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
+            final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
+            if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
+                final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
+                        .getKeyValues();
+                isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
+            }
+        }
+    }
+
+    private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
+            final List<QName> keyDefinitions) {
+        for (QName keyDefinition : keyDefinitions) {
+            final Object uriKeyValue = uriKeyValues.get(keyDefinition);
+            // should be caught during parsing URI to InstanceIdentifier
+            if (uriKeyValue == null) {
+                throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
+                        ErrorTag.DATA_MISSING);
+            }
+            final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
+            if (payloadKeyValues.isEmpty()) {
+                throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
+                        + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
+            }
+
+            Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
+            if (!uriKeyValue.equals(payloadKeyValue)) {
+                throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
+                        + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
+                        + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
+                        ErrorTag.INVALID_VALUE);
+            }
+        }
+    }
+
     @Override
     public Response createConfigurationData(final String identifier, final CompositeNode payload) {
-        if( payload == null ) {
-            throw new RestconfDocumentedException( "Input is required.",
-                    ErrorType.PROTOCOL,
-                    ErrorTag.MALFORMED_MESSAGE );
+        if (payload == null) {
+            throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
         }
 
         URI payloadNS = this.namespace(payload);
         if (payloadNS == null) {
             throw new RestconfDocumentedException(
                     "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
-                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE );
+                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
         }
 
         InstanceIdWithSchemaNode iiWithData = null;
@@ -716,27 +727,24 @@ public class RestconfImpl implements RestconfService {
             // payload represents mount point data and URI represents path to the mount point
 
             if (this.endsWithMountPoint(identifier)) {
-                throw new RestconfDocumentedException(
-                        "URI has bad format. URI should be without \"" + ControllerContext.MOUNT +
-                        "\" for POST operation.",
-                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                throw new RestconfDocumentedException("URI has bad format. URI should be without \""
+                        + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL,
+                        ErrorTag.INVALID_VALUE);
             }
 
             final String completeIdentifier = this.addMountPointIdentifier(identifier);
             iiWithData = this.controllerContext.toInstanceIdentifier(completeIdentifier);
 
             value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
-        }
-        else {
-            final InstanceIdWithSchemaNode incompleteInstIdWithData =
-                    this.controllerContext.toInstanceIdentifier(identifier);
+        } else {
+            final InstanceIdWithSchemaNode incompleteInstIdWithData = this.controllerContext
+                    .toInstanceIdentifier(identifier);
             final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
             MountInstance mountPoint = incompleteInstIdWithData.getMountPoint();
             final Module module = this.findModule(mountPoint, payload);
             if (module == null) {
-                throw new RestconfDocumentedException(
-                        "Module was not found for \"" + payloadNS + "\"",
-                        ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+                throw new RestconfDocumentedException("Module was not found for \"" + payloadNS + "\"",
+                        ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
             }
 
             String payloadName = this.getName(payload);
@@ -751,26 +759,23 @@ public class RestconfImpl implements RestconfService {
         MountInstance mountPoint = iiWithData.getMountPoint();
         try {
             if (mountPoint != null) {
-                Future<RpcResult<TransactionStatus>> future =
-                        broker.commitConfigurationDataPostBehindMountPoint(
-                                mountPoint, iiWithData.getInstanceIdentifier(), value);
+                Future<RpcResult<TransactionStatus>> future = broker.commitConfigurationDataPostBehindMountPoint(
+                        mountPoint, iiWithData.getInstanceIdentifier(), value);
                 status = future == null ? null : future.get();
-            }
-            else {
-                Future<RpcResult<TransactionStatus>> future =
-                        broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value);
+            } else {
+                Future<RpcResult<TransactionStatus>> future = broker.commitConfigurationDataPost(
+                        iiWithData.getInstanceIdentifier(), value);
                 status = future == null ? null : future.get();
             }
-        }
-        catch( Exception e ) {
-            throw new RestconfDocumentedException( "Error creating data", e );
+        } catch (Exception e) {
+            throw new RestconfDocumentedException("Error creating data", e);
         }
 
         if (status == null) {
             return Response.status(Status.ACCEPTED).build();
         }
 
-        if( status.getResult() == TransactionStatus.COMMITED ) {
+        if (status.getResult() == TransactionStatus.COMMITED) {
             return Response.status(Status.NO_CONTENT).build();
         }
 
@@ -779,29 +784,27 @@ public class RestconfImpl implements RestconfService {
 
     @Override
     public Response createConfigurationData(final CompositeNode payload) {
-        if( payload == null ) {
-            throw new RestconfDocumentedException( "Input is required.",
-                    ErrorType.PROTOCOL,
-                    ErrorTag.MALFORMED_MESSAGE );
+        if (payload == null) {
+            throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
         }
 
         URI payloadNS = this.namespace(payload);
         if (payloadNS == null) {
             throw new RestconfDocumentedException(
                     "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
-                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE );
+                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
         }
 
         final Module module = this.findModule(null, payload);
         if (module == null) {
             throw new RestconfDocumentedException(
                     "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
-                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE );
+                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
         }
 
         String payloadName = this.getName(payload);
-        final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace(
-                module, payloadName, module.getNamespace());
+        final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace(module,
+                payloadName, module.getNamespace());
         final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
         final InstanceIdWithSchemaNode iiWithData = this.addLastIdentifierFromData(null, value, schemaNode);
         RpcResult<TransactionStatus> status = null;
@@ -809,26 +812,23 @@ public class RestconfImpl implements RestconfService {
 
         try {
             if (mountPoint != null) {
-                Future<RpcResult<TransactionStatus>> future =
-                        broker.commitConfigurationDataPostBehindMountPoint(
-                                mountPoint, iiWithData.getInstanceIdentifier(), value);
+                Future<RpcResult<TransactionStatus>> future = broker.commitConfigurationDataPostBehindMountPoint(
+                        mountPoint, iiWithData.getInstanceIdentifier(), value);
                 status = future == null ? null : future.get();
-            }
-            else {
-                Future<RpcResult<TransactionStatus>> future =
-                        broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value);
+            } else {
+                Future<RpcResult<TransactionStatus>> future = broker.commitConfigurationDataPost(
+                        iiWithData.getInstanceIdentifier(), value);
                 status = future == null ? null : future.get();
             }
-        }
-        catch( Exception e ) {
-            throw new RestconfDocumentedException( "Error creating data", e );
+        } catch (Exception e) {
+            throw new RestconfDocumentedException("Error creating data", e);
         }
 
         if (status == null) {
             return Response.status(Status.ACCEPTED).build();
         }
 
-        if( status.getResult() == TransactionStatus.COMMITED ) {
+        if (status.getResult() == TransactionStatus.COMMITED) {
             return Response.status(Status.NO_CONTENT).build();
         }
 
@@ -843,18 +843,16 @@ public class RestconfImpl implements RestconfService {
 
         try {
             if (mountPoint != null) {
-                status = broker.commitConfigurationDataDeleteBehindMountPoint(
-                        mountPoint, iiWithData.getInstanceIdentifier()).get();
-            }
-            else {
+                status = broker.commitConfigurationDataDeleteBehindMountPoint(mountPoint,
+                        iiWithData.getInstanceIdentifier()).get();
+            } else {
                 status = broker.commitConfigurationDataDelete(iiWithData.getInstanceIdentifier()).get();
             }
-        }
-        catch( Exception e ) {
-            throw new RestconfDocumentedException( "Error creating data", e );
+        } catch (Exception e) {
+            throw new RestconfDocumentedException("Error creating data", e);
         }
 
-        if( status.getResult() == TransactionStatus.COMMITED ) {
+        if (status.getResult() == TransactionStatus.COMMITED) {
             return Response.status(Status.OK).build();
         }
 
@@ -865,14 +863,12 @@ public class RestconfImpl implements RestconfService {
     public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
         final String streamName = Notificator.createStreamNameFromUri(identifier);
         if (Strings.isNullOrEmpty(streamName)) {
-            throw new RestconfDocumentedException(
-                    "Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         final ListenerAdapter listener = Notificator.getListenerFor(streamName);
         if (listener == null) {
-            throw new RestconfDocumentedException(
-                    "Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+            throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
         }
 
         broker.registerToListenDataChanges(listener);
@@ -886,26 +882,23 @@ public class RestconfImpl implements RestconfService {
 
     private Module findModule(final MountInstance mountPoint, final CompositeNode data) {
         if (data instanceof CompositeNodeWrapper) {
-            return findModule(mountPoint, (CompositeNodeWrapper)data);
-        }
-        else if (data != null) {
+            return findModule(mountPoint, (CompositeNodeWrapper) data);
+        } else if (data != null) {
             URI namespace = data.getNodeType().getNamespace();
             if (mountPoint != null) {
                 return this.controllerContext.findModuleByNamespace(mountPoint, namespace);
-            }
-            else {
+            } else {
                 return this.controllerContext.findModuleByNamespace(namespace);
             }
-        }
-        else {
-            throw new IllegalArgumentException("Unhandled parameter types: " +
-                    Arrays.<Object>asList(mountPoint, data).toString());
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: "
+                    + Arrays.<Object> asList(mountPoint, data).toString());
         }
     }
 
     private Module findModule(final MountInstance mountPoint, final CompositeNodeWrapper data) {
         URI namespace = data.getNamespace();
-        Preconditions.<URI>checkNotNull(namespace);
+        Preconditions.<URI> checkNotNull(namespace);
 
         Module module = null;
         if (mountPoint != null) {
@@ -913,8 +906,7 @@ public class RestconfImpl implements RestconfService {
             if (module == null) {
                 module = this.controllerContext.findModuleByName(mountPoint, namespace.toString());
             }
-        }
-        else {
+        } else {
             module = this.controllerContext.findModuleByNamespace(namespace);
             if (module == null) {
                 module = this.controllerContext.findModuleByName(namespace.toString());
@@ -924,8 +916,7 @@ public class RestconfImpl implements RestconfService {
         return module;
     }
 
-    private InstanceIdWithSchemaNode addLastIdentifierFromData(
-            final InstanceIdWithSchemaNode identifierWithSchemaNode,
+    private InstanceIdWithSchemaNode addLastIdentifierFromData(final InstanceIdWithSchemaNode identifierWithSchemaNode,
             final CompositeNode data, final DataSchemaNode schemaOfData) {
         InstanceIdentifier instanceIdentifier = null;
         if (identifierWithSchemaNode != null) {
@@ -936,31 +927,28 @@ public class RestconfImpl implements RestconfService {
         InstanceIdentifierBuilder iiBuilder = null;
         if (iiOriginal == null) {
             iiBuilder = InstanceIdentifier.builder();
-        }
-        else {
+        } else {
             iiBuilder = InstanceIdentifier.builder(iiOriginal);
         }
 
         if ((schemaOfData instanceof ListSchemaNode)) {
-            HashMap<QName,Object> keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
+            HashMap<QName, Object> keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
             iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
-        }
-        else {
+        } else {
             iiBuilder.node(schemaOfData.getQName());
         }
 
         InstanceIdentifier instance = iiBuilder.toInstance();
         MountInstance mountPoint = null;
         if (identifierWithSchemaNode != null) {
-            mountPoint=identifierWithSchemaNode.getMountPoint();
+            mountPoint = identifierWithSchemaNode.getMountPoint();
         }
 
         return new InstanceIdWithSchemaNode(instance, schemaOfData, mountPoint);
     }
 
-    private HashMap<QName,Object> resolveKeysFromData(final ListSchemaNode listNode,
-            final CompositeNode dataNode) {
-        final HashMap<QName,Object> keyValues = new HashMap<QName, Object>();
+    private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
+        final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
         List<QName> _keyDefinition = listNode.getKeyDefinition();
         for (final QName key : _keyDefinition) {
             SimpleNode<? extends Object> head = null;
@@ -976,10 +964,9 @@ public class RestconfImpl implements RestconfService {
             }
 
             if (dataNodeKeyValueObject == null) {
-                throw new RestconfDocumentedException(
-                        "Data contains list \"" + dataNode.getNodeType().getLocalName() +
-                        "\" which does not contain key: \"" + key.getLocalName() + "\"",
-                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
+                        + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
+                        ErrorTag.INVALID_VALUE);
             }
 
             keyValues.put(key, dataNodeKeyValueObject);
@@ -989,15 +976,16 @@ public class RestconfImpl implements RestconfService {
     }
 
     private boolean endsWithMountPoint(final String identifier) {
-        return identifier.endsWith(ControllerContext.MOUNT) ||
-                identifier.endsWith(ControllerContext.MOUNT + "/");
+        return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
     }
 
     private boolean representsMountPointRootData(final CompositeNode data) {
         URI namespace = this.namespace(data);
-        return (SchemaContext.NAME.getNamespace().equals( namespace ) /* ||
-                MOUNT_POINT_MODULE_NAME.equals( namespace.toString() )*/ ) &&
-                SchemaContext.NAME.getLocalName().equals( this.localName(data) );
+        return (SchemaContext.NAME.getNamespace().equals(namespace) /*
+                                                                     * || MOUNT_POINT_MODULE_NAME .equals( namespace .
+                                                                     * toString( ) )
+                                                                     */)
+                && SchemaContext.NAME.getLocalName().equals(this.localName(data));
     }
 
     private String addMountPointIdentifier(final String identifier) {
@@ -1015,15 +1003,13 @@ public class RestconfImpl implements RestconfService {
             QName nodeType = node == null ? null : node.getNodeType();
             String localName = nodeType == null ? null : nodeType.getLocalName();
 
-            throw new RestconfDocumentedException(
-                    "Data schema node was not found for " + localName,
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            throw new RestconfDocumentedException("Data schema node was not found for " + localName,
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         if (!(schema instanceof DataNodeContainer)) {
-            throw new RestconfDocumentedException(
-                    "Root element has to be container or list yang datatype.",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         if ((node instanceof CompositeNodeWrapper)) {
@@ -1031,10 +1017,8 @@ public class RestconfImpl implements RestconfService {
             if (isChangeAllowed) {
                 try {
                     this.normalizeNode(((CompositeNodeWrapper) node), schema, null, mountPoint);
-                }
-                catch (IllegalArgumentException e) {
-                    throw new RestconfDocumentedException(
-                            e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                } catch (IllegalArgumentException e) {
+                    throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
                 }
             }
 
@@ -1044,66 +1028,56 @@ public class RestconfImpl implements RestconfService {
         return node;
     }
 
-    private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder,
-            final DataSchemaNode schema, final QName previousAugment,
-            final MountInstance mountPoint) {
+    private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
+            final QName previousAugment, final MountInstance mountPoint) {
         if (schema == null) {
-            throw new RestconfDocumentedException(
-                    "Data has bad format.\n\"" + nodeBuilder.getLocalName() +
-                    "\" does not exist in yang schema.",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
+                    + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         QName currentAugment = null;
         if (nodeBuilder.getQname() != null) {
             currentAugment = previousAugment;
-        }
-        else {
+        } else {
             currentAugment = this.normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
             if (nodeBuilder.getQname() == null) {
                 throw new RestconfDocumentedException(
-                        "Data has bad format.\nIf data is in XML format then namespace for \"" +
-                                nodeBuilder.getLocalName() +
-                                "\" should be \"" + schema.getQName().getNamespace() + "\".\n" +
-                                "If data is in JSON format then module name for \"" + nodeBuilder.getLocalName() +
-                                "\" should be corresponding to namespace \"" +
-                                schema.getQName().getNamespace() + "\".",
-                                ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                        "Data has bad format.\nIf data is in XML format then namespace for \""
+                                + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
+                                + "\".\n" + "If data is in JSON format then module name for \""
+                                + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
+                                + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
             }
         }
 
-        if ( nodeBuilder instanceof CompositeNodeWrapper ) {
-            if( schema instanceof DataNodeContainer ) {
-                normalizeCompositeNode( (CompositeNodeWrapper)nodeBuilder, (DataNodeContainer)schema,
-                        mountPoint, currentAugment );
-            }
-            else if( schema instanceof AnyXmlSchemaNode ) {
-                normalizeAnyXmlNode( (CompositeNodeWrapper)nodeBuilder, (AnyXmlSchemaNode)schema );
+        if (nodeBuilder instanceof CompositeNodeWrapper) {
+            if (schema instanceof DataNodeContainer) {
+                normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
+                        currentAugment);
+            } else if (schema instanceof AnyXmlSchemaNode) {
+                normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
             }
-        }
-        else if ( nodeBuilder instanceof SimpleNodeWrapper ) {
-            normalizeSimpleNode( (SimpleNodeWrapper) nodeBuilder, schema, mountPoint );
-        }
-        else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
-            normalizeEmptyNode( (EmptyNodeWrapper) nodeBuilder, schema );
+        } else if (nodeBuilder instanceof SimpleNodeWrapper) {
+            normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
+        } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
+            normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
         }
     }
 
-    private void normalizeAnyXmlNode( final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema ) {
+    private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
         List<NodeWrapper<?>> children = compositeNode.getValues();
-        for( NodeWrapper<? extends Object> child : children ) {
-            child.setNamespace( schema.getQName().getNamespace() );
-            if( child instanceof CompositeNodeWrapper ) {
-                normalizeAnyXmlNode( (CompositeNodeWrapper)child, schema );
+        for (NodeWrapper<? extends Object> child : children) {
+            child.setNamespace(schema.getQName().getNamespace());
+            if (child instanceof CompositeNodeWrapper) {
+                normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
             }
         }
     }
 
-    private void normalizeEmptyNode( final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema ) {
+    private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
         if ((schema instanceof LeafSchemaNode)) {
             emptyNodeBuilder.setComposite(false);
-        }
-        else {
+        } else {
             if ((schema instanceof ContainerSchemaNode)) {
                 // FIXME: Add presence check
                 emptyNodeBuilder.setComposite(true);
@@ -1111,59 +1085,55 @@ public class RestconfImpl implements RestconfService {
         }
     }
 
-    private void normalizeSimpleNode( final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
-            final MountInstance mountPoint ) {
+    private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
+            final MountInstance mountPoint) {
         final Object value = simpleNode.getValue();
         Object inputValue = value;
         TypeDefinition<? extends Object> typeDefinition = this.typeDefinition(schema);
         if ((typeDefinition instanceof IdentityrefTypeDefinition)) {
             if ((value instanceof String)) {
-                inputValue = new IdentityValuesDTO( simpleNode.getNamespace().toString(),
-                        (String) value, null, (String) value );
+                inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
+                        (String) value);
             } // else value is already instance of IdentityValuesDTO
         }
 
         Object outputValue = inputValue;
 
-        if( typeDefinition != null ) {
-            Codec<Object,Object> codec = RestCodec.from(typeDefinition, mountPoint);
+        if (typeDefinition != null) {
+            Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
             outputValue = codec == null ? null : codec.deserialize(inputValue);
         }
 
         simpleNode.setValue(outputValue);
     }
 
-    private void normalizeCompositeNode( final CompositeNodeWrapper compositeNodeBuilder,
-            final DataNodeContainer schema, final MountInstance mountPoint,
-            final QName currentAugment ) {
+    private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
+            final DataNodeContainer schema, final MountInstance mountPoint, final QName currentAugment) {
         final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
-        checkNodeMultiplicityAccordingToSchema(schema,children);
+        checkNodeMultiplicityAccordingToSchema(schema, children);
         for (final NodeWrapper<? extends Object> child : children) {
-            final List<DataSchemaNode> potentialSchemaNodes =
-                    this.controllerContext.findInstanceDataChildrenByName(
-                            schema, child.getLocalName());
+            final List<DataSchemaNode> potentialSchemaNodes = this.controllerContext.findInstanceDataChildrenByName(
+                    schema, child.getLocalName());
 
             if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
                 StringBuilder builder = new StringBuilder();
                 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
-                    builder.append("   ").append(potentialSchemaNode.getQName().getNamespace().toString())
-                    .append("\n");
+                    builder.append("   ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
                 }
 
-                throw new RestconfDocumentedException(
-                        "Node \"" + child.getLocalName() +
-                        "\" is added as augment from more than one module. " +
-                        "Therefore node must have namespace (XML format) or module name (JSON format)." +
-                        "\nThe node is added as augment from modules with namespaces:\n" + builder,
-                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                throw new RestconfDocumentedException("Node \"" + child.getLocalName()
+                        + "\" is added as augment from more than one module. "
+                        + "Therefore node must have namespace (XML format) or module name (JSON format)."
+                        + "\nThe node is added as augment from modules with namespaces:\n" + builder,
+                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
             }
 
             boolean rightNodeSchemaFound = false;
             for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
                 if (!rightNodeSchemaFound) {
-                    final QName potentialCurrentAugment =
-                            this.normalizeNodeName(child, potentialSchemaNode, currentAugment, mountPoint);
-                    if (child.getQname() != null ) {
+                    final QName potentialCurrentAugment = this.normalizeNodeName(child, potentialSchemaNode,
+                            currentAugment, mountPoint);
+                    if (child.getQname() != null) {
                         this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
                         rightNodeSchemaFound = true;
                     }
@@ -1171,14 +1141,13 @@ public class RestconfImpl implements RestconfService {
             }
 
             if (!rightNodeSchemaFound) {
-                throw new RestconfDocumentedException(
-                        "Schema node \"" + child.getLocalName() + "\" was not found in module.",
-                        ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT );
+                throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
+                        + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
             }
         }
 
         if ((schema instanceof ListSchemaNode)) {
-            ListSchemaNode listSchemaNode = (ListSchemaNode)schema;
+            ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
             final List<QName> listKeys = listSchemaNode.getKeyDefinition();
             for (final QName listKey : listKeys) {
                 boolean foundKey = false;
@@ -1189,10 +1158,9 @@ public class RestconfImpl implements RestconfService {
                 }
 
                 if (!foundKey) {
-                    throw new RestconfDocumentedException(
-                            "Missing key in URI \"" + listKey.getLocalName() +
-                            "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"",
-                            ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                    throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
+                            + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
+                            ErrorTag.DATA_MISSING);
                 }
             }
         }
@@ -1211,43 +1179,43 @@ public class RestconfImpl implements RestconfService {
                 String localName = childSchemaNode.getQName().getLocalName();
                 Integer count = equalNodeNamesToCounts.get(localName);
                 if (count != null && count > 1) {
-                    throw new RestconfDocumentedException(
-                            "Multiple input data elements were specified for '"
+                    throw new RestconfDocumentedException("Multiple input data elements were specified for '"
                             + childSchemaNode.getQName().getLocalName()
-                            + "'. The data for this element type can only be specified once.",
-                            ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT);
+                            + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
+                            ErrorTag.BAD_ELEMENT);
                 }
             }
         }
     }
 
-    private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder,
-            final DataSchemaNode schema, final QName previousAugment,
-            final MountInstance mountPoint) {
+    private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
+            final QName previousAugment, final MountInstance mountPoint) {
         QName validQName = schema.getQName();
         QName currentAugment = previousAugment;
         if (schema.isAugmenting()) {
             currentAugment = schema.getQName();
-        }
-        else if (previousAugment != null &&
-                !Objects.equal( schema.getQName().getNamespace(), previousAugment.getNamespace())) {
+        } else if (previousAugment != null
+                && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
             validQName = QName.create(currentAugment, schema.getQName().getLocalName());
         }
 
         String moduleName = null;
         if (mountPoint == null) {
             moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
-        }
-        else {
+        } else {
             moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
         }
 
-        if (nodeBuilder.getNamespace() == null ||
-                Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace()) ||
-                Objects.equal(nodeBuilder.getNamespace().toString(), moduleName) /*||
-            Note: this check is wrong - can never be true as it compares a URI with a String
-                  not sure what the intention is so commented out...
-            Objects.equal(nodeBuilder.getNamespace(), MOUNT_POINT_MODULE_NAME)*/ ) {
+        if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
+                || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName) /*
+                                                                                     * || Note : this check is wrong -
+                                                                                     * can never be true as it compares
+                                                                                     * a URI with a String not sure what
+                                                                                     * the intention is so commented out
+                                                                                     * ... Objects . equal ( nodeBuilder
+                                                                                     * . getNamespace ( ) ,
+                                                                                     * MOUNT_POINT_MODULE_NAME )
+                                                                                     */) {
 
             nodeBuilder.setQname(validQName);
         }
@@ -1257,40 +1225,31 @@ public class RestconfImpl implements RestconfService {
 
     private URI namespace(final CompositeNode data) {
         if (data instanceof CompositeNodeWrapper) {
-            return ((CompositeNodeWrapper)data).getNamespace();
-        }
-        else if (data != null) {
+            return ((CompositeNodeWrapper) data).getNamespace();
+        } else if (data != null) {
             return data.getNodeType().getNamespace();
-        }
-        else {
-            throw new IllegalArgumentException("Unhandled parameter types: " +
-                    Arrays.<Object>asList(data).toString());
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
         }
     }
 
     private String localName(final CompositeNode data) {
         if (data instanceof CompositeNodeWrapper) {
-            return ((CompositeNodeWrapper)data).getLocalName();
-        }
-        else if (data != null) {
+            return ((CompositeNodeWrapper) data).getLocalName();
+        } else if (data != null) {
             return data.getNodeType().getLocalName();
-        }
-        else {
-            throw new IllegalArgumentException("Unhandled parameter types: " +
-                    Arrays.<Object>asList(data).toString());
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
         }
     }
 
     private String getName(final CompositeNode data) {
         if (data instanceof CompositeNodeWrapper) {
-            return ((CompositeNodeWrapper)data).getLocalName();
-        }
-        else if (data != null) {
+            return ((CompositeNodeWrapper) data).getLocalName();
+        } else if (data != null) {
             return data.getNodeType().getLocalName();
-        }
-        else {
-            throw new IllegalArgumentException("Unhandled parameter types: " +
-                    Arrays.<Object>asList(data).toString());
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
         }
     }
 
@@ -1314,17 +1273,13 @@ public class RestconfImpl implements RestconfService {
 
     private TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
         if (node instanceof LeafListSchemaNode) {
-            return typeDefinition((LeafListSchemaNode)node);
-        }
-        else if (node instanceof LeafSchemaNode) {
-            return _typeDefinition((LeafSchemaNode)node);
-        }
-        else if (node instanceof AnyXmlSchemaNode) {
+            return typeDefinition((LeafListSchemaNode) node);
+        } else if (node instanceof LeafSchemaNode) {
+            return _typeDefinition((LeafSchemaNode) node);
+        } else if (node instanceof AnyXmlSchemaNode) {
             return null;
-        }
-        else {
-            throw new IllegalArgumentException("Unhandled parameter types: " +
-                    Arrays.<Object>asList(node).toString());
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
         }
     }
 }
index b0959c8398263dbd55a4ccb9fafac6d339f9fdaf..854e9635cf3cde883d97bbcc28f29c99bbda5c9c 100644 (file)
@@ -8,9 +8,7 @@
 package org.opendaylight.controller.sal.restconf.impl;
 
 import com.google.common.base.Preconditions;
-
 import java.net.URI;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
@@ -129,6 +127,4 @@ public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, Simp
         return unwrap().setValue(value);
     }
 
-
-
 }
index 6008b1d3c7d8f1f3d5d3e131a569f5eb42b960d3..120c67d3d5f5c3f44bb387d861fc371a829a1700 100644 (file)
@@ -5,4 +5,4 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-package org.opendaylight.controller.sal.restconf.impl;
+package org.opendaylight.controller.sal.restconf.impl;
\ No newline at end of file
index 417cca653365bf96e925925226ee313513a79417..4c5e3ab5301e0dc1fa4f27507030bc479f49a012 100644 (file)
@@ -1,16 +1,15 @@
 /*
-* Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*/
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.sal.restconf.rpc.impl;
 
 import java.util.concurrent.CancellationException;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
-
 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
@@ -21,7 +20,7 @@ import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 public abstract class AbstractRpcExecutor implements RpcExecutor {
     private final RpcDefinition rpcDef;
 
-    public AbstractRpcExecutor( RpcDefinition rpcDef ){
+    public AbstractRpcExecutor(RpcDefinition rpcDef) {
         this.rpcDef = rpcDef;
     }
 
@@ -31,60 +30,47 @@ public abstract class AbstractRpcExecutor implements RpcExecutor {
     }
 
     @Override
-    public RpcResult<CompositeNode> invokeRpc( CompositeNode rpcRequest )
-                                                   throws RestconfDocumentedException {
+    public RpcResult<CompositeNode> invokeRpc(CompositeNode rpcRequest) throws RestconfDocumentedException {
         try {
-            return getRpcResult( invokeRpcUnchecked( rpcRequest ) );
-        }
-        catch( IllegalArgumentException e ) {
-            throw new RestconfDocumentedException(
-                                e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
-        }
-        catch( UnsupportedOperationException e ) {
-            throw new RestconfDocumentedException(
-                                e.getMessage(), ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED );
-        }
-        catch( Exception e ) {
-            throw new RestconfDocumentedException(
-                    "The operation encountered an unexpected error while executing.", e );
+            return getRpcResult(invokeRpcUnchecked(rpcRequest));
+        } catch (IllegalArgumentException e) {
+            throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+        } catch (UnsupportedOperationException e) {
+            throw new RestconfDocumentedException(e.getMessage(), ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
+        } catch (Exception e) {
+            throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.", e);
         }
     }
 
-    protected abstract Future<RpcResult<CompositeNode>> invokeRpcUnchecked( CompositeNode rpcRequest );
+    protected abstract Future<RpcResult<CompositeNode>> invokeRpcUnchecked(CompositeNode rpcRequest);
 
-    protected RpcResult<CompositeNode> getRpcResult(
-                                            Future<RpcResult<CompositeNode>> fromFuture ) {
+    protected RpcResult<CompositeNode> getRpcResult(Future<RpcResult<CompositeNode>> fromFuture) {
         try {
             return fromFuture.get();
-        }
-        catch( InterruptedException e ) {
+        } catch (InterruptedException e) {
             throw new RestconfDocumentedException(
-                        "The operation was interrupted while executing and did not complete.",
-                        ErrorType.RPC, ErrorTag.PARTIAL_OPERATION );
-        }
-        catch( ExecutionException e ) {
+                    "The operation was interrupted while executing and did not complete.", ErrorType.RPC,
+                    ErrorTag.PARTIAL_OPERATION);
+        } catch (ExecutionException e) {
             Throwable cause = e.getCause();
-            if( cause instanceof CancellationException ) {
-                throw new RestconfDocumentedException(
-                        "The operation was cancelled while executing.",
-                        ErrorType.RPC, ErrorTag.PARTIAL_OPERATION );
-            }
-            else if( cause != null ){
-                while( cause.getCause() != null ) {
+            if (cause instanceof CancellationException) {
+                throw new RestconfDocumentedException("The operation was cancelled while executing.", ErrorType.RPC,
+                        ErrorTag.PARTIAL_OPERATION);
+            } else if (cause != null) {
+                while (cause.getCause() != null) {
                     cause = cause.getCause();
                 }
 
-                if( cause instanceof IllegalArgumentException ) {
-                    throw new RestconfDocumentedException(
-                            cause.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                if (cause instanceof IllegalArgumentException) {
+                    throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
+                            ErrorTag.INVALID_VALUE);
                 }
 
-                throw new RestconfDocumentedException(
-                       "The operation encountered an unexpected error while executing.", cause );
-            }
-            else {
-                throw new RestconfDocumentedException(
-                        "The operation encountered an unexpected error while executing.", e );
+                throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
+                        cause);
+            } else {
+                throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
+                        e);
             }
         }
     }
index e23e95faab21e2cc129a745ba4959dbaa7da5ef3..146e69f0112214792c9b7067025615e922bb5408 100644 (file)
@@ -1,14 +1,13 @@
 /*
-* Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*/
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.sal.restconf.rpc.impl;
 
 import java.util.concurrent.Future;
-
 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
@@ -17,14 +16,13 @@ import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 public class BrokerRpcExecutor extends AbstractRpcExecutor {
     private final BrokerFacade broker;
 
-    public BrokerRpcExecutor( RpcDefinition rpcDef, BrokerFacade broker )
-    {
-        super( rpcDef );
+    public BrokerRpcExecutor(RpcDefinition rpcDef, BrokerFacade broker) {
+        super(rpcDef);
         this.broker = broker;
     }
 
     @Override
-    protected Future<RpcResult<CompositeNode>> invokeRpcUnchecked( CompositeNode rpcRequest ) {
-        return broker.invokeRpc( getRpcDefinition().getQName(), rpcRequest );
+    protected Future<RpcResult<CompositeNode>> invokeRpcUnchecked(CompositeNode rpcRequest) {
+        return broker.invokeRpc(getRpcDefinition().getQName(), rpcRequest);
     }
 }
\ No newline at end of file
index 26cb3b81028637c1b513e5d89aad837923684a79..36502656c22834829deaaa73f01defce0be1885d 100644 (file)
@@ -1,23 +1,22 @@
 /*
-* Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*/
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.sal.restconf.rpc.impl;
 
+import com.google.common.base.Preconditions;
 import java.util.concurrent.Future;
-
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 
-import com.google.common.base.Preconditions;
-
 /**
  * Provides an implementation which invokes rpc methods via a mounted yang data model.
+ *
  * @author Devin Avery
  *
  */
@@ -25,13 +24,13 @@ public class MountPointRpcExecutor extends AbstractRpcExecutor {
     private final MountInstance mountPoint;
 
     public MountPointRpcExecutor(RpcDefinition rpcDef, MountInstance mountPoint) {
-        super( rpcDef );
+        super(rpcDef);
         this.mountPoint = mountPoint;
-        Preconditions.checkNotNull( mountPoint, "MountInstance can not be null." );
+        Preconditions.checkNotNull(mountPoint, "MountInstance can not be null.");
     }
 
     @Override
-    protected Future<RpcResult<CompositeNode>> invokeRpcUnchecked( CompositeNode rpcRequest ) {
-        return mountPoint.rpc( getRpcDefinition().getQName(), rpcRequest );
+    protected Future<RpcResult<CompositeNode>> invokeRpcUnchecked(CompositeNode rpcRequest) {
+        return mountPoint.rpc(getRpcDefinition().getQName(), rpcRequest);
     }
 }
\ No newline at end of file
index f628a63393d40e3016a96afb9b09c1fa196933e0..3430226c3a32174ffef9e3a6daac0230af91c98e 100644 (file)
@@ -1,10 +1,10 @@
 /*
-* Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*/
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.sal.restconf.rpc.impl;
 
 import org.opendaylight.yangtools.yang.common.RpcResult;
@@ -12,7 +12,7 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 
 public interface RpcExecutor {
-    RpcResult<CompositeNode> invokeRpc( CompositeNode rpcRequest );
+    RpcResult<CompositeNode> invokeRpc(CompositeNode rpcRequest);
 
     RpcDefinition getRpcDefinition();
 }
\ No newline at end of file
index 925a09337ca3ee1e8fba707020e3c7a19b8e03f6..e526ec13be75fad83ff6c33b95dfe9ba0d809298 100644 (file)
@@ -12,11 +12,9 @@ import com.google.common.base.Preconditions;
 import com.google.common.eventbus.AsyncEventBus;
 import com.google.common.eventbus.EventBus;
 import com.google.common.eventbus.Subscribe;
-
 import io.netty.channel.Channel;
 import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
 import io.netty.util.internal.ConcurrentSet;
-
 import java.io.ByteArrayOutputStream;
 import java.io.OutputStreamWriter;
 import java.io.UnsupportedEncodingException;
@@ -30,7 +28,6 @@ import java.util.Random;
 import java.util.Set;
 import java.util.concurrent.Executors;
 import java.util.regex.Pattern;
-
 import javax.activation.UnsupportedDataTypeException;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
@@ -41,7 +38,6 @@ 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.data.DataChangeEvent;
 import org.opendaylight.controller.sal.core.api.data.DataChangeListener;
 import org.opendaylight.controller.sal.rest.impl.XmlMapper;
@@ -61,8 +57,7 @@ import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
 /**
- * {@link ListenerAdapter} is responsible to track events, which occurred by
- * changing data in data source.
+ * {@link ListenerAdapter} is responsible to track events, which occurred by changing data in data source.
  */
 public class ListenerAdapter implements DataChangeListener {
 
@@ -72,8 +67,7 @@ public class ListenerAdapter implements DataChangeListener {
     private static final Pattern RFC3339_PATTERN = Pattern.compile("(\\d\\d)(\\d\\d)$");
 
     private final XmlMapper xmlMapper = new XmlMapper();
-    private final SimpleDateFormat rfc3339 = new SimpleDateFormat(
-            "yyyy-MM-dd'T'hh:mm:ssZ");
+    private final SimpleDateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
 
     private final InstanceIdentifier path;
     private ListenerRegistration<DataChangeListener> registration;
@@ -82,10 +76,8 @@ public class ListenerAdapter implements DataChangeListener {
     private final EventBus eventBus;
     private final EventBusChangeRecorder eventBusChangeRecorder;
 
-
     /**
-     * Creates new {@link ListenerAdapter} listener specified by path and stream
-     * name.
+     * Creates new {@link ListenerAdapter} listener specified by path and stream name.
      *
      * @param path
      *            Path to data in data store.
@@ -94,8 +86,7 @@ public class ListenerAdapter implements DataChangeListener {
      */
     ListenerAdapter(final InstanceIdentifier path, final String streamName) {
         Preconditions.checkNotNull(path);
-        Preconditions
-        .checkArgument(streamName != null && !streamName.isEmpty());
+        Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
         this.path = path;
         this.streamName = streamName;
         eventBus = new AsyncEventBus(Executors.newSingleThreadExecutor());
@@ -104,14 +95,10 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     @Override
-    public void onDataChanged(
-            final DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
-        if (!change.getCreatedConfigurationData().isEmpty()
-                || !change.getCreatedOperationalData().isEmpty()
-                || !change.getUpdatedConfigurationData().isEmpty()
-                || !change.getUpdatedOperationalData().isEmpty()
-                || !change.getRemovedConfigurationData().isEmpty()
-                || !change.getRemovedOperationalData().isEmpty()) {
+    public void onDataChanged(final DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
+        if (!change.getCreatedConfigurationData().isEmpty() || !change.getCreatedOperationalData().isEmpty()
+                || !change.getUpdatedConfigurationData().isEmpty() || !change.getUpdatedOperationalData().isEmpty()
+                || !change.getRemovedConfigurationData().isEmpty() || !change.getRemovedOperationalData().isEmpty()) {
             String xml = prepareXmlFrom(change);
             Event event = new Event(EventType.NOTIFY);
             event.setData(xml);
@@ -132,19 +119,14 @@ public class ListenerAdapter implements DataChangeListener {
                 }
             } else if (event.getType() == EventType.DEREGISTER) {
                 subscribers.remove(event.getSubscriber());
-                Notificator
-                .removeListenerIfNoSubscriberExists(ListenerAdapter.this);
+                Notificator.removeListenerIfNoSubscriberExists(ListenerAdapter.this);
             } else if (event.getType() == EventType.NOTIFY) {
                 for (Channel subscriber : subscribers) {
                     if (subscriber.isActive()) {
-                        LOG.debug("Data are sent to subscriber {}:",
-                                subscriber.remoteAddress());
-                        subscriber.writeAndFlush(new TextWebSocketFrame(event
-                                .getData()));
+                        LOG.debug("Data are sent to subscriber {}:", subscriber.remoteAddress());
+                        subscriber.writeAndFlush(new TextWebSocketFrame(event.getData()));
                     } else {
-                        LOG.debug(
-                                "Subscriber {} is removed - channel is not active yet.",
-                                subscriber.remoteAddress());
+                        LOG.debug("Subscriber {} is removed - channel is not active yet.", subscriber.remoteAddress());
                         subscribers.remove(subscriber);
                     }
                 }
@@ -153,8 +135,7 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     /**
-     * Represents event of specific {@link EventType} type, holds data and
-     * {@link Channel} subscriber.
+     * Represents event of specific {@link EventType} type, holds data and {@link Channel} subscriber.
      */
     private final class Event {
         private final EventType type;
@@ -223,7 +204,9 @@ public class ListenerAdapter implements DataChangeListener {
      * Type of the event.
      */
     private enum EventType {
-        REGISTER, DEREGISTER, NOTIFY;
+        REGISTER,
+        DEREGISTER,
+        NOTIFY;
     }
 
     /**
@@ -233,11 +216,9 @@ public class ListenerAdapter implements DataChangeListener {
      *            DataChangeEvent
      * @return Data in printable form.
      */
-    private String prepareXmlFrom(
-            final DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
+    private String prepareXmlFrom(final DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
         Document doc = createDocument();
-        Element notificationElement = doc.createElementNS(
-                "urn:ietf:params:xml:ns:netconf:notification:1.0",
+        Element notificationElement = doc.createElementNS("urn:ietf:params:xml:ns:netconf:notification:1.0",
                 "notification");
         doc.appendChild(notificationElement);
 
@@ -246,10 +227,8 @@ public class ListenerAdapter implements DataChangeListener {
         notificationElement.appendChild(eventTimeElement);
 
         Element dataChangedNotificationEventElement = doc.createElementNS(
-                "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote",
-                "data-changed-notification");
-        addValuesToDataChangedNotificationEventElement(doc,
-                dataChangedNotificationEventElement, change);
+                "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "data-changed-notification");
+        addValuesToDataChangedNotificationEventElement(doc, dataChangedNotificationEventElement, change);
         notificationElement.appendChild(dataChangedNotificationEventElement);
 
         try {
@@ -260,8 +239,7 @@ public class ListenerAdapter implements DataChangeListener {
             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
-            transformer.transform(new DOMSource(doc), new StreamResult(
-                    new OutputStreamWriter(out, Charsets.UTF_8)));
+            transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, Charsets.UTF_8)));
             byte[] charData = out.toByteArray();
             return new String(charData, "UTF-8");
         } catch (TransformerException | UnsupportedEncodingException e) {
@@ -310,29 +288,22 @@ public class ListenerAdapter implements DataChangeListener {
     private void addValuesToDataChangedNotificationEventElement(final Document doc,
             final Element dataChangedNotificationEventElement,
             final DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
-        addValuesFromDataToElement(doc, change.getCreatedConfigurationData(),
-                dataChangedNotificationEventElement, Store.CONFIG,
-                Operation.CREATED);
-        addValuesFromDataToElement(doc, change.getCreatedOperationalData(),
-                dataChangedNotificationEventElement, Store.OPERATION,
-                Operation.CREATED);
+        addValuesFromDataToElement(doc, change.getCreatedConfigurationData(), dataChangedNotificationEventElement,
+                Store.CONFIG, Operation.CREATED);
+        addValuesFromDataToElement(doc, change.getCreatedOperationalData(), dataChangedNotificationEventElement,
+                Store.OPERATION, Operation.CREATED);
         if (change.getCreatedConfigurationData().isEmpty()) {
-            addValuesFromDataToElement(doc,
-                    change.getUpdatedConfigurationData(),
-                    dataChangedNotificationEventElement, Store.CONFIG,
-                    Operation.UPDATED);
+            addValuesFromDataToElement(doc, change.getUpdatedConfigurationData(), dataChangedNotificationEventElement,
+                    Store.CONFIG, Operation.UPDATED);
         }
         if (change.getCreatedOperationalData().isEmpty()) {
-            addValuesFromDataToElement(doc, change.getUpdatedOperationalData(),
-                    dataChangedNotificationEventElement, Store.OPERATION,
-                    Operation.UPDATED);
+            addValuesFromDataToElement(doc, change.getUpdatedOperationalData(), dataChangedNotificationEventElement,
+                    Store.OPERATION, Operation.UPDATED);
         }
-        addValuesFromDataToElement(doc, change.getRemovedConfigurationData(),
-                dataChangedNotificationEventElement, Store.CONFIG,
-                Operation.DELETED);
-        addValuesFromDataToElement(doc, change.getRemovedOperationalData(),
-                dataChangedNotificationEventElement, Store.OPERATION,
-                Operation.DELETED);
+        addValuesFromDataToElement(doc, change.getRemovedConfigurationData(), dataChangedNotificationEventElement,
+                Store.CONFIG, Operation.DELETED);
+        addValuesFromDataToElement(doc, change.getRemovedOperationalData(), dataChangedNotificationEventElement,
+                Store.OPERATION, Operation.DELETED);
     }
 
     /**
@@ -349,15 +320,13 @@ public class ListenerAdapter implements DataChangeListener {
      * @param operation
      *            {@link Operation}
      */
-    private void addValuesFromDataToElement(final Document doc,
-            final Set<InstanceIdentifier> data, final Element element, final Store store,
-            final Operation operation) {
+    private void addValuesFromDataToElement(final Document doc, final Set<InstanceIdentifier> data,
+            final Element element, final Store store, final Operation operation) {
         if (data == null || data.isEmpty()) {
             return;
         }
         for (InstanceIdentifier path : data) {
-            Node node = createDataChangeEventElement(doc, path, null, store,
-                    operation);
+            Node node = createDataChangeEventElement(doc, path, null, store, operation);
             element.appendChild(node);
         }
     }
@@ -376,15 +345,13 @@ public class ListenerAdapter implements DataChangeListener {
      * @param operation
      *            {@link Operation}
      */
-    private void addValuesFromDataToElement(final Document doc,
-            final Map<InstanceIdentifier, CompositeNode> data, final Element element,
-            final Store store, final Operation operation) {
+    private void addValuesFromDataToElement(final Document doc, final Map<InstanceIdentifier, CompositeNode> data,
+            final Element element, final Store store, final Operation operation) {
         if (data == null || data.isEmpty()) {
             return;
         }
         for (Entry<InstanceIdentifier, CompositeNode> entry : data.entrySet()) {
-            Node node = createDataChangeEventElement(doc, entry.getKey(),
-                    entry.getValue(), store, operation);
+            Node node = createDataChangeEventElement(doc, entry.getKey(), entry.getValue(), store, operation);
             element.appendChild(node);
         }
     }
@@ -404,9 +371,8 @@ public class ListenerAdapter implements DataChangeListener {
      *            {@link Operation}
      * @return {@link Node} node represented by changed event element.
      */
-    private Node createDataChangeEventElement(final Document doc,
-            final InstanceIdentifier path, final CompositeNode data, final Store store,
-            final Operation operation) {
+    private Node createDataChangeEventElement(final Document doc, final InstanceIdentifier path,
+            final CompositeNode data, final Store store, final Operation operation) {
         Element dataChangeEventElement = doc.createElement("data-change-event");
 
         Element pathElement = doc.createElement("path");
@@ -442,8 +408,7 @@ public class ListenerAdapter implements DataChangeListener {
      * @return Data in XML format.
      */
     private Node translateToXml(final InstanceIdentifier path, final CompositeNode data) {
-        DataNodeContainer schemaNode = ControllerContext.getInstance()
-                .getDataNodeContainerFor(path);
+        DataNodeContainer schemaNode = ControllerContext.getInstance().getDataNodeContainerFor(path);
         if (schemaNode == null) {
             LOG.info(
                     "Path '{}' contains node with unsupported type (supported type is Container or List) or some node was not found.",
@@ -454,9 +419,7 @@ public class ListenerAdapter implements DataChangeListener {
             Document xml = xmlMapper.write(data, schemaNode);
             return xml.getFirstChild();
         } catch (UnsupportedDataTypeException e) {
-            LOG.error(
-                    "Error occured during translation of notification to XML.",
-                    e);
+            LOG.error("Error occured during translation of notification to XML.", e);
             return null;
         }
     }
@@ -469,8 +432,7 @@ public class ListenerAdapter implements DataChangeListener {
      * @param element
      *            {@link Element}
      */
-    private void addPathAsValueToElement(final InstanceIdentifier path,
-            final Element element) {
+    private void addPathAsValueToElement(final InstanceIdentifier path, final Element element) {
         // Map< key = namespace, value = prefix>
         Map<String, String> prefixes = new HashMap<>();
         InstanceIdentifier instanceIdentifier = path;
@@ -479,17 +441,13 @@ public class ListenerAdapter implements DataChangeListener {
         // FIXME: BUG-1281: this is duplicated code from yangtools (BUG-1275)
         for (PathArgument pathArgument : instanceIdentifier.getPathArguments()) {
             textContent.append("/");
-            writeIdentifierWithNamespacePrefix(element, textContent,
-                    pathArgument.getNodeType(), prefixes);
+            writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes);
             if (pathArgument instanceof NodeIdentifierWithPredicates) {
-                Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument)
-                        .getKeyValues();
+                Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
                 for (QName keyValue : predicates.keySet()) {
-                    String predicateValue = String.valueOf(predicates
-                            .get(keyValue));
+                    String predicateValue = String.valueOf(predicates.get(keyValue));
                     textContent.append("[");
-                    writeIdentifierWithNamespacePrefix(element, textContent,
-                            keyValue, prefixes);
+                    writeIdentifierWithNamespacePrefix(element, textContent, keyValue, prefixes);
                     textContent.append("='");
                     textContent.append(predicateValue);
                     textContent.append("'");
@@ -517,14 +475,13 @@ public class ListenerAdapter implements DataChangeListener {
      * @param prefixes
      *            Map of namespaces and prefixes.
      */
-    private static void writeIdentifierWithNamespacePrefix(final Element element,
-            final StringBuilder textContent, final QName qName, final Map<String, String> prefixes) {
+    private static void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent,
+            final QName qName, final Map<String, String> prefixes) {
         String namespace = qName.getNamespace().toString();
         String prefix = prefixes.get(namespace);
         if (prefix == null) {
             prefix = qName.getPrefix();
-            if (prefix == null || prefix.isEmpty()
-                    || prefixes.containsValue(prefix)) {
+            if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
                 prefix = generateNewPrefix(prefixes.values());
             }
         }
@@ -573,8 +530,7 @@ public class ListenerAdapter implements DataChangeListener {
      * @param registration
      *            ListenerRegistration<DataChangeListener>
      */
-    public void setRegistration(
-            final ListenerRegistration<DataChangeListener> registration) {
+    public void setRegistration(final ListenerRegistration<DataChangeListener> registration) {
         this.registration = registration;
     }
 
@@ -588,8 +544,7 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     /**
-     * Removes all subscribers and unregisters event bus change recorder form
-     * event bus.
+     * Removes all subscribers and unregisters event bus change recorder form event bus.
      */
     public void close() throws Exception {
         subscribers = new ConcurrentSet<>();
@@ -608,16 +563,15 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     /**
-     * Creates event of type {@link EventType#REGISTER}, set {@link Channel}
-     * subscriber to the event and post event into event bus.
+     * Creates event of type {@link EventType#REGISTER}, set {@link Channel} subscriber to the event and post event into
+     * event bus.
      *
      * @param subscriber
      *            Channel
      */
     public void addSubscriber(final Channel subscriber) {
         if (!subscriber.isActive()) {
-            LOG.debug("Channel is not active between websocket server and subscriber {}"
-                    + subscriber.remoteAddress());
+            LOG.debug("Channel is not active between websocket server and subscriber {}" + subscriber.remoteAddress());
         }
         Event event = new Event(EventType.REGISTER);
         event.setSubscriber(subscriber);
@@ -625,8 +579,8 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     /**
-     * Creates event of type {@link EventType#DEREGISTER}, sets {@link Channel}
-     * subscriber to the event and posts event into event bus.
+     * Creates event of type {@link EventType#DEREGISTER}, sets {@link Channel} subscriber to the event and posts event
+     * into event bus.
      *
      * @param subscriber
      */
@@ -640,8 +594,7 @@ public class ListenerAdapter implements DataChangeListener {
     /**
      * Checks if exists at least one {@link Channel} subscriber.
      *
-     * @return True if exist at least one {@link Channel} subscriber, false
-     *         otherwise.
+     * @return True if exist at least one {@link Channel} subscriber, false otherwise.
      */
     public boolean hasSubscribers() {
         return !subscribers.isEmpty();
@@ -651,7 +604,8 @@ public class ListenerAdapter implements DataChangeListener {
      * Consists of two types {@link Store#CONFIG} and {@link Store#OPERATION}.
      */
     private static enum Store {
-        CONFIG("config"), OPERATION("operation");
+        CONFIG("config"),
+        OPERATION("operation");
 
         private final String value;
 
@@ -661,11 +615,12 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     /**
-     * Consists of three types {@link Operation#CREATED},
-     * {@link Operation#UPDATED} and {@link Operation#DELETED}.
+     * Consists of three types {@link Operation#CREATED}, {@link Operation#UPDATED} and {@link Operation#DELETED}.
      */
     private static enum Operation {
-        CREATED("created"), UPDATED("updated"), DELETED("deleted");
+        CREATED("created"),
+        UPDATED("updated"),
+        DELETED("deleted");
 
         private final String value;
 
index a576eed26978fb0380cd8a28613712409bf6ce53..166c473b9c77d118b14c822bc177a1320b77e0fe 100644 (file)
@@ -12,7 +12,6 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
-
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 
 /**
@@ -34,7 +33,6 @@ public class Notificator {
         return listenersByStreamName.keySet();
     }
 
-
     /**
      * Gets {@link ListenerAdapter} specified by stream name.
      *
@@ -47,8 +45,7 @@ public class Notificator {
     }
 
     /**
-     * Gets {@link ListenerAdapter} listener specified by
-     * {@link InstanceIdentifier} path.
+     * Gets {@link ListenerAdapter} listener specified by {@link InstanceIdentifier} path.
      *
      * @param path
      *            Path to data in data repository.
@@ -59,8 +56,7 @@ public class Notificator {
     }
 
     /**
-     * Checks if the listener specified by {@link InstanceIdentifier} path
-     * exist.
+     * Checks if the listener specified by {@link InstanceIdentifier} path exist.
      *
      * @param path
      *            Path to data in data repository.
@@ -71,18 +67,15 @@ public class Notificator {
     }
 
     /**
-     * Creates new {@link ListenerAdapter} listener from
-     * {@link InstanceIdentifier} path and stream name.
+     * Creates new {@link ListenerAdapter} listener from {@link InstanceIdentifier} path and stream name.
      *
      * @param path
      *            Path to data in data repository.
      * @param streamName
      *            The name of the stream.
-     * @return New {@link ListenerAdapter} listener from
-     *         {@link InstanceIdentifier} path and stream name.
+     * @return New {@link ListenerAdapter} listener from {@link InstanceIdentifier} path and stream name.
      */
-    public static ListenerAdapter createListener(InstanceIdentifier path,
-            String streamName) {
+    public static ListenerAdapter createListener(InstanceIdentifier path, String streamName) {
         ListenerAdapter listener = new ListenerAdapter(path, streamName);
         try {
             lock.lock();
@@ -95,8 +88,7 @@ public class Notificator {
     }
 
     /**
-     * Looks for listener determined by {@link InstanceIdentifier} path and
-     * removes it.
+     * Looks for listener determined by {@link InstanceIdentifier} path and removes it.
      *
      * @param path
      *            InstanceIdentifier
@@ -107,8 +99,7 @@ public class Notificator {
     }
 
     /**
-     * Creates String representation of stream name from URI. Removes slash from
-     * URI in start and end position.
+     * Creates String representation of stream name from URI. Removes slash from URI in start and end position.
      *
      * @param uri
      *            URI for creation stream name.
@@ -148,14 +139,12 @@ public class Notificator {
     }
 
     /**
-     * Checks if listener has at least one subscriber. In case it doesn't have any, delete
-     * listener.
+     * Checks if listener has at least one subscriber. In case it doesn't have any, delete listener.
      *
      * @param listener
      *            ListenerAdapter
      */
-    public static void removeListenerIfNoSubscriberExists(
-            ListenerAdapter listener) {
+    public static void removeListenerIfNoSubscriberExists(ListenerAdapter listener) {
         if (!listener.hasSubscribers()) {
             deleteListener(listener);
         }
index 20951b01e2dd52a16b80cb5794d049c858eb2d82..67ed44f84ea86020b54553f3f0b4f108e4ada66f 100644 (file)
@@ -1,24 +1,21 @@
 package org.opendaylight.controller.sal.streams.websockets;
 
+import com.google.common.base.Preconditions;
 import io.netty.bootstrap.ServerBootstrap;
 import io.netty.channel.Channel;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.channel.socket.nio.NioServerSocketChannel;
-
 import org.opendaylight.controller.sal.streams.listeners.Notificator;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Preconditions;
-
 /**
  * {@link WebSocketServer} is responsible to start and stop web socket server
  */
 public class WebSocketServer implements Runnable {
 
-    private static final Logger logger = LoggerFactory
-            .getLogger(WebSocketServer.class);
+    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
     public static final String WEBSOCKET_SERVER_CONFIG_PROPERTY = "restconf.websocket.port";
     public static final int DEFAULT_PORT = 8181;
     private EventLoopGroup bossGroup;
@@ -32,14 +29,16 @@ public class WebSocketServer implements Runnable {
 
     /**
      * Create instance of {@link WebSocketServer}
-     * @param port TCP port used for this server
+     *
+     * @param port
+     *            TCP port used for this server
      * @return instance of {@link WebSocketServer}
      */
     public static WebSocketServer createInstance(int port) {
-        if(singleton != null) {
+        if (singleton != null) {
             throw new IllegalStateException("createInstance() has already been called");
         }
-        if(port < 1024) {
+        if (port < 1024) {
             throw new IllegalArgumentException("Privileged port (below 1024) is not allowed");
         }
         singleton = new WebSocketServer(port);
@@ -55,11 +54,11 @@ public class WebSocketServer implements Runnable {
 
     /**
      * Get instance of {@link WebSocketServer} created by {@link #createInstance(int)}
+     *
      * @return instance of {@link WebSocketServer}
      */
     public static WebSocketServer getInstance() {
-        Preconditions.checkNotNull(singleton,
-                "createInstance() must be called prior to getInstance()");
+        Preconditions.checkNotNull(singleton, "createInstance() must be called prior to getInstance()");
         return singleton;
     }
 
@@ -67,9 +66,8 @@ public class WebSocketServer implements Runnable {
      * Destroy this already created instance
      */
     public static void destroyInstance() {
-        if(singleton == null) {
-            throw new IllegalStateException(
-                    "createInstance() must be called prior to destroyInstance()");
+        if (singleton == null) {
+            throw new IllegalStateException("createInstance() must be called prior to destroyInstance()");
         }
         getInstance().stop();
     }
@@ -80,8 +78,7 @@ public class WebSocketServer implements Runnable {
         workerGroup = new NioEventLoopGroup();
         try {
             ServerBootstrap b = new ServerBootstrap();
-            b.group(bossGroup, workerGroup)
-                    .channel(NioServerSocketChannel.class)
+            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                     .childHandler(new WebSocketServerInitializer());
 
             Channel ch = b.bind(port).sync().channel();
index 26e4936d3f27d0d20e3875fe051335d79beae3be..ce12d34e083f2ca440c754ab736aed1834276e0f 100644 (file)
@@ -8,6 +8,7 @@ import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
 import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
 import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
+
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
 import io.netty.channel.ChannelFuture;
@@ -25,29 +26,24 @@ import io.netty.handler.codec.http.websocketx.WebSocketFrame;
 import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
 import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
 import io.netty.util.CharsetUtil;
-
 import java.io.IOException;
-
 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
 import org.opendaylight.controller.sal.streams.listeners.Notificator;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * {@link WebSocketServerHandler} is implementation of
- * {@link SimpleChannelInboundHandler} which allow handle
+ * {@link WebSocketServerHandler} is implementation of {@link SimpleChannelInboundHandler} which allow handle
  * {@link FullHttpRequest} and {@link WebSocketFrame} messages.
  */
 public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
 
-    private static final Logger logger = LoggerFactory
-            .getLogger(WebSocketServerHandler.class);
+    private static final Logger logger = LoggerFactory.getLogger(WebSocketServerHandler.class);
 
     private WebSocketServerHandshaker handshaker;
 
     @Override
-    protected void channelRead0(final ChannelHandlerContext ctx, final Object msg)
-            throws Exception {
+    protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
         if (msg instanceof FullHttpRequest) {
             handleHttpRequest(ctx, (FullHttpRequest) msg);
         } else if (msg instanceof WebSocketFrame) {
@@ -56,27 +52,23 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
     }
 
     /**
-     * Checks if HTTP request method is GET and if is possible to decode HTTP
-     * result of request.
+     * Checks if HTTP request method is GET and if is possible to decode HTTP result of request.
      *
      * @param ctx
      *            ChannelHandlerContext
      * @param req
      *            FullHttpRequest
      */
-    private void handleHttpRequest(final ChannelHandlerContext ctx,
-            final FullHttpRequest req) throws Exception {
+    private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception {
         // Handle a bad request.
         if (!req.getDecoderResult().isSuccess()) {
-            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
-                    BAD_REQUEST));
+            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
             return;
         }
 
         // Allow only GET methods.
         if (req.getMethod() != GET) {
-            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
-                    FORBIDDEN));
+            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
             return;
         }
 
@@ -86,15 +78,13 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
             listener.addSubscriber(ctx.channel());
             logger.debug("Subscriber successfully registered.");
         } else {
-            logger.error("Listener for stream with name '{}' was not found.",
-                    streamName);
-            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
-                    INTERNAL_SERVER_ERROR));
+            logger.error("Listener for stream with name '{}' was not found.", streamName);
+            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
         }
 
         // Handshake
-        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
-                getWebSocketLocation(req), null, false);
+        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
+                null, false);
         handshaker = wsFactory.newHandshaker(req);
         if (handshaker == null) {
             WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
@@ -114,12 +104,11 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
      * @param res
      *            FullHttpResponse
      */
-    private static void sendHttpResponse(final ChannelHandlerContext ctx,
-            final HttpRequest req, final FullHttpResponse res) {
+    private static void sendHttpResponse(final ChannelHandlerContext ctx, final HttpRequest req,
+            final FullHttpResponse res) {
         // Generate an error page if response getStatus code is not OK (200).
         if (res.getStatus().code() != 200) {
-            ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
-                    CharsetUtil.UTF_8);
+            ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
             res.content().writeBytes(buf);
             buf.release();
             setContentLength(res, res.content().readableBytes());
@@ -140,14 +129,10 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
      * @param frame
      *            {@link WebSocketFrame}
      */
-    private void handleWebSocketFrame(final ChannelHandlerContext ctx,
-            final WebSocketFrame frame) throws IOException {
+    private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) throws IOException {
         if (frame instanceof CloseWebSocketFrame) {
-            handshaker.close(ctx.channel(),
-                    (CloseWebSocketFrame) frame.retain());
-            String streamName = Notificator
-                    .createStreamNameFromUri(((CloseWebSocketFrame) frame)
-                            .reasonText());
+            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
+            String streamName = Notificator.createStreamNameFromUri(((CloseWebSocketFrame) frame).reasonText());
             ListenerAdapter listener = Notificator.getListenerFor(streamName);
             if (listener != null) {
                 listener.removeSubscriber(ctx.channel());
@@ -156,15 +141,13 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
             Notificator.removeListenerIfNoSubscriberExists(listener);
             return;
         } else if (frame instanceof PingWebSocketFrame) {
-            ctx.channel().write(
-                    new PongWebSocketFrame(frame.content().retain()));
+            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
             return;
         }
     }
 
     @Override
-    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause)
-            throws Exception {
+    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
         if (cause instanceof java.nio.channels.ClosedChannelException == false) {
             // cause.printStackTrace();
         }
index d188a029e7582a7672a67af0a956f978df79cc1b..754f156dde52d7b57eee9bc85b510685681bfc4c 100644 (file)
@@ -7,8 +7,8 @@ import io.netty.handler.codec.http.HttpObjectAggregator;
 import io.netty.handler.codec.http.HttpServerCodec;
 
 /**
- * {@link WebSocketServerInitializer} is used to setup the
- * {@link ChannelPipeline} of a {@link io.netty.channel.Channel}.
+ * {@link WebSocketServerInitializer} is used to setup the {@link ChannelPipeline} of a {@link io.netty.channel.Channel}
+ * .
  */
 public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {
 
index d978a2f0de25af2f26c106dea7c79a759fea4ce0..0f059f5024cdc7c70dc7042f488e9fa22c32da55 100644 (file)
@@ -13,13 +13,13 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
 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;
@@ -37,9 +37,6 @@ 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 CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
 
     @BeforeClass
@@ -48,8 +45,7 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test of json output when as input are specified composite node with empty
-     * data + YANG file
+     * Test of json output when as input are specified composite node with empty data + YANG file
      */
 
     @Test
@@ -67,8 +63,7 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test of json output when as input are specified xml file (no empty
-     * elements)and YANG file
+     * Test of json output when as input are specified xml file (no empty elements)and YANG file
      */
     @Test
     public void xmlAndYangTypesWithJsonReaderTest() {
@@ -355,11 +350,8 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
         assertEquals(1, lst11_1.getLfs().size());
         assertEquals(1, lst11_1.getConts().size());
         assertEquals(1, lst11_1.getLsts().size());
-        assertEquals(
-                lst11_1.getLsts().get("lst111"),
-                new Lst("lst111").addLstItem(new LstItem().addLf("lf1111", 35))
-                .addLstItem(new LstItem().addLf("lf1111", 34)).addLstItem(new LstItem())
-                .addLstItem(new LstItem()));
+        assertEquals(lst11_1.getLsts().get("lst111"), new Lst("lst111").addLstItem(new LstItem().addLf("lf1111", 35))
+                .addLstItem(new LstItem().addLf("lf1111", 34)).addLstItem(new LstItem()).addLstItem(new LstItem()));
         assertEquals(lst11_1.getConts().get("cont111"), new Cont("cont111"));
         // : lst11_1
 
@@ -378,8 +370,7 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
         assertEquals(1, lst11_2_cont111.getLsts().size());
         assertTrue(lst11_2_cont111.getConts().isEmpty());
 
-        assertEquals(new LfLst("lflst1111").addLf(1024).addLf(4096),
-                lst11_2_cont111.getLfLsts().get("lflst1111"));
+        assertEquals(new LfLst("lflst1111").addLf(1024).addLf(4096), lst11_2_cont111.getLfLsts().get("lflst1111"));
         assertEquals(
                 new Lst("lst1111").addLstItem(new LstItem().addLf("lf1111B", 4)).addLstItem(
                         new LstItem().addLf("lf1111A", "lf1111A str12")), lst11_2_cont111.getLsts().get("lst1111"));
@@ -539,90 +530,108 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
                 TestUtils.buildQName("cont1", "simple:yang:types", "2013-11-5"), null, null, ModifyAction.CREATE, null);
 
         // lst11_1
-        MutableCompositeNode lst11_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1,
-                null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst11_1 = NodeFactory
+                .createMutableCompositeNode(TestUtils.buildQName("lst11", "simple:yang:types", "2013-11-5"), cont1,
+                        null, ModifyAction.CREATE, null);
         cont1.getValue().add(lst11_1);
 
-        MutableSimpleNode<?> lf111_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111","simple:yang:types","2013-11-5"), lst11_1,
-                (short) 1, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf111_1 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf111", "simple:yang:types", "2013-11-5"), lst11_1, (short) 1,
+                ModifyAction.CREATE, null);
         lst11_1.getValue().add(lf111_1);
 
         // lst111_1_1
-        MutableCompositeNode lst111_1_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
-                lst11_1, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst111_1_1 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
+                null);
         lst11_1.getValue().add(lst111_1_1);
-        MutableSimpleNode<?> lf1111_1_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111","simple:yang:types","2013-11-5"),
-                lst111_1_1, 34, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1111_1_1 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf1111", "simple:yang:types", "2013-11-5"), lst111_1_1, 34, ModifyAction.CREATE,
+                null);
         lst111_1_1.getValue().add(lf1111_1_1);
         lst111_1_1.init();
         // :lst111_1_1
 
         // lst111_1_2
-        MutableCompositeNode lst111_1_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
-                lst11_1, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst111_1_2 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
+                null);
         lst11_1.getValue().add(lst111_1_2);
-        MutableSimpleNode<?> lf1111_1_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111","simple:yang:types","2013-11-5"),
-                lst111_1_2, 35, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1111_1_2 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf1111", "simple:yang:types", "2013-11-5"), lst111_1_2, 35, ModifyAction.CREATE,
+                null);
         lst111_1_2.getValue().add(lf1111_1_2);
         lst111_1_2.init();
         // :lst111_1_2
 
         // lst111_1_3
-        MutableCompositeNode lst111_1_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
-                lst11_1, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst111_1_3 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
+                null);
         lst11_1.getValue().add(lst111_1_3);
         lst111_1_2.init();
         // :lst111_1_3
 
         // lst111_1_4
-        MutableCompositeNode lst111_1_4 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
-                lst11_1, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst111_1_4 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
+                null);
         lst11_1.getValue().add(lst111_1_4);
         lst111_1_2.init();
         // :lst111_1_4
 
-        MutableCompositeNode cont111_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111","simple:yang:types","2013-11-5"),
-                lst11_1, null, ModifyAction.CREATE, null);
+        MutableCompositeNode cont111_1 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
+                null);
         lst11_1.getValue().add(cont111_1);
 
         lst11_1.init();
         // :lst11_1
 
         // lst11_2
-        MutableCompositeNode lst11_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1,
-                null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst11_2 = NodeFactory
+                .createMutableCompositeNode(TestUtils.buildQName("lst11", "simple:yang:types", "2013-11-5"), cont1,
+                        null, ModifyAction.CREATE, null);
         cont1.getValue().add(lst11_2);
 
-        MutableSimpleNode<?> lf111_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111","simple:yang:types","2013-11-5"), lst11_2,
-                (short) 2, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf111_2 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf111", "simple:yang:types", "2013-11-5"), lst11_2, (short) 2,
+                ModifyAction.CREATE, null);
         lst11_2.getValue().add(lf111_2);
 
         // cont111_2
-        MutableCompositeNode cont111_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111","simple:yang:types","2013-11-5"),
-                lst11_2, null, ModifyAction.CREATE, null);
+        MutableCompositeNode cont111_2 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont111", "simple:yang:types", "2013-11-5"), lst11_2, null, ModifyAction.CREATE,
+                null);
         lst11_2.getValue().add(cont111_2);
 
-        MutableSimpleNode<?> lflst1111_2_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lflst1111","simple:yang:types","2013-11-5"),
-                cont111_2, 1024, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lflst1111_2_2 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lflst1111", "simple:yang:types", "2013-11-5"), cont111_2, 1024,
+                ModifyAction.CREATE, null);
         cont111_2.getValue().add(lflst1111_2_2);
-        MutableSimpleNode<?> lflst1111_2_3 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lflst1111","simple:yang:types","2013-11-5"),
-                cont111_2, 4096, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lflst1111_2_3 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lflst1111", "simple:yang:types", "2013-11-5"), cont111_2, 4096,
+                ModifyAction.CREATE, null);
         cont111_2.getValue().add(lflst1111_2_3);
 
         // lst1111_2
-        MutableCompositeNode lst1111_2_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
-                cont111_2, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst1111_2_1 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst1111", "simple:yang:types", "2013-11-5"), cont111_2, null,
+                ModifyAction.CREATE, null);
         cont111_2.getValue().add(lst1111_2_1);
-        MutableSimpleNode<?> lf1111B_2_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111B","simple:yang:types","2013-11-5"),
-                lst1111_2_1, (short) 4, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1111B_2_1 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf1111B", "simple:yang:types", "2013-11-5"), lst1111_2_1, (short) 4,
+                ModifyAction.CREATE, null);
         lst1111_2_1.getValue().add(lf1111B_2_1);
         lst1111_2_1.init();
 
-        MutableCompositeNode lst1111_2_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
-                cont111_2, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst1111_2_2 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst1111", "simple:yang:types", "2013-11-5"), cont111_2, null,
+                ModifyAction.CREATE, null);
         cont111_2.getValue().add(lst1111_2_2);
-        MutableSimpleNode<?> lf1111A_2_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111A","simple:yang:types","2013-11-5"),
-                lst1111_2_2, "lf1111A str12", ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1111A_2_2 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf1111A", "simple:yang:types", "2013-11-5"), lst1111_2_2, "lf1111A str12",
+                ModifyAction.CREATE, null);
         lst1111_2_2.getValue().add(lf1111A_2_2);
         lst1111_2_2.init();
         // :lst1111_2
@@ -630,8 +639,9 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
         cont111_2.init();
         // :cont111_2
 
-        MutableCompositeNode lst112_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst112","simple:yang:types","2013-11-5"), lst11_2,
-                null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst112_2 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst112", "simple:yang:types", "2013-11-5"), lst11_2, null, ModifyAction.CREATE,
+                null);
         lst11_2.getValue().add(lst112_2);
         lst112_2.init();
         lst11_2.init();
@@ -639,26 +649,31 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
         // :lst11_2
 
         // lst11_3
-        MutableCompositeNode lst11_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1,
-                null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst11_3 = NodeFactory
+                .createMutableCompositeNode(TestUtils.buildQName("lst11", "simple:yang:types", "2013-11-5"), cont1,
+                        null, ModifyAction.CREATE, null);
         cont1.getValue().add(lst11_3);
 
-        MutableSimpleNode<?> lf111_3 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111","simple:yang:types","2013-11-5"), lst11_3,
-                (short) 3, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf111_3 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf111", "simple:yang:types", "2013-11-5"), lst11_3, (short) 3,
+                ModifyAction.CREATE, null);
         lst11_3.getValue().add(lf111_3);
 
         // cont111_3
-        MutableCompositeNode cont111_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111","simple:yang:types","2013-11-5"),
-                lst11_3, null, ModifyAction.CREATE, null);
+        MutableCompositeNode cont111_3 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont111", "simple:yang:types", "2013-11-5"), lst11_3, null, ModifyAction.CREATE,
+                null);
         lst11_3.getValue().add(cont111_3);
 
-        MutableCompositeNode lst1111_3_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
-                cont111_3, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst1111_3_1 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst1111", "simple:yang:types", "2013-11-5"), cont111_3, null,
+                ModifyAction.CREATE, null);
         cont111_3.getValue().add(lst1111_3_1);
         lst1111_3_1.init();
 
-        MutableCompositeNode lst1111_3_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
-                cont111_3, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst1111_3_2 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst1111", "simple:yang:types", "2013-11-5"), cont111_3, null,
+                ModifyAction.CREATE, null);
         cont111_3.getValue().add(lst1111_3_2);
         lst1111_3_2.init();
 
index 21590ecb335fa81c309012bc34b92c1975da169c..0d0ce5cdd36908e458e50ac242ef356d4008287e 100644 (file)
@@ -10,9 +10,7 @@ package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.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.StructuredDataToJsonProvider;
@@ -29,9 +27,8 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test when some data are in one case node and other in another. This isn't
-     * correct. Next Json validator should return error because nodes has to be
-     * from one case below concrete choice.
+     * Test when some data are in one case node and other in another. This isn't correct. Next Json validator should
+     * return error because nodes has to be from one case below concrete choice.
      *
      */
     @Test
@@ -40,10 +37,9 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test when some data are in one case node and other in another.
-     * Additionally data are loadef from various choices. This isn't correct.
-     * Next Json validator should return error because nodes has to be from one
-     * case below concrete choice.
+     * Test when some data are in one case node and other in another. Additionally data are loadef from various choices.
+     * This isn't correct. Next Json validator should return error because nodes has to be from one case below concrete
+     * choice.
      *
      */
     @Test
@@ -53,8 +49,8 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test when second level data are red first, then first and at the end
-     * third level. Level represents pass through couple choice-case
+     * Test when second level data are red first, then first and at the end third level. Level represents pass through
+     * couple choice-case
      */
 
     @Test
@@ -103,8 +99,8 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test whether is possible to find data schema for node which is specified
-     * as dirrect subnode of choice (case without CASE key word)
+     * Test whether is possible to find data schema for node which is specified as dirrect subnode of choice (case
+     * without CASE key word)
      */
     @Test
     public void nodeSchemasInCaseNotDefinedWithCaseKeyword() {
index 93d32a14992e9df0209be9409cbea91074db514a..4b8b71440a7688334897bafc3c3117e8e2dfb937 100644 (file)
@@ -13,10 +13,12 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.fail;
 
+import com.google.common.collect.Maps;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
 import java.io.IOException;
 import java.io.StringReader;
 import java.util.Map;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
@@ -27,10 +29,6 @@ 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;
 
-import com.google.common.collect.Maps;
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonToken;
-
 public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader {
 
     static abstract class LeafVerifier {
@@ -38,15 +36,15 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
         Object expectedValue;
         JsonToken expectedToken;
 
-        LeafVerifier( Object expectedValue, JsonToken expectedToken ) {
+        LeafVerifier(Object expectedValue, JsonToken expectedToken) {
             this.expectedValue = expectedValue;
             this.expectedToken = expectedToken;
         }
 
-        abstract Object getActualValue( JsonReader reader ) throws IOException;
+        abstract Object getActualValue(JsonReader reader) throws IOException;
 
-        void verify( JsonReader reader, String keyName ) throws IOException {
-            assertEquals( "Json value for key " + keyName, expectedValue, getActualValue( reader ) );
+        void verify(JsonReader reader, String keyName) throws IOException {
+            assertEquals("Json value for key " + keyName, expectedValue, getActualValue(reader));
         }
 
         JsonToken expectedTokenType() {
@@ -56,31 +54,29 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
 
     static class BooleanVerifier extends LeafVerifier {
 
-        public BooleanVerifier( boolean expected ) {
-            super( expected, JsonToken.BOOLEAN );
+        public BooleanVerifier(boolean expected) {
+            super(expected, JsonToken.BOOLEAN);
         }
 
         @Override
-        Object getActualValue( JsonReader reader ) throws IOException {
+        Object getActualValue(JsonReader reader) throws IOException {
             return reader.nextBoolean();
         }
     }
 
     static class NumberVerifier extends LeafVerifier {
 
-        public NumberVerifier( Number expected ) {
-            super( expected, JsonToken.NUMBER );
+        public NumberVerifier(Number expected) {
+            super(expected, JsonToken.NUMBER);
         }
 
         @Override
-        Object getActualValue( JsonReader reader ) throws IOException {
-            if( expectedValue instanceof Double ) {
+        Object getActualValue(JsonReader reader) throws IOException {
+            if (expectedValue instanceof Double) {
                 return reader.nextDouble();
-            }
-            else if( expectedValue instanceof Long ) {
+            } else if (expectedValue instanceof Long) {
                 return reader.nextLong();
-            }
-            else if( expectedValue instanceof Integer ) {
+            } else if (expectedValue instanceof Integer) {
                 return reader.nextInt();
             }
 
@@ -90,12 +86,12 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
 
     static class StringVerifier extends LeafVerifier {
 
-        StringVerifier( String expected ) {
-            super( expected, JsonToken.STRING );
+        StringVerifier(String expected) {
+            super(expected, JsonToken.STRING);
         }
 
         @Override
-        Object getActualValue( JsonReader reader ) throws IOException {
+        Object getActualValue(JsonReader reader) throws IOException {
             return reader.nextString();
         }
     }
@@ -103,11 +99,11 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
     static class EmptyVerifier extends LeafVerifier {
 
         EmptyVerifier() {
-            super( null, null );
+            super(null, null);
         }
 
         @Override
-        Object getActualValue( JsonReader reader ) throws IOException {
+        Object getActualValue(JsonReader reader) throws IOException {
             reader.beginArray();
             reader.nextNull();
             reader.endArray();
@@ -119,68 +115,68 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
     static class ComplexAnyXmlVerifier extends LeafVerifier {
 
         ComplexAnyXmlVerifier() {
-            super( null, JsonToken.BEGIN_OBJECT );
+            super(null, JsonToken.BEGIN_OBJECT);
         }
 
         @Override
-        void verify( JsonReader reader, String keyName ) throws IOException {
+        void verify(JsonReader reader, String keyName) throws IOException {
 
             reader.beginObject();
             String innerKey = reader.nextName();
-            assertEquals( "Json reader child key for " + keyName, "data", innerKey );
-            assertEquals( "Json token type for key " + innerKey, JsonToken.BEGIN_OBJECT, reader.peek() );
+            assertEquals("Json reader child key for " + keyName, "data", innerKey);
+            assertEquals("Json token type for key " + innerKey, JsonToken.BEGIN_OBJECT, reader.peek());
 
             reader.beginObject();
-            verifyLeaf( reader, innerKey, "leaf1", "leaf1-value" );
-            verifyLeaf( reader, innerKey, "leaf2", "leaf2-value" );
+            verifyLeaf(reader, innerKey, "leaf1", "leaf1-value");
+            verifyLeaf(reader, innerKey, "leaf2", "leaf2-value");
 
             String nextName = reader.nextName();
-            assertEquals( "Json reader child key for " + innerKey, "leaf-list", nextName );
+            assertEquals("Json reader child key for " + innerKey, "leaf-list", nextName);
             reader.beginArray();
-            assertEquals( "Json value for key " + nextName, "leaf-list-value1", reader.nextString() );
-            assertEquals( "Json value for key " + nextName, "leaf-list-value2", reader.nextString() );
+            assertEquals("Json value for key " + nextName, "leaf-list-value1", reader.nextString());
+            assertEquals("Json value for key " + nextName, "leaf-list-value2", reader.nextString());
             reader.endArray();
 
             nextName = reader.nextName();
-            assertEquals( "Json reader child key for " + innerKey, "list", nextName );
+            assertEquals("Json reader child key for " + innerKey, "list", nextName);
             reader.beginArray();
-            verifyNestedLists( reader, 1 );
-            verifyNestedLists( reader, 3 );
+            verifyNestedLists(reader, 1);
+            verifyNestedLists(reader, 3);
             reader.endArray();
 
             reader.endObject();
             reader.endObject();
         }
 
-        void verifyNestedLists( JsonReader reader, int leafNum ) throws IOException {
+        void verifyNestedLists(JsonReader reader, int leafNum) throws IOException {
             reader.beginObject();
 
             String nextName = reader.nextName();
-            assertEquals( "Json reader next name", "nested-list", nextName );
+            assertEquals("Json reader next name", "nested-list", nextName);
 
             reader.beginArray();
 
             reader.beginObject();
-            verifyLeaf( reader, "nested-list", "nested-leaf", "nested-value" + leafNum++ );
+            verifyLeaf(reader, "nested-list", "nested-leaf", "nested-value" + leafNum++);
             reader.endObject();
 
             reader.beginObject();
-            verifyLeaf( reader, "nested-list", "nested-leaf", "nested-value" + leafNum );
+            verifyLeaf(reader, "nested-list", "nested-leaf", "nested-value" + leafNum);
             reader.endObject();
 
             reader.endArray();
             reader.endObject();
         }
 
-        void verifyLeaf( JsonReader reader, String parent, String name, String value ) throws IOException {
+        void verifyLeaf(JsonReader reader, String parent, String name, String value) throws IOException {
             String nextName = reader.nextName();
-            assertEquals( "Json reader child key for " + parent, name, nextName );
-            assertEquals( "Json token type for key " + parent, JsonToken.STRING, reader.peek() );
-            assertEquals( "Json value for key " + nextName, value, reader.nextString() );
+            assertEquals("Json reader child key for " + parent, name, nextName);
+            assertEquals("Json token type for key " + parent, JsonToken.STRING, reader.peek());
+            assertEquals("Json value for key " + nextName, value, reader.nextString());
         }
 
         @Override
-        Object getActualValue( JsonReader reader ) throws IOException {
+        Object getActualValue(JsonReader reader) throws IOException {
             return null;
         }
     }
@@ -199,7 +195,7 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
         TestUtils.normalizeCompositeNode(compositeNode, modules, "simple-data-types:cont");
 
         String jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode,
-                    StructuredDataToJsonProvider.INSTANCE);
+                StructuredDataToJsonProvider.INSTANCE);
 
         assertNotNull(jsonOutput);
 
@@ -236,68 +232,68 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
     private void jsonReadContElements(JsonReader jReader) throws IOException {
         jReader.beginObject();
 
-        Map<String,LeafVerifier> expectedMap = Maps.newHashMap();
-        expectedMap.put( "lfnint8Min", new NumberVerifier( Integer.valueOf( -128 ) ) );
-        expectedMap.put( "lfnint8Max", new NumberVerifier( Integer.valueOf( 127 ) ) );
-        expectedMap.put( "lfnint16Min", new NumberVerifier( Integer.valueOf( -32768 ) ) );
-        expectedMap.put( "lfnint16Max", new NumberVerifier( Integer.valueOf( 32767 ) ) );
-        expectedMap.put( "lfnint32Min", new NumberVerifier( Integer.valueOf( -2147483648 ) ) );
-        expectedMap.put( "lfnint32Max", new NumberVerifier( Long.valueOf( 2147483647 ) ) );
-        expectedMap.put( "lfnint64Min", new NumberVerifier( Long.valueOf( -9223372036854775808L ) ) );
-        expectedMap.put( "lfnint64Max", new NumberVerifier( Long.valueOf( 9223372036854775807L ) ) );
-        expectedMap.put( "lfnuint8Max", new NumberVerifier( Integer.valueOf( 255 ) ) );
-        expectedMap.put( "lfnuint16Max", new NumberVerifier( Integer.valueOf( 65535 ) ) );
-        expectedMap.put( "lfnuint32Max", new NumberVerifier( Long.valueOf( 4294967295L ) ) );
-        expectedMap.put( "lfstr", new StringVerifier( "lfstr" ) );
-        expectedMap.put( "lfstr1", new StringVerifier( "" ) );
-        expectedMap.put( "lfbool1", new BooleanVerifier( true ) );
-        expectedMap.put( "lfbool2", new BooleanVerifier( false ) );
-        expectedMap.put( "lfbool3", new BooleanVerifier( false ) );
-        expectedMap.put( "lfdecimal1", new NumberVerifier( new Double( 43.32 ) ) );
-        expectedMap.put( "lfdecimal2", new NumberVerifier( new Double( -0.43 ) ) );
-        expectedMap.put( "lfdecimal3", new NumberVerifier( new Double( 43 ) ) );
-        expectedMap.put( "lfdecimal4", new NumberVerifier( new Double( 43E3 ) ) );
-        expectedMap.put( "lfdecimal6", new NumberVerifier( new Double( 33.12345 ) ) );
-        expectedMap.put( "lfenum", new StringVerifier( "enum3" ) );
-        expectedMap.put( "lfbits", new StringVerifier( "bit3 bit2" ) );
-        expectedMap.put( "lfbinary", new StringVerifier( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" ) );
-        expectedMap.put( "lfunion1", new StringVerifier( "324" ) );
-        expectedMap.put( "lfunion2", new StringVerifier( "33.3" ) );
-        expectedMap.put( "lfunion3", new StringVerifier( "55" ) );
-        expectedMap.put( "lfunion4", new StringVerifier( "true" ) );
-        expectedMap.put( "lfunion5", new StringVerifier( "true" ) );
-        expectedMap.put( "lfunion6", new StringVerifier( "10" ) );
-        expectedMap.put( "lfunion7", new StringVerifier( "" ) );
-        expectedMap.put( "lfunion8", new StringVerifier( "" ) );
-        expectedMap.put( "lfunion9", new StringVerifier( "" ) );
-        expectedMap.put( "lfunion10", new StringVerifier( "bt1" ) );
-        expectedMap.put( "lfunion11", new StringVerifier( "33" ) );
-        expectedMap.put( "lfunion12", new StringVerifier( "false" ) );
-        expectedMap.put( "lfunion13", new StringVerifier( "b1" ) );
-        expectedMap.put( "lfunion14", new StringVerifier( "zero" ) );
-        expectedMap.put( "lfempty", new EmptyVerifier() );
-        expectedMap.put( "identityref1", new StringVerifier( "simple-data-types:iden" ) );
-        expectedMap.put( "complex-any", new ComplexAnyXmlVerifier() );
-        expectedMap.put( "simple-any", new StringVerifier( "simple" ) );
-        expectedMap.put( "empty-any", new StringVerifier( "" ) );
+        Map<String, LeafVerifier> expectedMap = Maps.newHashMap();
+        expectedMap.put("lfnint8Min", new NumberVerifier(Integer.valueOf(-128)));
+        expectedMap.put("lfnint8Max", new NumberVerifier(Integer.valueOf(127)));
+        expectedMap.put("lfnint16Min", new NumberVerifier(Integer.valueOf(-32768)));
+        expectedMap.put("lfnint16Max", new NumberVerifier(Integer.valueOf(32767)));
+        expectedMap.put("lfnint32Min", new NumberVerifier(Integer.valueOf(-2147483648)));
+        expectedMap.put("lfnint32Max", new NumberVerifier(Long.valueOf(2147483647)));
+        expectedMap.put("lfnint64Min", new NumberVerifier(Long.valueOf(-9223372036854775808L)));
+        expectedMap.put("lfnint64Max", new NumberVerifier(Long.valueOf(9223372036854775807L)));
+        expectedMap.put("lfnuint8Max", new NumberVerifier(Integer.valueOf(255)));
+        expectedMap.put("lfnuint16Max", new NumberVerifier(Integer.valueOf(65535)));
+        expectedMap.put("lfnuint32Max", new NumberVerifier(Long.valueOf(4294967295L)));
+        expectedMap.put("lfstr", new StringVerifier("lfstr"));
+        expectedMap.put("lfstr1", new StringVerifier(""));
+        expectedMap.put("lfbool1", new BooleanVerifier(true));
+        expectedMap.put("lfbool2", new BooleanVerifier(false));
+        expectedMap.put("lfbool3", new BooleanVerifier(false));
+        expectedMap.put("lfdecimal1", new NumberVerifier(new Double(43.32)));
+        expectedMap.put("lfdecimal2", new NumberVerifier(new Double(-0.43)));
+        expectedMap.put("lfdecimal3", new NumberVerifier(new Double(43)));
+        expectedMap.put("lfdecimal4", new NumberVerifier(new Double(43E3)));
+        expectedMap.put("lfdecimal6", new NumberVerifier(new Double(33.12345)));
+        expectedMap.put("lfenum", new StringVerifier("enum3"));
+        expectedMap.put("lfbits", new StringVerifier("bit3 bit2"));
+        expectedMap.put("lfbinary", new StringVerifier("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"));
+        expectedMap.put("lfunion1", new StringVerifier("324"));
+        expectedMap.put("lfunion2", new StringVerifier("33.3"));
+        expectedMap.put("lfunion3", new StringVerifier("55"));
+        expectedMap.put("lfunion4", new StringVerifier("true"));
+        expectedMap.put("lfunion5", new StringVerifier("true"));
+        expectedMap.put("lfunion6", new StringVerifier("10"));
+        expectedMap.put("lfunion7", new StringVerifier(""));
+        expectedMap.put("lfunion8", new StringVerifier(""));
+        expectedMap.put("lfunion9", new StringVerifier(""));
+        expectedMap.put("lfunion10", new StringVerifier("bt1"));
+        expectedMap.put("lfunion11", new StringVerifier("33"));
+        expectedMap.put("lfunion12", new StringVerifier("false"));
+        expectedMap.put("lfunion13", new StringVerifier("b1"));
+        expectedMap.put("lfunion14", new StringVerifier("zero"));
+        expectedMap.put("lfempty", new EmptyVerifier());
+        expectedMap.put("identityref1", new StringVerifier("simple-data-types:iden"));
+        expectedMap.put("complex-any", new ComplexAnyXmlVerifier());
+        expectedMap.put("simple-any", new StringVerifier("simple"));
+        expectedMap.put("empty-any", new StringVerifier(""));
 
         while (jReader.hasNext()) {
             String keyName = jReader.nextName();
             JsonToken peek = jReader.peek();
 
-            LeafVerifier verifier = expectedMap.remove( keyName );
-            assertNotNull( "Found unexpected leaf: " + keyName , verifier );
+            LeafVerifier verifier = expectedMap.remove(keyName);
+            assertNotNull("Found unexpected leaf: " + keyName, verifier);
 
             JsonToken expToken = verifier.expectedTokenType();
-            if( expToken != null ) {
-                assertEquals( "Json token type for key " + keyName, expToken, peek );
+            if (expToken != null) {
+                assertEquals("Json token type for key " + keyName, expToken, peek);
             }
 
-            verifier.verify( jReader, keyName );
+            verifier.verify(jReader, keyName);
         }
 
-        if( !expectedMap.isEmpty() ) {
-            fail( "Missing leaf nodes in Json output: " +expectedMap.keySet() );
+        if (!expectedMap.isEmpty()) {
+            fail("Missing leaf nodes in Json output: " + expectedMap.keySet());
         }
 
         jReader.endObject();
@@ -307,15 +303,13 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
     public void testBadData() throws Exception {
 
         try {
-            CompositeNode compositeNode = TestUtils.readInputToCnSn(
-                                               "/cnsn-to-json/simple-data-types/xml/bad-data.xml",
-                                               XmlToCompositeNodeProvider.INSTANCE);
+            CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/bad-data.xml",
+                    XmlToCompositeNodeProvider.INSTANCE);
 
             TestUtils.normalizeCompositeNode(compositeNode, modules, "simple-data-types:cont");
-            fail( "Expected RestconfDocumentedException" );
-        }
-        catch( RestconfDocumentedException e ) {
-            assertEquals( "getErrorTag", ErrorTag.INVALID_VALUE, e.getErrors().get( 0 ).getErrorTag() );
+            fail("Expected RestconfDocumentedException");
+        } catch (RestconfDocumentedException e) {
+            assertEquals("getErrorTag", ErrorTag.INVALID_VALUE, e.getErrors().get(0).getErrorTag());
         }
     }
 }
index fdd3aa6684303babcabc9c849792e37c6cbf758e..506ca847a936c4abc006c099b02f970a6022fe36 100644 (file)
@@ -13,9 +13,7 @@ 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;
@@ -74,14 +72,16 @@ public class CnSnToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     private CompositeNode prepareCompositeNode(final Object value) {
-        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont","identityref:module","2013-12-2"), null, null,
-                ModifyAction.CREATE, null);
-        MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont1","identityref:module","2013-12-2"), cont, null,
-                ModifyAction.CREATE, null);
+        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont", "identityref:module", "2013-12-2"), null, null, ModifyAction.CREATE, null);
+        MutableCompositeNode cont1 = NodeFactory
+                .createMutableCompositeNode(TestUtils.buildQName("cont1", "identityref:module", "2013-12-2"), cont,
+                        null, ModifyAction.CREATE, null);
         cont.getValue().add(cont1);
 
-        MutableSimpleNode<?> lf1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1","identityref:module","2013-12-2"), cont1, value,
-                ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1 = NodeFactory
+                .createMutableSimpleNode(TestUtils.buildQName("lf1", "identityref:module", "2013-12-2"), cont1, value,
+                        ModifyAction.CREATE, null);
 
         cont1.getValue().add(lf1);
         cont1.init();
index 050a9925ff3f7f767af0c371ef651d2d3e0ba7a5..50c834b1ffee46f96787d73ac47c9f6e49d6ffd4 100644 (file)
@@ -12,10 +12,8 @@ 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;
@@ -147,7 +145,8 @@ public class CnSnToJsonIncorrectTopLevelTest extends YangAndXmlAndDataSchemaLoad
     @Test
     public void incorrectTopLevelElementTest() {
 
-        CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml", XmlToCompositeNodeProvider.INSTANCE);
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml",
+                XmlToCompositeNodeProvider.INSTANCE);
         DataSchemaNode incorrectDataSchema = null;
         incorrectDataSchema = new IncorrectDataSchema();
 
index 21a46a6cc32b60de0e3db3c9c74e71c96e5385ec..6e41dcb57769b6fd633edb2bea9ea0ede1c9014a 100644 (file)
@@ -13,9 +13,7 @@ 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;
@@ -50,8 +48,8 @@ public class CnSnToJsonLeafrefType extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Tests case when reference to not existing element is present. In this
-     * case value from single node is printed as string.
+     * 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() {
@@ -60,8 +58,7 @@ public class CnSnToJsonLeafrefType extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Tests case when non leaf element is referenced. In this case value from
-     * single node is printed as string.
+     * Tests case when non leaf element is referenced. In this case value from single node is printed as string.
      */
     @Test
     public void leafrefToNotLeafTest() {
index 3f89c97367efd2f849802a61d5e4fec1f12149f1..3ca29c8d65cd485002ef8b46ad7b675d4a4bc581 100644 (file)
@@ -46,14 +46,12 @@ public class CnSnToJsonNotExistingLeafTypeTest extends YangAndXmlAndDataSchemaLo
     @Test
     public void incorrectTopLevelElementTest() throws WebApplicationException, IOException {
         String jsonOutput = null;
-        jsonOutput = TestUtils
-                .writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
-                        Collections.<Module>emptySet(), prepareDataSchemaNode(),
-                        StructuredDataToJsonProvider.INSTANCE);
+        jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
+                Collections.<Module> emptySet(), prepareDataSchemaNode(), StructuredDataToJsonProvider.INSTANCE);
         assertNotNull(jsonOutput);
 
-//      pattern for e.g. >    "lf1"   : ""    < or >"lf1":""<
-        assertTrue(containsStringData(jsonOutput, "\"lf1\"",":","\"\""));
+        // pattern for e.g. > "lf1" : "" < or >"lf1":""<
+        assertTrue(containsStringData(jsonOutput, "\"lf1\"", ":", "\"\""));
     }
 
     private CompositeNode prepareCompositeNode() {
index 3d25955b3caae0bff5a51b5dec49f53b270160e5..eb6a5b9e00f7c7af65d2398bd2e21e87f650fe9f 100644 (file)
@@ -29,8 +29,7 @@ public class CnSnToJsonWithAugmentTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test of json output when as input are specified composite node with empty
-     * data + YANG file
+     * Test of json output when as input are specified composite node with empty data + YANG file
      */
     @Test
     public void augmentedElementsToJson() {
@@ -46,12 +45,12 @@ public class CnSnToJsonWithAugmentTest extends YangAndXmlAndDataSchemaLoader {
         }
         assertNotNull(jsonOutput);
 
-        assertTrue(containsStringData(jsonOutput,"\"augment-leaf:lf2\"",":", "\"lf2\""));
-        assertTrue(containsStringData(jsonOutput,"\"augment-container:cont1\"",":", "\\{"));
-        assertTrue(containsStringData(jsonOutput,"\"augment-container:lf11\"",":", "\"lf11\""));
-        assertTrue(containsStringData(jsonOutput,"\"augment-list:lst1\"",":", "\\["));
-        assertTrue(containsStringData(jsonOutput,"\"augment-list:lf11\"",":", "\"lf1_1\""));
-        assertTrue(containsStringData(jsonOutput,"\"augment-list:lf11\"",":", "\"lf1_2\""));
-        assertTrue(containsStringData(jsonOutput,"\"augment-leaflist:lflst1\"",":", "\\["));
+        assertTrue(containsStringData(jsonOutput, "\"augment-leaf:lf2\"", ":", "\"lf2\""));
+        assertTrue(containsStringData(jsonOutput, "\"augment-container:cont1\"", ":", "\\{"));
+        assertTrue(containsStringData(jsonOutput, "\"augment-container:lf11\"", ":", "\"lf11\""));
+        assertTrue(containsStringData(jsonOutput, "\"augment-list:lst1\"", ":", "\\["));
+        assertTrue(containsStringData(jsonOutput, "\"augment-list:lf11\"", ":", "\"lf1_1\""));
+        assertTrue(containsStringData(jsonOutput, "\"augment-list:lf11\"", ":", "\"lf1_2\""));
+        assertTrue(containsStringData(jsonOutput, "\"augment-leaflist:lflst1\"", ":", "\\["));
     }
 }
index 052bb1a2be762ffca684a54109f724bd4d188ce9..a84fc79b86fbc9bb1d028859b629aeb1ecbfe622 100644 (file)
@@ -13,9 +13,7 @@ import java.io.IOException;
 import java.net.URISyntaxException;
 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;
index 086e648097294354cb8a34baca155581397dad15..3ab880fe7e19a5eb156608e8c34435819ad6c568 100644 (file)
@@ -12,9 +12,7 @@ import static org.junit.Assert.assertNotNull;
 import java.io.IOException;
 import java.net.URI;
 import java.net.URISyntaxException;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
@@ -26,9 +24,8 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
 /**
  *
- * 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
+ * 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 CnSnInstanceIdentifierToXmlTest extends YangAndXmlAndDataSchemaLoader {
@@ -40,7 +37,7 @@ public class CnSnInstanceIdentifierToXmlTest extends YangAndXmlAndDataSchemaLoad
 
     @Test
     public void snAsYangInstanceIdentifier() throws WebApplicationException, IOException, URISyntaxException {
-        CompositeNode cnSnData = prepareCnStructForYangData( );
+        CompositeNode cnSnData = prepareCnStructForYangData();
         String xmlOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSnData, modules, dataSchemaNode,
                 StructuredDataToXmlProvider.INSTANCE);
         assertNotNull(xmlOutput);
index 2ada6e13e9a64c2e62101f693027e3686645d025..800e2d3b486998e0993a136a0e7b0a1de6551c4c 100644 (file)
@@ -11,9 +11,7 @@ import static org.junit.Assert.assertTrue;
 
 import java.io.IOException;
 import java.util.Collections;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
@@ -41,8 +39,8 @@ public class CnSnToXmlNotExistingLeafTypeTest {
 
         boolean nullPointerExceptionRaised = false;
         try {
-            TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
-                    Collections.<Module>emptySet(), prepareDataSchemaNode(), StructuredDataToXmlProvider.INSTANCE);
+            TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(), Collections.<Module> emptySet(),
+                    prepareDataSchemaNode(), StructuredDataToXmlProvider.INSTANCE);
         } catch (WebApplicationException | IOException e) {
             LOG.error("WebApplicationException or IOException was raised");
         } catch (NullPointerException e) {
index 30dc1161bf43841888f4d823e4c50450bf93a199..3d5fee3ab8aff5ef3adfde3dbbcdc91a9a13923e 100644 (file)
@@ -12,12 +12,12 @@ import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
+import com.google.common.base.Optional;
+import com.google.common.collect.Lists;
 import java.io.IOException;
 import java.util.List;
-
 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.StructuredDataToXmlProvider;
@@ -50,14 +50,10 @@ import org.opendaylight.yangtools.yang.model.util.Uint64;
 import org.opendaylight.yangtools.yang.model.util.Uint8;
 import org.opendaylight.yangtools.yang.model.util.UnionType;
 
-import com.google.common.base.Optional;
-import com.google.common.collect.Lists;
-
 /**
  *
- * 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
+ * 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 CnSnToXmlTest extends YangAndXmlAndDataSchemaLoader {
@@ -87,76 +83,77 @@ public class CnSnToXmlTest extends YangAndXmlAndDataSchemaLoader {
         serializeToXml(prepareLeafrefData(), "<lfBoolean>true</lfBoolean>", "<lfLfref>true</lfLfref>");
     }
 
-
     @Test
     public void snAsYangStringToXmlTest() {
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(StringType.getInstance()).deserialize("lfStr value"),
-                        "lfStr"), "<lfStr>lfStr value</lfStr>");
+                prepareCnStructForYangData(
+                        TypeDefinitionAwareCodec.from(StringType.getInstance()).deserialize("lfStr value"), "lfStr"),
+                "<lfStr>lfStr value</lfStr>");
     }
 
     @Test
     public void snAsYangInt8ToXmlTest() {
         String elName = "lfInt8";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int8.getInstance()).deserialize("14"), elName), "<"
-                        + elName + ">14</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int8.getInstance()).deserialize("14"), elName),
+                "<" + elName + ">14</" + elName + ">");
     }
 
     @Test
     public void snAsYangInt16ToXmlTest() {
         String elName = "lfInt16";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int16.getInstance()).deserialize("3000"), elName),
-                "<" + elName + ">3000</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int16.getInstance()).deserialize("3000"),
+                        elName), "<" + elName + ">3000</" + elName + ">");
     }
 
     @Test
     public void snAsYangInt32ToXmlTest() {
         String elName = "lfInt32";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int32.getInstance()).deserialize("201234"), elName),
-                "<" + elName + ">201234</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int32.getInstance()).deserialize("201234"),
+                        elName), "<" + elName + ">201234</" + elName + ">");
     }
 
     @Test
     public void snAsYangInt64ToXmlTest() {
         String elName = "lfInt64";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int64.getInstance()).deserialize("5123456789"),
-                        elName), "<" + elName + ">5123456789</" + elName + ">");
+                prepareCnStructForYangData(
+                        TypeDefinitionAwareCodec.from(Int64.getInstance()).deserialize("5123456789"), elName), "<"
+                        + elName + ">5123456789</" + elName + ">");
     }
 
     @Test
     public void snAsYangUint8ToXmlTest() {
         String elName = "lfUint8";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint8.getInstance()).deserialize("200"), elName),
-                "<" + elName + ">200</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint8.getInstance()).deserialize("200"),
+                        elName), "<" + elName + ">200</" + elName + ">");
     }
 
     @Test
     public void snAsYangUint16ToXmlTest() {
         String elName = "lfUint16";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint16.getInstance()).deserialize("4000"), elName),
-                "<" + elName + ">4000</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint16.getInstance()).deserialize("4000"),
+                        elName), "<" + elName + ">4000</" + elName + ">");
     }
 
     @Test
     public void snAsYangUint32ToXmlTest() {
         String elName = "lfUint32";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint32.getInstance()).deserialize("4123456789"),
-                        elName), "<" + elName + ">4123456789</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint32.getInstance())
+                        .deserialize("4123456789"), elName), "<" + elName + ">4123456789</" + elName + ">");
     }
 
     @Test
     public void snAsYangUint64ToXmlTest() {
         String elName = "lfUint64";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint64.getInstance()).deserialize("5123456789"),
-                        elName), "<" + elName + ">5123456789</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint64.getInstance())
+                        .deserialize("5123456789"), elName), "<" + elName + ">5123456789</" + elName + ">");
     }
 
     @Test
@@ -164,92 +161,87 @@ public class CnSnToXmlTest extends YangAndXmlAndDataSchemaLoader {
         String elName = "lfBinary";
         serializeToXml(
                 prepareCnStructForYangData(
-                        TypeDefinitionAwareCodec.from(BinaryType.getInstance())
-                        .deserialize("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"),
-                        elName), "<" + elName + ">ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567</"
-                                + elName + ">");
+                        TypeDefinitionAwareCodec.from(BinaryType.getInstance()).deserialize(
+                                "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"), elName), "<" + elName
+                        + ">ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567</" + elName + ">");
     }
 
     @Test
     public void snAsYangBitsToXmlTest() {
-        BitsTypeDefinition.Bit mockBit1 = mock( BitsTypeDefinition.Bit.class );
-        when( mockBit1.getName() ).thenReturn( "one" );
-        BitsTypeDefinition.Bit mockBit2 = mock( BitsTypeDefinition.Bit.class );
-        when( mockBit2.getName() ).thenReturn( "two" );
-        List<BitsTypeDefinition.Bit> bitList = Lists.newArrayList( mockBit1, mockBit2 );
+        BitsTypeDefinition.Bit mockBit1 = mock(BitsTypeDefinition.Bit.class);
+        when(mockBit1.getName()).thenReturn("one");
+        BitsTypeDefinition.Bit mockBit2 = mock(BitsTypeDefinition.Bit.class);
+        when(mockBit2.getName()).thenReturn("two");
+        List<BitsTypeDefinition.Bit> bitList = Lists.newArrayList(mockBit1, mockBit2);
 
         String elName = "lfBits";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(
-                        BitsType.create( mock( SchemaPath.class ), bitList ) )
-                        .deserialize("one two"), elName),
-                        "<" + elName + ">one two</" + elName + ">", "<" + elName + ">two one</" + elName + ">");
+                prepareCnStructForYangData(
+                        TypeDefinitionAwareCodec.from(BitsType.create(mock(SchemaPath.class), bitList)).deserialize(
+                                "one two"), elName), "<" + elName + ">one two</" + elName + ">", "<" + elName
+                        + ">two one</" + elName + ">");
     }
 
     @Test
     public void snAsYangEnumerationToXmlTest() {
-        EnumTypeDefinition.EnumPair mockEnum = mock( EnumTypeDefinition.EnumPair.class );
-        when( mockEnum.getName() ).thenReturn( "enum2" );
-        List<EnumPair> enumList = Lists.newArrayList( mockEnum );
+        EnumTypeDefinition.EnumPair mockEnum = mock(EnumTypeDefinition.EnumPair.class);
+        when(mockEnum.getName()).thenReturn("enum2");
+        List<EnumPair> enumList = Lists.newArrayList(mockEnum);
 
         String elName = "lfEnumeration";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(
-                        EnumerationType.create( mock( SchemaPath.class ), enumList,
-                                Optional.<EnumTypeDefinition.EnumPair>absent() ) )
-                                .deserialize("enum2"),
-                                elName), "<" + elName + ">enum2</" + elName + ">");
+                prepareCnStructForYangData(
+                        TypeDefinitionAwareCodec.from(
+                                EnumerationType.create(mock(SchemaPath.class), enumList,
+                                        Optional.<EnumTypeDefinition.EnumPair> absent())).deserialize("enum2"), elName),
+                "<" + elName + ">enum2</" + elName + ">");
     }
 
     @Test
     public void snAsYangEmptyToXmlTest() {
         String elName = "lfEmpty";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(EmptyType.getInstance()).deserialize(null), elName), "<"
-                        + elName + "/>");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(EmptyType.getInstance()).deserialize(null),
+                        elName), "<" + elName + "/>");
     }
 
     @Test
     public void snAsYangBooleanToXmlTest() {
         String elName = "lfBoolean";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("str"), elName),
-                "<" + elName + ">false</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("str"),
+                        elName), "<" + elName + ">false</" + elName + ">");
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("true"), elName),
-                "<" + elName + ">true</" + elName + ">");
+                prepareCnStructForYangData(
+                        TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("true"), elName), "<"
+                        + elName + ">true</" + elName + ">");
     }
 
     @Test
     public void snAsYangUnionToXmlTest() {
 
-        BitsTypeDefinition.Bit mockBit1 = mock( BitsTypeDefinition.Bit.class );
-        when( mockBit1.getName() ).thenReturn( "first" );
-        BitsTypeDefinition.Bit mockBit2 = mock( BitsTypeDefinition.Bit.class );
-        when( mockBit2.getName() ).thenReturn( "second" );
-        List<BitsTypeDefinition.Bit> bitList = Lists.newArrayList( mockBit1, mockBit2 );
+        BitsTypeDefinition.Bit mockBit1 = mock(BitsTypeDefinition.Bit.class);
+        when(mockBit1.getName()).thenReturn("first");
+        BitsTypeDefinition.Bit mockBit2 = mock(BitsTypeDefinition.Bit.class);
+        when(mockBit2.getName()).thenReturn("second");
+        List<BitsTypeDefinition.Bit> bitList = Lists.newArrayList(mockBit1, mockBit2);
 
-        List<TypeDefinition<?>> types = Lists.<TypeDefinition<?>>newArrayList(
-                Int8.getInstance(),
-                BitsType.create( mock( SchemaPath.class ) , bitList ),
-                BooleanType.getInstance() );
-        UnionType unionType = UnionType.create( types );
+        List<TypeDefinition<?>> types = Lists.<TypeDefinition<?>> newArrayList(Int8.getInstance(),
+                BitsType.create(mock(SchemaPath.class), bitList), BooleanType.getInstance());
+        UnionType unionType = UnionType.create(types);
 
         String elName = "lfUnion";
         String int8 = "15";
-        serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(int8), elName), "<"
-                        + elName + ">15</" + elName + ">");
+        serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(int8), elName),
+                "<" + elName + ">15</" + elName + ">");
 
         String bits = "first second";
-        serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bits), elName), "<"
-                        + elName + ">first second</" + elName + ">");
+        serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bits), elName),
+                "<" + elName + ">first second</" + elName + ">");
 
         String bool = "str";
-        serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bool), elName), "<"
-                        + elName + ">str</" + elName + ">");
+        serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bool), elName),
+                "<" + elName + ">str</" + elName + ">");
     }
 
     private void serializeToXml(final CompositeNode compositeNode, final String... xmlRepresentation)
index ac7fe20818f31fc7fbb5bfd24b4399b2113cadee..8e5449029c78dccaba89861feb71e018d22c6ab2 100644 (file)
@@ -10,9 +10,7 @@ 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;
@@ -26,9 +24,8 @@ 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
+ * 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 {
index f8d04c157f2e9d1678da36c6636bd872e05e4cc7..1e366dcaec88dd5171a191581a6877409afc696a 100644 (file)
@@ -14,9 +14,7 @@ import java.net.URI;
 import java.net.URISyntaxException;
 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.StructuredDataToXmlProvider;
@@ -31,7 +29,7 @@ public class CnSnToXmlWithDataFromSeveralModulesTest extends YangAndXmlAndDataSc
 
     @BeforeClass
     public static void initialize() {
-        dataLoad("/xml-to-cnsn/data-of-several-modules/yang",2,"module1","cont_m1");
+        dataLoad("/xml-to-cnsn/data-of-several-modules/yang", 2, "module1", "cont_m1");
     }
 
     @Test
@@ -40,19 +38,19 @@ public class CnSnToXmlWithDataFromSeveralModulesTest extends YangAndXmlAndDataSc
         String output = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCnSn(), modules, schemaContext,
                 StructuredDataToXmlProvider.INSTANCE);
 
-//         String output =
-//         String.format("<data>" +
-//                  "\n<cont_m1>" +
-//                         "\n\t<lf1_m1>" +
-//                             "\n\t\tlf1 m1 value" +
-//                             "\n\t</lf1_m1>" +
-//                         "\n</cont_m1>" +
-//                         "\n<cont_m2>" +
-//                             "\n\t<lf1_m2>" +
-//                                 "\n\t\tlf1 m2 value" +
-//                             "\n\t</lf1_m2>" +
-//                         "\n</cont_m2>" +
-//                     "\n</data>");
+        // String output =
+        // String.format("<data>" +
+        // "\n<cont_m1>" +
+        // "\n\t<lf1_m1>" +
+        // "\n\t\tlf1 m1 value" +
+        // "\n\t</lf1_m1>" +
+        // "\n</cont_m1>" +
+        // "\n<cont_m2>" +
+        // "\n\t<lf1_m2>" +
+        // "\n\t\tlf1 m2 value" +
+        // "\n\t</lf1_m2>" +
+        // "\n</cont_m2>" +
+        // "\n</data>");
 
         StringBuilder regex = new StringBuilder();
         regex.append("^");
@@ -61,7 +59,6 @@ public class CnSnToXmlWithDataFromSeveralModulesTest extends YangAndXmlAndDataSc
         regex.append(".*xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"");
         regex.append(".*>");
 
-
         regex.append(".*<contB_m1.*\\/>");
         regex.append(".*xmlns=\"module:one\"");
         regex.append(".*>");
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java
new file mode 100644 (file)
index 0000000..f4281c0
--- /dev/null
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.restconf.impl.input.to.cnsn.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.FileNotFoundException;
+import java.net.URI;
+import java.util.List;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+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.RestconfDocumentedException;
+import org.opendaylight.controller.sal.restconf.impl.RestconfError;
+import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
+import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
+import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
+import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
+import org.opendaylight.controller.sal.restconf.impl.test.DummyFuture;
+import org.opendaylight.controller.sal.restconf.impl.test.DummyFuture.Builder;
+import org.opendaylight.controller.sal.restconf.impl.test.DummyRpcResult;
+import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class RestPutListDataTest {
+
+    private static BrokerFacade brokerFacade;
+    private static RestconfImpl restconfImpl;
+    private static SchemaContext schemaContextTestModule;
+
+    private static final String TEST_MODULE_NS_STRING = "test:module";
+    private static final URI TEST_MODULE_NS;
+    private static final String TEST_MODULE_REVISION = "2014-01-09";
+
+    static {
+        TEST_MODULE_NS = URI.create("test:module");
+    }
+
+    @Before
+    public void initialize() throws FileNotFoundException {
+        ControllerContext controllerContext = ControllerContext.getInstance();
+        schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
+        controllerContext.setSchemas(schemaContextTestModule);
+        brokerFacade = mock(BrokerFacade.class);
+        restconfImpl = RestconfImpl.getInstance();
+        restconfImpl.setBroker(brokerFacade);
+        restconfImpl.setControllerContext(controllerContext);
+        Builder<TransactionStatus> futureBuilder = new DummyFuture.Builder<TransactionStatus>();
+        futureBuilder.rpcResult(new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
+                .build());
+        when(brokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
+                .thenReturn(futureBuilder.build());
+    }
+
+    /**
+     * Tests whether no exception is raised if number and values of keys in URI
+     * and payload are equal
+     */
+    @Test
+    public void testValidKeys() {
+        putListDataTest("key1value", "15", "key1value", (short) 15);
+    }
+
+    /**
+     * Tests whether an exception is raised if key values in URI and payload are
+     * different.
+     *
+     * The exception should be raised from validation method
+     * {@code RestconfImpl#validateListEqualityOfListInDataAndUri}
+     */
+    @Test
+    public void testUriAndPayloadKeysDifferent() {
+        try {
+            putListDataTest("key1value", "15", "key1value", (short) 16);
+            fail("RestconfDocumentedException expected");
+        } catch (RestconfDocumentedException e) {
+            verifyException(e, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+        }
+
+        try {
+            putListDataTest("key1value", "15", "key1value1", (short) 16);
+            fail("RestconfDocumentedException expected");
+        } catch (RestconfDocumentedException e) {
+            verifyException(e, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+        }
+    }
+
+    /**
+     * Tests whether an exception is raised if URI contains less key values then
+     * payload.
+     *
+     * The exception is raised during {@code InstanceIdentifier} instance is
+     * built from URI
+     */
+    @Test
+    public void testMissingKeysInUri() {
+        try {
+            putListDataTest("key1value", null, "key1value", (short) 15);
+            fail("RestconfDocumentedException expected");
+        } catch (RestconfDocumentedException e) {
+            verifyException(e, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
+        }
+    }
+
+    /**
+     * Tests whether an exception is raised if URI contains more key values then
+     * payload.
+     *
+     * The exception should be raised from validation method
+     * {@code RestconfImpl#validateListEqualityOfListInDataAndUri}
+     */
+    @Test
+    public void testMissingKeysInPayload() {
+        try {
+            putListDataTest("key1value", "15", "key1value", null);
+            fail("RestconfDocumentedException expected");
+        } catch (RestconfDocumentedException e) {
+            verifyException(e, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
+        }
+        try {
+            putListDataWithWrapperTest("key1value", "15", "key1value", null);
+            fail("RestconfDocumentedException expected");
+        } catch (RestconfDocumentedException e) {
+            // this exception is raised from RestconfImpl.normalizeCompositeNode()
+            verifyException(e, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
+        }
+
+    }
+
+    private void verifyException(final RestconfDocumentedException e, final ErrorType errorType, final ErrorTag errorTag) {
+        List<RestconfError> errors = e.getErrors();
+        assertEquals("getErrors() size", 1, errors.size());
+        assertEquals("RestconfError getErrorType()", errorType, errors.get(0).getErrorType());
+        assertEquals("RestconfError getErrorTag()", errorTag, errors.get(0).getErrorTag());
+    }
+
+    public void putListDataTest(final String uriKey1, final String uriKey2, final String payloadKey1,
+            final Short payloadKey2) {
+        QName lstWithCompositeKey = QName.create(TEST_MODULE_NS_STRING, TEST_MODULE_REVISION, "lst-with-composite-key");
+        QName key1 = QName.create(TEST_MODULE_NS_STRING, TEST_MODULE_REVISION, "key1");
+        QName key2 = QName.create(TEST_MODULE_NS_STRING, TEST_MODULE_REVISION, "key2");
+
+        CompositeNodeBuilder<ImmutableCompositeNode> payloadBuilder = ImmutableCompositeNode.builder();
+        payloadBuilder.setQName(lstWithCompositeKey).addLeaf(key1, payloadKey1);
+        if (payloadKey2 != null) {
+            payloadBuilder.addLeaf(key2, payloadKey2);
+        }
+
+        restconfImpl.updateConfigurationData(toUri(uriKey1, uriKey2), payloadBuilder.toInstance());
+    }
+
+    public void putListDataWithWrapperTest(final String uriKey1, final String uriKey2, final String payloadKey1,
+            final Short payloadKey2) {
+        CompositeNodeWrapper payloadBuilder = new CompositeNodeWrapper(TEST_MODULE_NS, "lst-with-composite-key");
+        payloadBuilder.addValue(new SimpleNodeWrapper(TEST_MODULE_NS, "key1", payloadKey1));
+        if (payloadKey2 != null) {
+            payloadBuilder.addValue(new SimpleNodeWrapper(TEST_MODULE_NS, "key2", payloadKey2));
+        }
+        restconfImpl.updateConfigurationData(toUri(uriKey1, uriKey2), payloadBuilder);
+    }
+
+    private String toUri(final String uriKey1, final String uriKey2) {
+        final StringBuilder uriBuilder = new StringBuilder("/test-module:lst-with-composite-key/");
+        uriBuilder.append(uriKey1);
+        if (uriKey2 != null) {
+            uriBuilder.append("/");
+            uriBuilder.append(uriKey2);
+        }
+        return uriBuilder.toString();
+    }
+
+}
index 0c9e95173fd3f1e309b6e512a90260eaf8bbb899..23b040a9a3846b6e273dedcb0fcb42e8c36ff5f4 100644 (file)
@@ -12,7 +12,6 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
 import java.util.List;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
index 79dd026fd0dc5cf21b69d7dae886070b009a5999..913e9f2d707bd310feb103313d53d5c8a83928df 100644 (file)
@@ -28,8 +28,7 @@ public class JsonLeafrefToCnSnTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * JSON values which represents leafref are always loaded to simple node as
-     * string
+     * JSON values which represents leafref are always loaded to simple node as string
      */
     @Test
     public void jsonIdentityrefToCompositeNode() {
index 47e329cc3ef11a4cdfc8842c9a1285a445989517..7b71e42ab8ed669516c4e724231628c8d6bd4908 100644 (file)
@@ -17,7 +17,6 @@ import java.io.InputStream;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
-
 import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
@@ -82,8 +81,8 @@ public class JsonToCnSnTest {
     }
 
     /**
-     * List contains 4 items and in every item are other elements. It is
-     * supposed that there should be: lf11, lflst11, cont11, lst11
+     * List contains 4 items and in every item are other elements. It is supposed that there should be: lf11, lflst11,
+     * cont11, lst11
      */
     @Test
     public void multipleItemsInListTest() {
@@ -116,14 +115,19 @@ public class JsonToCnSnTest {
     public void incorrectTopLevelElementsTest() {
         RestconfDocumentedException cause1 = null;
         try {
-            TestUtils.readInputToCnSn("/json-to-cnsn/wrong-top-level1.json", true, JsonToCompositeNodeProvider.INSTANCE);
+            TestUtils
+                    .readInputToCnSn("/json-to-cnsn/wrong-top-level1.json", true, JsonToCompositeNodeProvider.INSTANCE);
         } catch (RestconfDocumentedException e) {
             cause1 = e;
         }
 
         assertNotNull(cause1);
-        assertTrue(cause1.getErrors().get( 0 ).getErrorMessage().contains(
-            "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet."));
+        assertTrue(cause1
+                .getErrors()
+                .get(0)
+                .getErrorMessage()
+                .contains(
+                        "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet."));
 
         RestconfDocumentedException cause2 = null;
         try {
@@ -133,26 +137,29 @@ public class JsonToCnSnTest {
             cause2 = e;
         }
         assertNotNull(cause2);
-        assertTrue(cause2.getErrors().get( 0 ).getErrorMessage().contains(
-                                                     "Json Object should contain one element"));
+        assertTrue(cause2.getErrors().get(0).getErrorMessage().contains("Json Object should contain one element"));
 
         RestconfDocumentedException cause3 = null;
         try {
             TestUtils
 
-                    .readInputToCnSn("/json-to-cnsn/wrong-top-level3.json", true, JsonToCompositeNodeProvider.INSTANCE);
+            .readInputToCnSn("/json-to-cnsn/wrong-top-level3.json", true, JsonToCompositeNodeProvider.INSTANCE);
         } catch (RestconfDocumentedException e) {
             cause3 = e;
         }
         assertNotNull(cause3);
-        assertTrue(cause3.getErrors().get( 0 ).getErrorMessage().contains(
-            "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet."));
+        assertTrue(cause3
+                .getErrors()
+                .get(0)
+                .getErrorMessage()
+                .contains(
+                        "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet."));
 
     }
 
     /**
-     * if leaf list with no data is in json then no corresponding data is
-     * created in composite node. if leaf with no data then exception is raised
+     * if leaf list with no data is in json then no corresponding data is created in composite node. if leaf with no
+     * data then exception is raised
      */
     @Test
     public void emptyDataReadTest() {
@@ -172,7 +179,7 @@ public class JsonToCnSnTest {
         try {
             TestUtils.readInputToCnSn("/json-to-cnsn/empty-data1.json", true, JsonToCompositeNodeProvider.INSTANCE);
         } catch (RestconfDocumentedException e) {
-            reason = e.getErrors().get( 0 ).getErrorMessage();
+            reason = e.getErrors().get(0).getErrorMessage();
         }
 
         assertTrue(reason.contains("Expected value at line"));
@@ -180,17 +187,16 @@ public class JsonToCnSnTest {
     }
 
     @Test
-    public void testJsonBlankInput() throws Exception{
-        InputStream inputStream = new ByteArrayInputStream( "".getBytes() );
-        CompositeNode compositeNode =
-                JsonToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream);
-        assertNull( compositeNode );
+    public void testJsonBlankInput() throws Exception {
+        InputStream inputStream = new ByteArrayInputStream("".getBytes());
+        CompositeNode compositeNode = JsonToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null,
+                inputStream);
+        assertNull(compositeNode);
     }
 
     /**
-     * Tests whether namespace <b>stay unchanged</b> if concrete values are
-     * present in composite or simple node and if the method for update is
-     * called.
+     * Tests whether namespace <b>stay unchanged</b> if concrete values are present in composite or simple node and if
+     * the method for update is called.
      *
      */
     @Test
@@ -284,13 +290,14 @@ public class JsonToCnSnTest {
 
     }
 
-    private void simpleTest(final String jsonPath, final String yangPath, final String topLevelElementName, final String namespace,
-            final String moduleName) {
+    private void simpleTest(final String jsonPath, final String yangPath, final String topLevelElementName,
+            final String namespace, final String moduleName) {
         CompositeNode compNode = loadAndNormalizeData(jsonPath, yangPath, topLevelElementName, moduleName);
         verifyCompositeNode(compNode, namespace);
     }
 
-    private CompositeNode loadAndNormalizeData(final String jsonPath, final String yangPath, final String topLevelElementName, final String moduleName) {
+    private CompositeNode loadAndNormalizeData(final String jsonPath, final String yangPath,
+            final String topLevelElementName, final String moduleName) {
         CompositeNode compositeNode = TestUtils.readInputToCnSn(jsonPath, false, JsonToCompositeNodeProvider.INSTANCE);
         assertNotNull(compositeNode);
 
@@ -395,7 +402,7 @@ public class JsonToCnSnTest {
             TestUtils.readInputToCnSn("/json-to-cnsn/unsupported-json-format.json", true,
                     JsonToCompositeNodeProvider.INSTANCE);
         } catch (RestconfDocumentedException e) {
-            exceptionMessage = e.getErrors().get( 0 ).getErrorMessage();
+            exceptionMessage = e.getErrors().get(0).getErrorMessage();
         }
         assertTrue(exceptionMessage.contains("Root element of Json has to be Object"));
     }
index 19ca812f8e9a90c1aad698be0df347b2b651b26f..656427352aea0da2242910ba5a274b1d500e63f2 100644 (file)
@@ -7,6 +7,7 @@
  */
 
 package org.opendaylight.controller.sal.restconf.impl.test;
+
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertSame;
@@ -66,268 +67,252 @@ public class BrokerFacadeTest {
 
     BrokerFacade brokerFacade = BrokerFacade.getInstance();
 
-    CompositeNode dataNode = TestUtils.readInputToCnSn( "/parts/ietf-interfaces_interfaces.xml",
-                                                        XmlToCompositeNodeProvider.INSTANCE );
+    CompositeNode dataNode = TestUtils.readInputToCnSn("/parts/ietf-interfaces_interfaces.xml",
+            XmlToCompositeNodeProvider.INSTANCE);
 
-    QName qname = QName.create( "node" );
+    QName qname = QName.create("node");
 
-    InstanceIdentifier instanceID = InstanceIdentifier.builder().node( qname ).toInstance();
+    InstanceIdentifier instanceID = InstanceIdentifier.builder().node(qname).toInstance();
 
     @Before
     public void setUp() throws Exception {
-        MockitoAnnotations.initMocks( this );
+        MockitoAnnotations.initMocks(this);
 
-        brokerFacade.setDataService( dataBroker );
-        brokerFacade.setContext( mockConsumerSession );
+        brokerFacade.setDataService(dataBroker);
+        brokerFacade.setContext(mockConsumerSession);
     }
 
     @Test
     public void testReadConfigurationData() {
-        when( dataBroker.readConfigurationData( instanceID ) ).thenReturn( dataNode );
+        when(dataBroker.readConfigurationData(instanceID)).thenReturn(dataNode);
 
-        CompositeNode actualNode = brokerFacade.readConfigurationData( instanceID );
+        CompositeNode actualNode = brokerFacade.readConfigurationData(instanceID);
 
-        assertSame( "readConfigurationData", dataNode, actualNode );
+        assertSame("readConfigurationData", dataNode, actualNode);
     }
 
     @Test
     public void testReadConfigurationDataBehindMountPoint() {
-        when( mockMountInstance.readConfigurationData( instanceID ) ).thenReturn( dataNode );
+        when(mockMountInstance.readConfigurationData(instanceID)).thenReturn(dataNode);
 
-        CompositeNode actualNode = brokerFacade.readConfigurationDataBehindMountPoint(
-                                                                              mockMountInstance, instanceID );
+        CompositeNode actualNode = brokerFacade.readConfigurationDataBehindMountPoint(mockMountInstance, instanceID);
 
-        assertSame( "readConfigurationDataBehindMountPoint", dataNode, actualNode );
+        assertSame("readConfigurationDataBehindMountPoint", dataNode, actualNode);
     }
 
     @Test
     public void testReadOperationalData() {
-        when( dataBroker.readOperationalData( instanceID ) ).thenReturn( dataNode );
+        when(dataBroker.readOperationalData(instanceID)).thenReturn(dataNode);
 
-        CompositeNode actualNode = brokerFacade.readOperationalData( instanceID );
+        CompositeNode actualNode = brokerFacade.readOperationalData(instanceID);
 
-        assertSame( "readOperationalData", dataNode, actualNode );
+        assertSame("readOperationalData", dataNode, actualNode);
     }
 
     @Test
     public void testReadOperationalDataBehindMountPoint() {
-        when( mockMountInstance.readOperationalData( instanceID ) ).thenReturn( dataNode );
+        when(mockMountInstance.readOperationalData(instanceID)).thenReturn(dataNode);
 
-        CompositeNode actualNode = brokerFacade.readOperationalDataBehindMountPoint(
-                                                                              mockMountInstance, instanceID );
+        CompositeNode actualNode = brokerFacade.readOperationalDataBehindMountPoint(mockMountInstance, instanceID);
 
-        assertSame( "readOperationalDataBehindMountPoint", dataNode, actualNode );
+        assertSame("readOperationalDataBehindMountPoint", dataNode, actualNode);
     }
 
-    @Test(expected=RestconfDocumentedException.class)
+    @Test(expected = RestconfDocumentedException.class)
     public void testReadOperationalDataWithNoDataBroker() {
-        brokerFacade.setDataService( null );
+        brokerFacade.setDataService(null);
 
-        brokerFacade.readOperationalData( instanceID );
+        brokerFacade.readOperationalData(instanceID);
     }
 
     @SuppressWarnings("unchecked")
     @Test
     public void testInvokeRpc() throws Exception {
-        RpcResult<CompositeNode> expResult = mock( RpcResult.class );
-        Future<RpcResult<CompositeNode>> future = Futures.immediateFuture( expResult );
-        when( mockConsumerSession.rpc( qname, dataNode ) ).thenReturn( future );
+        RpcResult<CompositeNode> expResult = mock(RpcResult.class);
+        Future<RpcResult<CompositeNode>> future = Futures.immediateFuture(expResult);
+        when(mockConsumerSession.rpc(qname, dataNode)).thenReturn(future);
 
-        Future<RpcResult<CompositeNode>> actualFuture = brokerFacade.invokeRpc( qname, dataNode );
-        assertNotNull( "Future is null", actualFuture );
+        Future<RpcResult<CompositeNode>> actualFuture = brokerFacade.invokeRpc(qname, dataNode);
+        assertNotNull("Future is null", actualFuture);
         RpcResult<CompositeNode> actualResult = actualFuture.get();
 
-        assertSame( "invokeRpc", expResult, actualResult );
+        assertSame("invokeRpc", expResult, actualResult);
     }
 
-    @Test(expected=RestconfDocumentedException.class)
+    @Test(expected = RestconfDocumentedException.class)
     public void testInvokeRpcWithNoConsumerSession() {
-        brokerFacade.setContext( null );
+        brokerFacade.setContext(null);
 
-        brokerFacade.invokeRpc( qname, dataNode );
+        brokerFacade.invokeRpc(qname, dataNode);
     }
 
     @Test
     public void testCommitConfigurationDataPut() {
-        Future<RpcResult<TransactionStatus>> expFuture =  Futures.immediateFuture( null );
+        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
 
-        when( dataBroker.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.putConfigurationData( instanceID, dataNode );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        when(dataBroker.beginTransaction()).thenReturn(mockTransaction);
+        mockTransaction.putConfigurationData(instanceID, dataNode);
+        when(mockTransaction.commit()).thenReturn(expFuture);
 
-        Future<RpcResult<TransactionStatus>> actualFuture =
-                             brokerFacade.commitConfigurationDataPut( instanceID, dataNode );
+        Future<RpcResult<TransactionStatus>> actualFuture = brokerFacade.commitConfigurationDataPut(instanceID,
+                dataNode);
 
-        assertSame( "invokeRpc", expFuture, actualFuture );
+        assertSame("invokeRpc", expFuture, actualFuture);
 
-        InOrder inOrder = inOrder( dataBroker, mockTransaction );
-        inOrder.verify( dataBroker ).beginTransaction();
-        inOrder.verify( mockTransaction ).putConfigurationData( instanceID, dataNode );
-        inOrder.verify( mockTransaction ).commit();
+        InOrder inOrder = inOrder(dataBroker, mockTransaction);
+        inOrder.verify(dataBroker).beginTransaction();
+        inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode);
+        inOrder.verify(mockTransaction).commit();
     }
 
     @Test
     public void testCommitConfigurationDataPutBehindMountPoint() {
-        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture( null );
+        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
 
-        when( mockMountInstance.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.putConfigurationData( instanceID, dataNode );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction);
+        mockTransaction.putConfigurationData(instanceID, dataNode);
+        when(mockTransaction.commit()).thenReturn(expFuture);
 
-        Future<RpcResult<TransactionStatus>> actualFuture =
-                 brokerFacade.commitConfigurationDataPutBehindMountPoint(
-                                                       mockMountInstance, instanceID, dataNode );
+        Future<RpcResult<TransactionStatus>> actualFuture = brokerFacade.commitConfigurationDataPutBehindMountPoint(
+                mockMountInstance, instanceID, dataNode);
 
-        assertSame( "invokeRpc", expFuture, actualFuture );
+        assertSame("invokeRpc", expFuture, actualFuture);
 
-        InOrder inOrder = inOrder( mockMountInstance, mockTransaction );
-        inOrder.verify( mockMountInstance ).beginTransaction();
-        inOrder.verify( mockTransaction ).putConfigurationData( instanceID, dataNode );
-        inOrder.verify( mockTransaction ).commit();
+        InOrder inOrder = inOrder(mockMountInstance, mockTransaction);
+        inOrder.verify(mockMountInstance).beginTransaction();
+        inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode);
+        inOrder.verify(mockTransaction).commit();
     }
 
     @Test
     public void testCommitConfigurationDataPost() {
-        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture( null );
+        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
 
-        Map<InstanceIdentifier, CompositeNode> nodeMap =
-                new ImmutableMap.Builder<InstanceIdentifier,CompositeNode>()
-                                                             .put( instanceID, dataNode ).build();
+        Map<InstanceIdentifier, CompositeNode> nodeMap = new ImmutableMap.Builder<InstanceIdentifier, CompositeNode>()
+                .put(instanceID, dataNode).build();
 
-        when( dataBroker.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.putConfigurationData( instanceID, dataNode );
-        when( mockTransaction.getCreatedConfigurationData() ).thenReturn( nodeMap );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        when(dataBroker.beginTransaction()).thenReturn(mockTransaction);
+        mockTransaction.putConfigurationData(instanceID, dataNode);
+        when(mockTransaction.getCreatedConfigurationData()).thenReturn(nodeMap);
+        when(mockTransaction.commit()).thenReturn(expFuture);
 
-        Future<RpcResult<TransactionStatus>> actualFuture =
-                             brokerFacade.commitConfigurationDataPost( instanceID, dataNode );
+        Future<RpcResult<TransactionStatus>> actualFuture = brokerFacade.commitConfigurationDataPost(instanceID,
+                dataNode);
 
-        assertSame( "commitConfigurationDataPut", expFuture, actualFuture );
+        assertSame("commitConfigurationDataPut", expFuture, actualFuture);
 
-        InOrder inOrder = inOrder( dataBroker, mockTransaction );
-        inOrder.verify( dataBroker ).beginTransaction();
-        inOrder.verify( mockTransaction ).putConfigurationData( instanceID, dataNode );
-        inOrder.verify( mockTransaction ).commit();
+        InOrder inOrder = inOrder(dataBroker, mockTransaction);
+        inOrder.verify(dataBroker).beginTransaction();
+        inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode);
+        inOrder.verify(mockTransaction).commit();
     }
 
-    @Test(expected=RestconfDocumentedException.class)
+    @Test(expected = RestconfDocumentedException.class)
     public void testCommitConfigurationDataPostAlreadyExists() {
-        when( dataBroker.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.putConfigurationData( instanceID, dataNode );
-        when ( mockTransaction.readConfigurationData( instanceID ) )
-            .thenReturn( dataNode );
+        when(dataBroker.beginTransaction()).thenReturn(mockTransaction);
+        mockTransaction.putConfigurationData(instanceID, dataNode);
+        when(mockTransaction.readConfigurationData(instanceID)).thenReturn(dataNode);
         try {
-            brokerFacade.commitConfigurationDataPost( instanceID, dataNode );
-        }
-        catch (RestconfDocumentedException e) {
-            assertEquals("getErrorTag",
-                    RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get( 0 ).getErrorTag());
+            brokerFacade.commitConfigurationDataPost(instanceID, dataNode);
+        } catch (RestconfDocumentedException e) {
+            assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
             throw e;
         }
     }
 
     @Test
     public void testCommitConfigurationDataPostBehindMountPoint() {
-        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture( null );
+        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
 
-        Map<InstanceIdentifier, CompositeNode> nodeMap =
-                new ImmutableMap.Builder<InstanceIdentifier,CompositeNode>()
-                                                           .put( instanceID, dataNode ).build();
+        Map<InstanceIdentifier, CompositeNode> nodeMap = new ImmutableMap.Builder<InstanceIdentifier, CompositeNode>()
+                .put(instanceID, dataNode).build();
 
-        when( mockMountInstance.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.putConfigurationData( instanceID, dataNode );
-        when( mockTransaction.getCreatedConfigurationData() ).thenReturn( nodeMap );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction);
+        mockTransaction.putConfigurationData(instanceID, dataNode);
+        when(mockTransaction.getCreatedConfigurationData()).thenReturn(nodeMap);
+        when(mockTransaction.commit()).thenReturn(expFuture);
 
-        Future<RpcResult<TransactionStatus>> actualFuture =
-                brokerFacade.commitConfigurationDataPostBehindMountPoint( mockMountInstance,
-                                                                          instanceID, dataNode );
+        Future<RpcResult<TransactionStatus>> actualFuture = brokerFacade.commitConfigurationDataPostBehindMountPoint(
+                mockMountInstance, instanceID, dataNode);
 
-        assertSame( "commitConfigurationDataPostBehindMountPoint", expFuture, actualFuture );
+        assertSame("commitConfigurationDataPostBehindMountPoint", expFuture, actualFuture);
 
-        InOrder inOrder = inOrder( mockMountInstance, mockTransaction );
-        inOrder.verify( mockMountInstance ).beginTransaction();
-        inOrder.verify( mockTransaction ).putConfigurationData( instanceID, dataNode );
-        inOrder.verify( mockTransaction ).commit();
+        InOrder inOrder = inOrder(mockMountInstance, mockTransaction);
+        inOrder.verify(mockMountInstance).beginTransaction();
+        inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode);
+        inOrder.verify(mockTransaction).commit();
     }
 
-    @Test(expected=RestconfDocumentedException.class)
+    @Test(expected = RestconfDocumentedException.class)
     public void testCommitConfigurationDataPostBehindMountPointAlreadyExists() {
 
-        when( mockMountInstance.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.putConfigurationData( instanceID, dataNode );
-        when ( mockTransaction.readConfigurationData( instanceID ) )
-            .thenReturn( dataNode );
+        when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction);
+        mockTransaction.putConfigurationData(instanceID, dataNode);
+        when(mockTransaction.readConfigurationData(instanceID)).thenReturn(dataNode);
         try {
-            brokerFacade.commitConfigurationDataPostBehindMountPoint( mockMountInstance,
-                    instanceID, dataNode );
-        }
-        catch (RestconfDocumentedException e) {
-            assertEquals("getErrorTag",
-                    RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get( 0 ).getErrorTag());
+            brokerFacade.commitConfigurationDataPostBehindMountPoint(mockMountInstance, instanceID, dataNode);
+        } catch (RestconfDocumentedException e) {
+            assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
             throw e;
         }
     }
 
     @Test
     public void testCommitConfigurationDataDelete() {
-        Future<RpcResult<TransactionStatus>> expFuture =  Futures.immediateFuture( null );
+        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
 
-        when( dataBroker.beginTransaction() ).thenReturn( mockTransaction );
+        when(dataBroker.beginTransaction()).thenReturn(mockTransaction);
         when(mockTransaction.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(
                 ImmutableCompositeNode.builder().toInstance());
-        mockTransaction.removeConfigurationData( instanceID );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        mockTransaction.removeConfigurationData(instanceID);
+        when(mockTransaction.commit()).thenReturn(expFuture);
 
-        Future<RpcResult<TransactionStatus>> actualFuture =
-                             brokerFacade.commitConfigurationDataDelete( instanceID );
+        Future<RpcResult<TransactionStatus>> actualFuture = brokerFacade.commitConfigurationDataDelete(instanceID);
 
-        assertSame( "commitConfigurationDataDelete", expFuture, actualFuture );
+        assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
 
-        InOrder inOrder = inOrder( dataBroker, mockTransaction );
-        inOrder.verify( dataBroker ).beginTransaction();
-        inOrder.verify( mockTransaction ).removeConfigurationData( instanceID );
-        inOrder.verify( mockTransaction ).commit();
+        InOrder inOrder = inOrder(dataBroker, mockTransaction);
+        inOrder.verify(dataBroker).beginTransaction();
+        inOrder.verify(mockTransaction).removeConfigurationData(instanceID);
+        inOrder.verify(mockTransaction).commit();
     }
 
     @Test
     public void testCommitConfigurationDataDeleteBehindMountPoint() {
-        Future<RpcResult<TransactionStatus>> expFuture =  Futures.immediateFuture( null );
+        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
 
-        when( mockMountInstance.beginTransaction() ).thenReturn( mockTransaction );
+        when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction);
         when(mockTransaction.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(
                 ImmutableCompositeNode.builder().toInstance());
-        mockTransaction.removeConfigurationData( instanceID );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        mockTransaction.removeConfigurationData(instanceID);
+        when(mockTransaction.commit()).thenReturn(expFuture);
 
-        Future<RpcResult<TransactionStatus>> actualFuture =
-                             brokerFacade.commitConfigurationDataDeleteBehindMountPoint(
-                                                              mockMountInstance, instanceID );
+        Future<RpcResult<TransactionStatus>> actualFuture = brokerFacade.commitConfigurationDataDeleteBehindMountPoint(
+                mockMountInstance, instanceID);
 
-        assertSame( "commitConfigurationDataDeleteBehindMountPoint", expFuture, actualFuture );
+        assertSame("commitConfigurationDataDeleteBehindMountPoint", expFuture, actualFuture);
 
-        InOrder inOrder = inOrder( mockMountInstance, mockTransaction );
-        inOrder.verify( mockMountInstance ).beginTransaction();
-        inOrder.verify( mockTransaction ).removeConfigurationData( instanceID );
-        inOrder.verify( mockTransaction ).commit();
+        InOrder inOrder = inOrder(mockMountInstance, mockTransaction);
+        inOrder.verify(mockMountInstance).beginTransaction();
+        inOrder.verify(mockTransaction).removeConfigurationData(instanceID);
+        inOrder.verify(mockTransaction).commit();
     }
 
     @SuppressWarnings("unchecked")
     @Test
     public void testRegisterToListenDataChanges() {
-        ListenerAdapter listener = Notificator.createListener( instanceID, "stream" );
+        ListenerAdapter listener = Notificator.createListener(instanceID, "stream");
 
-        ListenerRegistration<DataChangeListener> mockRegistration = mock( ListenerRegistration.class );
-        when( dataBroker.registerDataChangeListener( instanceID, listener ) )
-            .thenReturn( mockRegistration );
+        ListenerRegistration<DataChangeListener> mockRegistration = mock(ListenerRegistration.class);
+        when(dataBroker.registerDataChangeListener(instanceID, listener)).thenReturn(mockRegistration);
 
-        brokerFacade.registerToListenDataChanges( listener );
+        brokerFacade.registerToListenDataChanges(listener);
 
-        verify( dataBroker ).registerDataChangeListener( instanceID, listener );
+        verify(dataBroker).registerDataChangeListener(instanceID, listener);
 
-        assertEquals( "isListening", true, listener.isListening() );
+        assertEquals("isListening", true, listener.isListening());
 
-        brokerFacade.registerToListenDataChanges( listener );
-        verifyNoMoreInteractions( dataBroker );
+        brokerFacade.registerToListenDataChanges(listener);
+        verifyNoMoreInteractions(dataBroker);
     }
 }
index 307abebdd7b1a37ebfb3cc1d716048614c3e44cc..4ff4f707106a59058702166beb99a5cf8f506cb2 100644 (file)
@@ -3,12 +3,10 @@ package org.opendaylight.controller.sal.restconf.impl.test;
 import static org.junit.Assert.assertTrue;
 
 import java.io.FileNotFoundException;
-
 import javax.ws.rs.client.Entity;
 import javax.ws.rs.core.Application;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.JerseyTest;
 import org.junit.BeforeClass;
@@ -47,7 +45,7 @@ public class CodecsExceptionsCatchingTest extends JerseyTest {
         resourceConfig = resourceConfig.registerInstances(restConf, StructuredDataToXmlProvider.INSTANCE,
                 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
                 JsonToCompositeNodeProvider.INSTANCE);
-        resourceConfig.registerClasses( RestconfDocumentedExceptionMapper.class );
+        resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
         return resourceConfig;
     }
 
index 19a7eff480dece01d1e9ff5743b3ef9c5fa94c5e..8ae8d0bdac927415b7ebd514cf8c356a45a6b52e 100644 (file)
@@ -34,7 +34,6 @@ public class DummyFuture<T> implements Future<RpcResult<T>> {
         result = builder.result;
     }
 
-
     @Override
     public boolean cancel(final boolean mayInterruptIfRunning) {
         return cancel;
@@ -56,8 +55,8 @@ public class DummyFuture<T> implements Future<RpcResult<T>> {
     }
 
     @Override
-    public RpcResult<T> get(final long timeout, final TimeUnit unit) throws InterruptedException,
-    ExecutionException, TimeoutException {
+    public RpcResult<T> get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException,
+            TimeoutException {
         return result;
     }
 
index 16d14842db3c2cc02684e244a219f7d20da03daf..3c545c06e95054f70dd4ab21c42912179f37990d 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.controller.sal.restconf.impl.test;
 
 import java.util.Collection;
-
 import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 
index d90e9539c83cbbeeff51726967370dc1f6e53724..008fda4e0960b9e2ecd3b3c5518887dd03dba452 100644 (file)
@@ -8,7 +8,6 @@
 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.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.Status;
index b90097bc94a0e7888b589f33960343cc94d36c12..d12bf9e44efa96be39b2dea863c2339e74e8577b 100644 (file)
@@ -67,17 +67,15 @@ public class InvokeRpcMethodTest {
     private static ControllerContext controllerContext = null;
     private static UriInfo uriInfo;
 
-
     @BeforeClass
     public static void init() throws FileNotFoundException {
-        Set<Module> allModules = new HashSet<Module>( TestUtils
-                .loadModulesFrom("/full-versions/yangs") );
-        allModules.addAll( TestUtils.loadModulesFrom("/invoke-rpc") );
+        Set<Module> allModules = new HashSet<Module>(TestUtils.loadModulesFrom("/full-versions/yangs"));
+        allModules.addAll(TestUtils.loadModulesFrom("/invoke-rpc"));
         assertNotNull(allModules);
         Module module = TestUtils.resolveModule("invoke-rpc-module", allModules);
         assertNotNull(module);
         SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
-        controllerContext = spy( ControllerContext.getInstance() );
+        controllerContext = spy(ControllerContext.getInstance());
         controllerContext.setSchemas(schemaContext);
         uriInfo = mock(UriInfo.class);
         MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
@@ -86,17 +84,15 @@ public class InvokeRpcMethodTest {
     }
 
     @Before
-    public void initMethod()
-    {
+    public void initMethod() {
         restconfImpl = RestconfImpl.getInstance();
-        restconfImpl.setControllerContext( controllerContext );
+        restconfImpl.setControllerContext(controllerContext);
     }
 
     /**
-     * Test method invokeRpc in RestconfImpl class tests if composite node as
-     * input parameter of method invokeRpc (second argument) is wrapped to
-     * parent composite node which has QName equals to QName of rpc (resolved
-     * from string - first argument).
+     * Test method invokeRpc in RestconfImpl class tests if composite node as input parameter of method invokeRpc
+     * (second argument) is wrapped to parent composite node which has QName equals to QName of rpc (resolved from
+     * string - first argument).
      */
     @Test
     public void invokeRpcMtethodTest() {
@@ -115,11 +111,10 @@ public class InvokeRpcMethodTest {
 
         CompositeNode payload = preparePayload();
 
-        when(mockedBrokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class)))
-            .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture(
-                                               Rpcs.<CompositeNode>getRpcResult( true ) ) );
+        when(mockedBrokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(Rpcs.<CompositeNode> getRpcResult(true)));
 
-        StructuredData structData = restconf.invokeRpc("invoke-rpc-module:rpc-test", payload,uriInfo);
+        StructuredData structData = restconf.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo);
         assertTrue(structData == null);
 
     }
@@ -137,207 +132,203 @@ public class InvokeRpcMethodTest {
 
     @Test
     public void testInvokeRpcWithNoPayloadRpc_FailNoErrors() {
-        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( false );
+        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode> getRpcResult(false);
 
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
-        when( brokerFacade.invokeRpc(
-                 eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
-                 any(CompositeNode.class)))
-            .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+        when(
+                brokerFacade.invokeRpc(
+                        eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
+                        any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
 
         restconfImpl.setBroker(brokerFacade);
 
         try {
-            restconfImpl.invokeRpc("toaster:cancel-toast", "",uriInfo);
+            restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
             fail("Expected an exception to be thrown.");
-        }
-        catch (RestconfDocumentedException e) {
-            verifyRestconfDocumentedException( e, 0, ErrorType.RPC, ErrorTag.OPERATION_FAILED,
-                                               Optional.<String>absent(), Optional.<String>absent() );
+        } catch (RestconfDocumentedException e) {
+            verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.OPERATION_FAILED,
+                    Optional.<String> absent(), Optional.<String> absent());
         }
     }
 
-    void verifyRestconfDocumentedException( final RestconfDocumentedException e, final int index,
-                                            final ErrorType expErrorType, final ErrorTag expErrorTag,
-                                            final Optional<String> expErrorMsg,
-                                            final Optional<String> expAppTag ) {
+    void verifyRestconfDocumentedException(final RestconfDocumentedException e, final int index,
+            final ErrorType expErrorType, final ErrorTag expErrorTag, final Optional<String> expErrorMsg,
+            final Optional<String> expAppTag) {
         RestconfError actual = null;
         try {
-            actual = e.getErrors().get( index );
-        }
-        catch( ArrayIndexOutOfBoundsException ex ) {
-            fail( "RestconfError not found at index " + index );
+            actual = e.getErrors().get(index);
+        } catch (ArrayIndexOutOfBoundsException ex) {
+            fail("RestconfError not found at index " + index);
         }
 
-        assertEquals( "getErrorType", expErrorType, actual.getErrorType() );
-        assertEquals( "getErrorTag", expErrorTag, actual.getErrorTag() );
-        assertNotNull( "getErrorMessage is null", actual.getErrorMessage() );
+        assertEquals("getErrorType", expErrorType, actual.getErrorType());
+        assertEquals("getErrorTag", expErrorTag, actual.getErrorTag());
+        assertNotNull("getErrorMessage is null", actual.getErrorMessage());
 
-        if( expErrorMsg.isPresent() ) {
-            assertEquals( "getErrorMessage", expErrorMsg.get(), actual.getErrorMessage() );
+        if (expErrorMsg.isPresent()) {
+            assertEquals("getErrorMessage", expErrorMsg.get(), actual.getErrorMessage());
         }
 
-        if( expAppTag.isPresent() ) {
-            assertEquals( "getErrorAppTag", expAppTag.get(), actual.getErrorAppTag() );
+        if (expAppTag.isPresent()) {
+            assertEquals("getErrorAppTag", expAppTag.get(), actual.getErrorAppTag());
         }
     }
 
     @Test
     public void testInvokeRpcWithNoPayloadRpc_FailWithRpcError() {
-        List<RpcError> rpcErrors = Arrays.asList(
-            RpcErrors.getRpcError( null, "bogusTag", null, ErrorSeverity.ERROR, "foo",
-                                   RpcError.ErrorType.TRANSPORT, null ),
-            RpcErrors.getRpcError( "app-tag", "in-use", null, ErrorSeverity.WARNING, "bar",
-                                   RpcError.ErrorType.RPC, null ));
+        List<RpcError> rpcErrors = Arrays.asList(RpcErrors.getRpcError(null, "bogusTag", null, ErrorSeverity.ERROR,
+                "foo", RpcError.ErrorType.TRANSPORT, null), RpcErrors.getRpcError("app-tag", "in-use", null,
+                ErrorSeverity.WARNING, "bar", RpcError.ErrorType.RPC, null));
 
-        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( false, rpcErrors );
+        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode> getRpcResult(false, rpcErrors);
 
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
-        when( brokerFacade.invokeRpc(
-                 eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
-                 any(CompositeNode.class)))
-            .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+        when(
+                brokerFacade.invokeRpc(
+                        eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
+                        any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
 
         restconfImpl.setBroker(brokerFacade);
 
         try {
-            restconfImpl.invokeRpc("toaster:cancel-toast", "",uriInfo);
+            restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
             fail("Expected an exception to be thrown.");
-        }
-        catch (RestconfDocumentedException e) {
-            verifyRestconfDocumentedException( e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED,
-                                               Optional.of( "foo" ), Optional.<String>absent() );
-            verifyRestconfDocumentedException( e, 1, ErrorType.RPC, ErrorTag.IN_USE,
-                                               Optional.of( "bar" ), Optional.of( "app-tag" ) );
+        } catch (RestconfDocumentedException e) {
+            verifyRestconfDocumentedException(e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, Optional.of("foo"),
+                    Optional.<String> absent());
+            verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
+                    Optional.of("app-tag"));
         }
     }
 
     @Test
     public void testInvokeRpcWithNoPayload_Success() {
-        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( true );
+        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode> getRpcResult(true);
 
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
-        when( brokerFacade.invokeRpc(
-                 eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
-                 any( CompositeNode.class )))
-            .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+        when(
+                brokerFacade.invokeRpc(
+                        eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
+                        any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
 
         restconfImpl.setBroker(brokerFacade);
 
-        StructuredData output = restconfImpl.invokeRpc("toaster:cancel-toast",
-                "",uriInfo);
+        StructuredData output = restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
         assertEquals(null, output);
-        //additional validation in the fact that the restconfImpl does not throw an exception.
+        // additional validation in the fact that the restconfImpl does not
+        // throw an exception.
     }
 
     @Test
     public void testInvokeRpcMethodExpectingNoPayloadButProvidePayload() {
         try {
-            restconfImpl.invokeRpc("toaster:cancel-toast", " a payload ",uriInfo);
+            restconfImpl.invokeRpc("toaster:cancel-toast", " a payload ", uriInfo);
             fail("Expected an exception");
         } catch (RestconfDocumentedException e) {
-            verifyRestconfDocumentedException( e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
-                                               Optional.<String>absent(), Optional.<String>absent() );
+            verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
+                    Optional.<String> absent(), Optional.<String> absent());
         }
     }
 
     @Test
     public void testInvokeRpcMethodWithBadMethodName() {
         try {
-            restconfImpl.invokeRpc("toaster:bad-method", "",uriInfo);
+            restconfImpl.invokeRpc("toaster:bad-method", "", uriInfo);
             fail("Expected an exception");
-        }
-        catch (RestconfDocumentedException e) {
-            verifyRestconfDocumentedException( e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
-                                               Optional.<String>absent(), Optional.<String>absent() );
+        } catch (RestconfDocumentedException e) {
+            verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
+                    Optional.<String> absent(), Optional.<String> absent());
         }
     }
 
     @Test
     public void testInvokeRpcMethodWithInput() {
-        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( true );
+        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode> getRpcResult(true);
 
         CompositeNode payload = mock(CompositeNode.class);
 
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
-        when( brokerFacade.invokeRpc(
-                 eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast")),
-                 any(CompositeNode.class)))
-            .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+        when(
+                brokerFacade.invokeRpc(
+                        eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast")),
+                        any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
 
         restconfImpl.setBroker(brokerFacade);
 
-        StructuredData output = restconfImpl.invokeRpc("toaster:make-toast",
-                payload,uriInfo);
+        StructuredData output = restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
         assertEquals(null, output);
-        //additional validation in the fact that the restconfImpl does not throw an exception.
+        // additional validation in the fact that the restconfImpl does not
+        // throw an exception.
     }
 
     @Test
     public void testThrowExceptionWhenSlashInModuleName() {
         try {
-            restconfImpl.invokeRpc("toaster/slash", "",uriInfo);
+            restconfImpl.invokeRpc("toaster/slash", "", uriInfo);
             fail("Expected an exception.");
-        }
-        catch (RestconfDocumentedException e) {
-            verifyRestconfDocumentedException( e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
-                                               Optional.<String>absent(), Optional.<String>absent() );
+        } catch (RestconfDocumentedException e) {
+            verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
+                    Optional.<String> absent(), Optional.<String> absent());
         }
     }
 
     @Test
     public void testInvokeRpcWithNoPayloadWithOutput_Success() {
-        CompositeNode compositeNode = mock( CompositeNode.class );
-        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( true, compositeNode,
-                                                            Collections.<RpcError>emptyList() );
+        CompositeNode compositeNode = mock(CompositeNode.class);
+        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode> getRpcResult(true, compositeNode,
+                Collections.<RpcError> emptyList());
 
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
-        when( brokerFacade.invokeRpc(
+        when(
+                brokerFacade.invokeRpc(
                         eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)testOutput")),
-                        any( CompositeNode.class )))
-            .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+                        any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
 
         restconfImpl.setBroker(brokerFacade);
 
-        StructuredData output = restconfImpl.invokeRpc("toaster:testOutput", "",uriInfo);
-        assertNotNull( output );
-        assertSame( compositeNode, output.getData() );
-        assertNotNull( output.getSchema() );
+        StructuredData output = restconfImpl.invokeRpc("toaster:testOutput", "", uriInfo);
+        assertNotNull(output);
+        assertSame(compositeNode, output.getData());
+        assertNotNull(output.getSchema());
     }
 
     @Test
-    public void testMountedRpcCallNoPayload_Success() throws Exception
-    {
-        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( true );
+    public void testMountedRpcCallNoPayload_Success() throws Exception {
+        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode> getRpcResult(true);
 
-        ListenableFuture<RpcResult<CompositeNode>> mockListener = mock( ListenableFuture.class );
-        when( mockListener.get() ).thenReturn( rpcResult );
+        ListenableFuture<RpcResult<CompositeNode>> mockListener = mock(ListenableFuture.class);
+        when(mockListener.get()).thenReturn(rpcResult);
 
-        QName cancelToastQName = QName.create( "namespace", "2014-05-28", "cancelToast" );
+        QName cancelToastQName = QName.create("namespace", "2014-05-28", "cancelToast");
 
-        RpcDefinition mockRpc = mock( RpcDefinition.class );
-        when( mockRpc.getQName() ).thenReturn( cancelToastQName );
+        RpcDefinition mockRpc = mock(RpcDefinition.class);
+        when(mockRpc.getQName()).thenReturn(cancelToastQName);
 
-        MountInstance mockMountPoint = mock( MountInstance.class );
-        when( mockMountPoint.rpc( eq( cancelToastQName ), any( CompositeNode.class ) ) )
-        .thenReturn( mockListener );
+        MountInstance mockMountPoint = mock(MountInstance.class);
+        when(mockMountPoint.rpc(eq(cancelToastQName), any(CompositeNode.class))).thenReturn(mockListener);
 
-        InstanceIdWithSchemaNode mockedInstanceId = mock( InstanceIdWithSchemaNode.class );
-        when( mockedInstanceId.getMountPoint() ).thenReturn( mockMountPoint );
+        InstanceIdWithSchemaNode mockedInstanceId = mock(InstanceIdWithSchemaNode.class);
+        when(mockedInstanceId.getMountPoint()).thenReturn(mockMountPoint);
 
-        ControllerContext mockedContext = mock( ControllerContext.class );
+        ControllerContext mockedContext = mock(ControllerContext.class);
         String cancelToastStr = "toaster:cancel-toast";
-        when( mockedContext.urlPathArgDecode( cancelToastStr ) ).thenReturn( cancelToastStr );
-        when( mockedContext.getRpcDefinition( cancelToastStr ) ).thenReturn( mockRpc );
-        when( mockedContext.toMountPointIdentifier(  "opendaylight-inventory:nodes/node/"
-                + "REMOTE_HOST/yang-ext:mount/toaster:cancel-toast" ) ).thenReturn( mockedInstanceId );
+        when(mockedContext.urlPathArgDecode(cancelToastStr)).thenReturn(cancelToastStr);
+        when(mockedContext.getRpcDefinition(cancelToastStr)).thenReturn(mockRpc);
+        when(
+                mockedContext.toMountPointIdentifier("opendaylight-inventory:nodes/node/"
+                        + "REMOTE_HOST/yang-ext:mount/toaster:cancel-toast")).thenReturn(mockedInstanceId);
 
-        restconfImpl.setControllerContext( mockedContext );
+        restconfImpl.setControllerContext(mockedContext);
         StructuredData output = restconfImpl.invokeRpc(
-                "opendaylight-inventory:nodes/node/REMOTE_HOST/yang-ext:mount/toaster:cancel-toast",
-                "",uriInfo);
+                "opendaylight-inventory:nodes/node/REMOTE_HOST/yang-ext:mount/toaster:cancel-toast", "", uriInfo);
         assertEquals(null, output);
 
-        //additional validation in the fact that the restconfImpl does not throw an exception.
+        // additional validation in the fact that the restconfImpl does not
+        // throw an exception.
     }
 }
index 42131026a5218cdb59079cc2324059930e816dd6..5fbfc453523339500c46e5d751b7967db455c19d 100644 (file)
@@ -25,9 +25,8 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 
 /**
- * If more then one data element with equal name exists where container or
- * leaf schema node should be present the RestconfDocumentedException has to
- * be raised
+ * If more then one data element with equal name exists where container or leaf schema node should be present the
+ * RestconfDocumentedException has to be raised
  *
  * Tests for BUG 1204
  */
@@ -35,31 +34,32 @@ public class MultipleEqualNamesForDataNodesTest {
 
     @Test
     public void multipleEqualNameDataNodeTestForContainerJsonTest() {
-        multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-container.json", ErrorType.APPLICATION,
-                ErrorTag.BAD_ELEMENT,JsonToCompositeNodeProvider.INSTANCE);
+        multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-container.json",
+                ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, JsonToCompositeNodeProvider.INSTANCE);
     }
 
     @Test
     public void multipleEqualNameDataNodeTestForLeafJsonTest() {
         multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-leaf.json", ErrorType.PROTOCOL,
-                ErrorTag.MALFORMED_MESSAGE,JsonToCompositeNodeProvider.INSTANCE);
+                ErrorTag.MALFORMED_MESSAGE, JsonToCompositeNodeProvider.INSTANCE);
     }
 
     @Test
     public void multipleEqualNameDataNodeTestForContainerXmlTest() {
-        multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-container.xml", ErrorType.APPLICATION,
-                ErrorTag.BAD_ELEMENT,XmlToCompositeNodeProvider.INSTANCE);
+        multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-container.xml",
+                ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, XmlToCompositeNodeProvider.INSTANCE);
     }
 
     @Test
     public void multipleEqualNameDataNodeTestForLeafXmlTest() {
         multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-leaf.xml", ErrorType.APPLICATION,
-                ErrorTag.BAD_ELEMENT,XmlToCompositeNodeProvider.INSTANCE);
+                ErrorTag.BAD_ELEMENT, XmlToCompositeNodeProvider.INSTANCE);
     }
 
-    private void multipleEqualNameDataNodeTest(String path, ErrorType errorType, ErrorTag errorTag,MessageBodyReader<CompositeNode> messageBodyReader) {
+    private void multipleEqualNameDataNodeTest(String path, ErrorType errorType, ErrorTag errorTag,
+            MessageBodyReader<CompositeNode> messageBodyReader) {
         try {
-            CompositeNode compositeNode = TestUtils.readInputToCnSn(path, false,messageBodyReader);
+            CompositeNode compositeNode = TestUtils.readInputToCnSn(path, false, messageBodyReader);
             assertNotNull(compositeNode);
 
             Set<Module> modules = null;
index 158569af7386eb35081ba046af00d96b0de08d96..7c354acc4077a4c1d50ad9da0d27e3a009973127 100644 (file)
@@ -11,7 +11,6 @@ import static org.junit.Assert.assertNotNull;
 
 import java.net.URI;
 import java.net.URISyntaxException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
@@ -26,7 +25,7 @@ public class NormalizeNodeTest extends YangAndXmlAndDataSchemaLoader {
         dataLoad("/normalize-node/yang/");
     }
 
-    @Test(expected=RestconfDocumentedException.class)
+    @Test(expected = RestconfDocumentedException.class)
     public void namespaceNotNullAndInvalidNamespaceAndNoModuleNameTest() {
 
         TestUtils.normalizeCompositeNode(prepareCnSn("wrongnamespace"), modules, schemaNodePath);
index 024a93b78e7e2a52e76059b198363fec003ababd..4000c7cc807f7e62c3583649ee3d04e2acd32f53 100644 (file)
@@ -12,7 +12,6 @@ import static org.junit.Assert.assertNull;
 import static org.mockito.Mockito.mock;
 
 import java.util.Collections;
-
 import org.junit.Test;
 import org.opendaylight.controller.sal.restconf.impl.RestCodec;
 import org.opendaylight.yangtools.concepts.Codec;
@@ -28,7 +27,7 @@ public class RestCodecExceptionsTest {
 
     @Test
     public void serializeExceptionTest() {
-        Codec<Object, Object> codec = RestCodec.from(BitsType.create(PATH, Collections.<Bit>emptyList()), null);
+        Codec<Object, Object> codec = RestCodec.from(BitsType.create(PATH, Collections.<Bit> emptyList()), null);
         String serializedValue = (String) codec.serialize("incorrect value"); // set
                                                                               // expected
         assertEquals("incorrect value", serializedValue);
index e8cbf3140f35f9f750612ddc5c932a8763034a4b..d1d2a5babf5bcbd554b1f5612979c59b2c032730 100644 (file)
@@ -57,10 +57,10 @@ public class RestDeleteOperationTest extends JerseyTest {
     @Override
     protected Application configure() {
         /* enable/disable Jersey logs to console */
-//        enable(TestProperties.LOG_TRAFFIC);
-//        enable(TestProperties.DUMP_ENTITY);
-//        enable(TestProperties.RECORD_LOG_LEVEL);
-//        set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
+        // enable(TestProperties.LOG_TRAFFIC);
+        // enable(TestProperties.DUMP_ENTITY);
+        // enable(TestProperties.RECORD_LOG_LEVEL);
+        // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
         ResourceConfig resourceConfig = new ResourceConfig();
         resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
                 XmlToCompositeNodeProvider.INSTANCE);
@@ -82,7 +82,8 @@ public class RestDeleteOperationTest extends JerseyTest {
     }
 
     private Future<RpcResult<TransactionStatus>> createFuture(TransactionStatus statusName) {
-        RpcResult<TransactionStatus> rpcResult = new DummyRpcResult.Builder<TransactionStatus>().result(statusName).build();
+        RpcResult<TransactionStatus> rpcResult = new DummyRpcResult.Builder<TransactionStatus>().result(statusName)
+                .build();
         return new DummyFuture.Builder<TransactionStatus>().rpcResult(rpcResult).build();
     }
 
index 53183c611cf54329d5555b2de8b56b01cedfdf0d..bab06e92451985b5a0d95032e99174adb91ba4b0 100644 (file)
@@ -12,7 +12,6 @@ import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import java.io.FileNotFoundException;
-
 import org.junit.BeforeClass;
 import org.junit.Rule;
 import org.junit.Test;
@@ -47,10 +46,9 @@ public class RestGetAugmentedElementWhenEqualNamesTest {
     public void nodeWithoutNamespaceHasMoreAugments() {
         try {
             controllerContext.toInstanceIdentifier("main:cont/cont1");
-            fail( "Expected exception" );
+            fail("Expected exception");
         } catch (RestconfDocumentedException e) {
-            assertTrue(e.getErrors().get( 0 ).getErrorMessage().contains(
-                                    "is added as augment from more than one module"));
+            assertTrue(e.getErrors().get(0).getErrorMessage().contains("is added as augment from more than one module"));
         }
     }
 }
index 9fd5128d19b51db4c71ad3678dae982aec1b3551..536d140cf1b78e05b7a3e77d38e43a32d8a1f8f4 100644 (file)
@@ -75,7 +75,7 @@ public class RestGetOperationTest extends JerseyTest {
         Object key;
         Object data; // List for a CompositeNode, value Object for a SimpleNode
 
-        NodeData( final Object key, final Object data ) {
+        NodeData(final Object key, final Object data) {
             this.key = key;
             this.data = data;
         }
@@ -117,7 +117,7 @@ public class RestGetOperationTest extends JerseyTest {
         resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
                 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
                 JsonToCompositeNodeProvider.INSTANCE);
-        resourceConfig.registerClasses( RestconfDocumentedExceptionMapper.class );
+        resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
         return resourceConfig;
     }
 
@@ -172,19 +172,18 @@ public class RestGetOperationTest extends JerseyTest {
     /**
      * MountPoint test. URI represents mount point.
      *
-     * Slashes in URI behind mount point. lst1 element with key
-     * GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is requested via
-     * GET HTTP operation. It is tested whether %2F character is replaced with
-     * simple / in InstanceIdentifier parameter in method
-     * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, InstanceIdentifier)}
-     * which is called in method {@link RestconfImpl#readConfigurationData}
+     * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
+     * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
+     * InstanceIdentifier parameter in method
+     * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, InstanceIdentifier)} which is called in
+     * method {@link RestconfImpl#readConfigurationData}
      *
      *
      * @throws ParseException
      */
     @Test
     public void getDataWithSlashesBehindMountPoint() throws UnsupportedEncodingException, URISyntaxException,
-    ParseException {
+            ParseException {
         InstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
         when(
                 brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class),
@@ -446,11 +445,11 @@ public class RestGetOperationTest extends JerseyTest {
         assertTrue(
                 "module1-behind-mount-point in json wasn't found",
                 prepareXmlRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point", responseBody)
-                .find());
+                        .find());
         assertTrue(
                 "module2-behind-mount-point in json wasn't found",
                 prepareXmlRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point", responseBody)
-                .find());
+                        .find());
 
     }
 
@@ -486,7 +485,7 @@ public class RestGetOperationTest extends JerseyTest {
         assertTrue(
                 "module1-behind-mount-point in json wasn't found",
                 prepareXmlRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point", responseBody)
-                .find());
+                        .find());
         split = responseBody.split("<module");
         assertEquals("<module element is returned more then once", 2, split.length);
 
@@ -516,7 +515,8 @@ public class RestGetOperationTest extends JerseyTest {
                 .find());
     }
 
-    private Matcher prepareJsonRegex(final String module, final String revision, final String namespace, final String searchIn) {
+    private Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
+            final String searchIn) {
         StringBuilder regex = new StringBuilder();
         regex.append("^");
 
@@ -542,7 +542,8 @@ public class RestGetOperationTest extends JerseyTest {
 
     }
 
-    private Matcher prepareXmlRegex(final String module, final String revision, final String namespace, final String searchIn) {
+    private Matcher prepareXmlRegex(final String module, final String revision, final String namespace,
+            final String searchIn) {
         StringBuilder regex = new StringBuilder();
         regex.append("^");
 
@@ -570,7 +571,8 @@ public class RestGetOperationTest extends JerseyTest {
         return ptrn.matcher(searchIn);
     }
 
-    private void prepareMockForModulesTest(final ControllerContext mockedControllerContext) throws FileNotFoundException {
+    private void prepareMockForModulesTest(final ControllerContext mockedControllerContext)
+            throws FileNotFoundException {
         SchemaContext schemaContext = TestUtils.loadSchemaContext("/modules");
         mockedControllerContext.setGlobalSchema(schemaContext);
         // when(mockedControllerContext.getGlobalSchema()).thenReturn(schemaContext);
@@ -614,8 +616,8 @@ public class RestGetOperationTest extends JerseyTest {
     }
 
     /**
-     * If includeWhiteChars URI parameter is set to false then no white
-     * characters can be included in returned output
+     * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
+     *
      * @throws UnsupportedEncodingException
      */
     @Test
@@ -624,10 +626,9 @@ public class RestGetOperationTest extends JerseyTest {
         getDataWithUriIncludeWhiteCharsParameter("operational");
     }
 
-
     private void getDataWithUriIncludeWhiteCharsParameter(String target) throws UnsupportedEncodingException {
         mockReadConfigurationDataMethod();
-        String uri = "/"+target+"/ietf-interfaces:interfaces/interface/eth0";
+        String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
         Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
         String xmlData = response.readEntity(String.class);
 
@@ -649,311 +650,290 @@ public class RestGetOperationTest extends JerseyTest {
     @Test
     public void getDataWithUriDepthParameterTest() throws UnsupportedEncodingException {
 
-        ControllerContext.getInstance().setGlobalSchema( schemaContextModules );
-
-        CompositeNode depth1Cont = toCompositeNode(
-                toCompositeNodeData( toNestedQName( "depth1-cont" ),
-                        toCompositeNodeData( toNestedQName( "depth2-cont1" ),
-                                toCompositeNodeData( toNestedQName( "depth3-cont1" ),
-                                        toCompositeNodeData( toNestedQName( "depth4-cont1" ),
-                                                toSimpleNodeData( toNestedQName( "depth5-leaf1" ), "depth5-leaf1-value" )
-                                                ),
-                                                toSimpleNodeData( toNestedQName( "depth4-leaf1" ), "depth4-leaf1-value" )
-                                        ),
-                                        toSimpleNodeData( toNestedQName( "depth3-leaf1" ), "depth3-leaf1-value" )
-                                ),
-                                toCompositeNodeData( toNestedQName( "depth2-cont2" ),
-                                        toCompositeNodeData( toNestedQName( "depth3-cont2" ),
-                                                toCompositeNodeData( toNestedQName( "depth4-cont2" ),
-                                                        toSimpleNodeData( toNestedQName( "depth5-leaf2" ), "depth5-leaf2-value" )
-                                                        ),
-                                                        toSimpleNodeData( toNestedQName( "depth4-leaf2" ), "depth4-leaf2-value" )
-                                                ),
-                                                toSimpleNodeData( toNestedQName( "depth3-leaf2" ), "depth3-leaf2-value" )
-                                        ),
-                                        toSimpleNodeData( toNestedQName( "depth2-leaf1" ), "depth2-leaf1-value" )
-                        ) );
-
-        when( brokerFacade.readConfigurationData( any( InstanceIdentifier.class ) ) )
-        .thenReturn( depth1Cont );
+        ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
+
+        CompositeNode depth1Cont = toCompositeNode(toCompositeNodeData(
+                toNestedQName("depth1-cont"),
+                toCompositeNodeData(
+                        toNestedQName("depth2-cont1"),
+                        toCompositeNodeData(
+                                toNestedQName("depth3-cont1"),
+                                toCompositeNodeData(toNestedQName("depth4-cont1"),
+                                        toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
+                                toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
+                        toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")),
+                toCompositeNodeData(
+                        toNestedQName("depth2-cont2"),
+                        toCompositeNodeData(
+                                toNestedQName("depth3-cont2"),
+                                toCompositeNodeData(toNestedQName("depth4-cont2"),
+                                        toSimpleNodeData(toNestedQName("depth5-leaf2"), "depth5-leaf2-value")),
+                                toSimpleNodeData(toNestedQName("depth4-leaf2"), "depth4-leaf2-value")),
+                        toSimpleNodeData(toNestedQName("depth3-leaf2"), "depth3-leaf2-value")),
+                toSimpleNodeData(toNestedQName("depth2-leaf1"), "depth2-leaf1-value")));
+
+        when(brokerFacade.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(depth1Cont);
 
         // Test config with depth 1
 
-        Response response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "1" )
-                .request( "application/xml" ).get();
+        Response response = target("/config/nested-module:depth1-cont").queryParam("depth", "1")
+                .request("application/xml").get();
 
-        verifyXMLResponse( response, expectEmptyContainer( "depth1-cont" ) );
+        verifyXMLResponse(response, expectEmptyContainer("depth1-cont"));
 
         // Test config with depth 2
 
-        response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "2" )
-                .request( "application/xml" ).get();
+        response = target("/config/nested-module:depth1-cont").queryParam("depth", "2").request("application/xml")
+                .get();
 
-        //        String xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
-        //        Response mr=mock(Response.class);
-        //        when(mr.getEntity()).thenReturn( new java.io.StringBufferInputStream(xml) );
+        // String
+        // xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
+        // Response mr=mock(Response.class);
+        // when(mr.getEntity()).thenReturn( new
+        // java.io.StringBufferInputStream(xml) );
 
-        verifyXMLResponse( response,
-                expectContainer( "depth1-cont",
-                        expectEmptyContainer( "depth2-cont1" ),
-                        expectEmptyContainer( "depth2-cont2" ),
-                        expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-                        ) );
+        verifyXMLResponse(
+                response,
+                expectContainer("depth1-cont", expectEmptyContainer("depth2-cont1"),
+                        expectEmptyContainer("depth2-cont2"), expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
 
         // Test config with depth 3
 
-        response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "3" )
-                .request( "application/xml" ).get();
-
-        verifyXMLResponse( response,
-                expectContainer( "depth1-cont",
-                        expectContainer( "depth2-cont1",
-                                expectEmptyContainer( "depth3-cont1" ),
-                                expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                                ),
-                                expectContainer( "depth2-cont2",
-                                        expectEmptyContainer( "depth3-cont2" ),
-                                        expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
-                                        ),
-                                        expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-                        ) );
+        response = target("/config/nested-module:depth1-cont").queryParam("depth", "3").request("application/xml")
+                .get();
+
+        verifyXMLResponse(
+                response,
+                expectContainer(
+                        "depth1-cont",
+                        expectContainer("depth2-cont1", expectEmptyContainer("depth3-cont1"),
+                                expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
+                        expectContainer("depth2-cont2", expectEmptyContainer("depth3-cont2"),
+                                expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
+                        expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
 
         // Test config with depth 4
 
-        response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "4" )
-                .request( "application/xml" ).get();
-
-        verifyXMLResponse( response,
-                expectContainer( "depth1-cont",
-                        expectContainer( "depth2-cont1",
-                                expectContainer( "depth3-cont1",
-                                        expectEmptyContainer( "depth4-cont1" ),
-                                        expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
-                                        ),
-                                        expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                                ),
-                                expectContainer( "depth2-cont2",
-                                        expectContainer( "depth3-cont2",
-                                                expectEmptyContainer( "depth4-cont2" ),
-                                                expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
-                                                ),
-                                                expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
-                                        ),
-                                        expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-                        ) );
+        response = target("/config/nested-module:depth1-cont").queryParam("depth", "4").request("application/xml")
+                .get();
+
+        verifyXMLResponse(
+                response,
+                expectContainer(
+                        "depth1-cont",
+                        expectContainer(
+                                "depth2-cont1",
+                                expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
+                                        expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
+                                expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
+                        expectContainer(
+                                "depth2-cont2",
+                                expectContainer("depth3-cont2", expectEmptyContainer("depth4-cont2"),
+                                        expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
+                                expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
+                        expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
 
         // Test config with depth 5
 
-        response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "5" )
-                .request( "application/xml" ).get();
-
-        verifyXMLResponse( response,
-                expectContainer( "depth1-cont",
-                        expectContainer( "depth2-cont1",
-                                expectContainer( "depth3-cont1",
-                                        expectContainer( "depth4-cont1",
-                                                expectLeaf( "depth5-leaf1", "depth5-leaf1-value" )
-                                                ),
-                                                expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
-                                        ),
-                                        expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                                ),
-                                expectContainer( "depth2-cont2",
-                                        expectContainer( "depth3-cont2",
-                                                expectContainer( "depth4-cont2",
-                                                        expectLeaf( "depth5-leaf2", "depth5-leaf2-value" )
-                                                        ),
-                                                        expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
-                                                ),
-                                                expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
-                                        ),
-                                        expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-                        ) );
+        response = target("/config/nested-module:depth1-cont").queryParam("depth", "5").request("application/xml")
+                .get();
+
+        verifyXMLResponse(
+                response,
+                expectContainer(
+                        "depth1-cont",
+                        expectContainer(
+                                "depth2-cont1",
+                                expectContainer(
+                                        "depth3-cont1",
+                                        expectContainer("depth4-cont1",
+                                                expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
+                                        expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
+                                expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
+                        expectContainer(
+                                "depth2-cont2",
+                                expectContainer(
+                                        "depth3-cont2",
+                                        expectContainer("depth4-cont2",
+                                                expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
+                                        expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
+                                expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
+                        expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
 
         // Test config with depth unbounded
 
-        response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "unbounded" )
-                .request( "application/xml" ).get();
-
-        verifyXMLResponse( response,
-                expectContainer( "depth1-cont",
-                        expectContainer( "depth2-cont1",
-                                expectContainer( "depth3-cont1",
-                                        expectContainer( "depth4-cont1",
-                                                expectLeaf( "depth5-leaf1", "depth5-leaf1-value" )
-                                                ),
-                                                expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
-                                        ),
-                                        expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                                ),
-                                expectContainer( "depth2-cont2",
-                                        expectContainer( "depth3-cont2",
-                                                expectContainer( "depth4-cont2",
-                                                        expectLeaf( "depth5-leaf2", "depth5-leaf2-value" )
-                                                        ),
-                                                        expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
-                                                ),
-                                                expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
-                                        ),
-                                        expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-                        ) );
+        response = target("/config/nested-module:depth1-cont").queryParam("depth", "unbounded")
+                .request("application/xml").get();
+
+        verifyXMLResponse(
+                response,
+                expectContainer(
+                        "depth1-cont",
+                        expectContainer(
+                                "depth2-cont1",
+                                expectContainer(
+                                        "depth3-cont1",
+                                        expectContainer("depth4-cont1",
+                                                expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
+                                        expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
+                                expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
+                        expectContainer(
+                                "depth2-cont2",
+                                expectContainer(
+                                        "depth3-cont2",
+                                        expectContainer("depth4-cont2",
+                                                expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
+                                        expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
+                                expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
+                        expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
 
         // Test operational
 
-        CompositeNode depth2Cont1 = toCompositeNode(
-                toCompositeNodeData( toNestedQName( "depth2-cont1" ),
-                        toCompositeNodeData( toNestedQName( "depth3-cont1" ),
-                                toCompositeNodeData( toNestedQName( "depth4-cont1" ),
-                                        toSimpleNodeData( toNestedQName( "depth5-leaf1" ), "depth5-leaf1-value" )
-                                        ),
-                                        toSimpleNodeData( toNestedQName( "depth4-leaf1" ), "depth4-leaf1-value" )
-                                ),
-                                toSimpleNodeData( toNestedQName( "depth3-leaf1" ), "depth3-leaf1-value" )
-                        ) );
-
-        when( brokerFacade.readOperationalData( any( InstanceIdentifier.class ) ) )
-        .thenReturn( depth2Cont1 );
-
-        response = target( "/operational/nested-module:depth1-cont/depth2-cont1" )
-                .queryParam( "depth", "3" ).request( "application/xml" ).get();
-
-        verifyXMLResponse( response,
-                expectContainer( "depth2-cont1",
-                        expectContainer( "depth3-cont1",
-                                expectEmptyContainer( "depth4-cont1" ),
-                                expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
-                                ),
-                                expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                        ) );
+        CompositeNode depth2Cont1 = toCompositeNode(toCompositeNodeData(
+                toNestedQName("depth2-cont1"),
+                toCompositeNodeData(
+                        toNestedQName("depth3-cont1"),
+                        toCompositeNodeData(toNestedQName("depth4-cont1"),
+                                toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
+                        toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
+                toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")));
+
+        when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(depth2Cont1);
+
+        response = target("/operational/nested-module:depth1-cont/depth2-cont1").queryParam("depth", "3")
+                .request("application/xml").get();
+
+        verifyXMLResponse(
+                response,
+                expectContainer(
+                        "depth2-cont1",
+                        expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
+                                expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
+                        expectLeaf("depth3-leaf1", "depth3-leaf1-value")));
     }
 
     @Test
     public void getDataWithInvalidDepthParameterTest() {
 
-        ControllerContext.getInstance().setGlobalSchema( schemaContextModules );
+        ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
 
-        final MultivaluedMap<String,String> paramMap = new MultivaluedHashMap<>();
-        paramMap.putSingle( "depth", "1o" );
-        UriInfo mockInfo = mock( UriInfo.class );
-        when( mockInfo.getQueryParameters( false ) ).thenAnswer(
-                new Answer<MultivaluedMap<String,String>>() {
-                    @Override
-                    public MultivaluedMap<String, String> answer( final InvocationOnMock invocation ) {
-                        return paramMap;
-                    }
-                } );
+        final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
+        paramMap.putSingle("depth", "1o");
+        UriInfo mockInfo = mock(UriInfo.class);
+        when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer<MultivaluedMap<String, String>>() {
+            @Override
+            public MultivaluedMap<String, String> answer(final InvocationOnMock invocation) {
+                return paramMap;
+            }
+        });
 
-        getDataWithInvalidDepthParameterTest( mockInfo );
+        getDataWithInvalidDepthParameterTest(mockInfo);
 
-        paramMap.putSingle( "depth", "0" );
-        getDataWithInvalidDepthParameterTest( mockInfo );
+        paramMap.putSingle("depth", "0");
+        getDataWithInvalidDepthParameterTest(mockInfo);
 
-        paramMap.putSingle( "depth", "-1" );
-        getDataWithInvalidDepthParameterTest( mockInfo );
+        paramMap.putSingle("depth", "-1");
+        getDataWithInvalidDepthParameterTest(mockInfo);
     }
 
-    private void getDataWithInvalidDepthParameterTest( final UriInfo uriInfo ) {
+    private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
         try {
-            restconfImpl.readConfigurationData( "nested-module:depth1-cont", uriInfo );
-            fail( "Expected RestconfDocumentedException" );
-        }
-        catch( RestconfDocumentedException e ) {
-            assertTrue( "Unexpected error message: " + e.getErrors().get( 0 ).getErrorMessage(),
-                    e.getErrors().get( 0 ).getErrorMessage().contains( "depth" ) );
+            restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
+            fail("Expected RestconfDocumentedException");
+        } catch (RestconfDocumentedException e) {
+            assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
+                    .getErrorMessage().contains("depth"));
         }
     }
 
-    private void verifyXMLResponse( final Response response, final NodeData nodeData ) {
+    private void verifyXMLResponse(final Response response, final NodeData nodeData) {
 
-        Document doc = TestUtils.loadDocumentFrom( (InputStream) response.getEntity() );
-        assertNotNull( "Could not parse XML document", doc );
+        Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity());
+        assertNotNull("Could not parse XML document", doc);
 
-        //System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
+        // System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
 
-        verifyContainerElement( doc.getDocumentElement(), nodeData );
+        verifyContainerElement(doc.getDocumentElement(), nodeData);
     }
 
     @SuppressWarnings("unchecked")
-    private void verifyContainerElement( final Element element, final NodeData nodeData ) {
+    private void verifyContainerElement(final Element element, final NodeData nodeData) {
 
-        assertEquals( "Element local name", nodeData.key, element.getNodeName() );
+        assertEquals("Element local name", nodeData.key, element.getNodeName());
 
         NodeList childNodes = element.getChildNodes();
-        if( nodeData.data == null ) { // empty container
-            assertTrue( "Expected no child elements for \"" + element.getNodeName() + "\"",
-                    childNodes.getLength() == 0 );
+        if (nodeData.data == null) { // empty container
+            assertTrue("Expected no child elements for \"" + element.getNodeName() + "\"", childNodes.getLength() == 0);
             return;
         }
 
-        Map<String,NodeData> expChildMap = Maps.newHashMap();
-        for( NodeData expChild: (List<NodeData>)nodeData.data ) {
-            expChildMap.put( expChild.key.toString(), expChild );
+        Map<String, NodeData> expChildMap = Maps.newHashMap();
+        for (NodeData expChild : (List<NodeData>) nodeData.data) {
+            expChildMap.put(expChild.key.toString(), expChild);
         }
 
-        for( int i = 0; i < childNodes.getLength(); i++ ) {
-            org.w3c.dom.Node actualChild = childNodes.item( i );
-            if( !( actualChild instanceof Element ) ) {
+        for (int i = 0; i < childNodes.getLength(); i++) {
+            org.w3c.dom.Node actualChild = childNodes.item(i);
+            if (!(actualChild instanceof Element)) {
                 continue;
             }
 
-            Element actualElement = (Element)actualChild;
-            NodeData expChild = expChildMap.remove( actualElement.getNodeName() );
-            assertNotNull( "Unexpected child element for parent \"" + element.getNodeName() +
-                    "\": " + actualElement.getNodeName(), expChild );
-
-            if( expChild.data == null || expChild.data instanceof List ) {
-                verifyContainerElement( actualElement, expChild );
-            }
-            else {
-                assertEquals( "Text content for element: " + actualElement.getNodeName(),
-                        expChild.data, actualElement.getTextContent() );
+            Element actualElement = (Element) actualChild;
+            NodeData expChild = expChildMap.remove(actualElement.getNodeName());
+            assertNotNull(
+                    "Unexpected child element for parent \"" + element.getNodeName() + "\": "
+                            + actualElement.getNodeName(), expChild);
+
+            if (expChild.data == null || expChild.data instanceof List) {
+                verifyContainerElement(actualElement, expChild);
+            else {
+                assertEquals("Text content for element: " + actualElement.getNodeName(), expChild.data,
+                        actualElement.getTextContent());
             }
         }
 
-        if( !expChildMap.isEmpty() ) {
-            fail( "Missing elements for parent \"" + element.getNodeName() +
-                    "\": " + expChildMap.keySet() );
+        if (!expChildMap.isEmpty()) {
+            fail("Missing elements for parent \"" + element.getNodeName() + "\": " + expChildMap.keySet());
         }
     }
 
-    private NodeData expectContainer( final String name, final NodeData... childData ) {
-        return new NodeData( name, Lists.newArrayList( childData ) );
+    private NodeData expectContainer(final String name, final NodeData... childData) {
+        return new NodeData(name, Lists.newArrayList(childData));
     }
 
-    private NodeData expectEmptyContainer( final String name ) {
-        return new NodeData( name, null );
+    private NodeData expectEmptyContainer(final String name) {
+        return new NodeData(name, null);
     }
 
-    private NodeData expectLeaf( final String name, final Object value ) {
-        return new NodeData( name, value );
+    private NodeData expectLeaf(final String name, final Object value) {
+        return new NodeData(name, value);
     }
 
-    private QName toNestedQName( final String localName ) {
-        return QName.create( "urn:nested:module", "2014-06-3", localName );
+    private QName toNestedQName(final String localName) {
+        return QName.create("urn:nested:module", "2014-06-3", localName);
     }
 
     @SuppressWarnings("unchecked")
-    private CompositeNode toCompositeNode( final NodeData nodeData ) {
+    private CompositeNode toCompositeNode(final NodeData nodeData) {
         CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
-        builder.setQName( (QName) nodeData.key );
+        builder.setQName((QName) nodeData.key);
 
-        for( NodeData child: (List<NodeData>)nodeData.data ) {
-            if( child.data instanceof List ) {
-                builder.add( toCompositeNode( child ) );
-            }
-            else {
-                builder.addLeaf( (QName) child.key, child.data );
+        for (NodeData child : (List<NodeData>) nodeData.data) {
+            if (child.data instanceof List) {
+                builder.add(toCompositeNode(child));
+            } else {
+                builder.addLeaf((QName) child.key, child.data);
             }
         }
 
         return builder.toInstance();
     }
 
-    private NodeData toCompositeNodeData( final QName key, final NodeData... childData ) {
-        return new NodeData( key, Lists.newArrayList( childData ) );
+    private NodeData toCompositeNodeData(final QName key, final NodeData... childData) {
+        return new NodeData(key, Lists.newArrayList(childData));
     }
 
-    private NodeData toSimpleNodeData( final QName key, final Object value ) {
-        return new NodeData( key, value );
+    private NodeData toSimpleNodeData(final QName key, final Object value) {
+        return new NodeData(key, value);
     }
 }
index 5b36fd52f78c329649fb3d593034d6bf028031f0..1442338e2c24292b181645e3e7e06005f206a112 100644 (file)
@@ -125,10 +125,12 @@ public class RestPostOperationTest extends JerseyTest {
         assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
 
         List<RpcError> rpcErrors = new ArrayList<>();
-        rpcErrors.add( RpcErrors.getRpcError("applicationTag1", "tag1", "info1", ErrorSeverity.ERROR, "message1", ErrorType.RPC, null));
-        rpcErrors.add( RpcErrors.getRpcError("applicationTag2", "tag2", "info2", ErrorSeverity.WARNING, "message2", ErrorType.PROTOCOL, null));
+        rpcErrors.add(RpcErrors.getRpcError("applicationTag1", "tag1", "info1", ErrorSeverity.ERROR, "message1",
+                ErrorType.RPC, null));
+        rpcErrors.add(RpcErrors.getRpcError("applicationTag2", "tag2", "info2", ErrorSeverity.WARNING, "message2",
+                ErrorType.PROTOCOL, null));
         mockInvokeRpc(null, false, rpcErrors);
-        assertEquals(500,post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
+        assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
 
         uri = "/operations/test-module:rpc-wrongtest";
         assertEquals(400, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
@@ -198,8 +200,8 @@ public class RestPostOperationTest extends JerseyTest {
             builder.errors(errors);
         }
         RpcResult<CompositeNode> rpcResult = builder.build();
-        when(brokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class)))
-                .thenReturn(Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
+        when(brokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
     }
 
     private void mockInvokeRpc(CompositeNode result, boolean sucessful) {
index c5c459618933af91bb272654d0b40b070fb7ffd3..b8c0270a61407a8358a741abe2515bc83395ef60 100644 (file)
@@ -78,63 +78,61 @@ import org.w3c.dom.NodeList;
 public class RestconfDocumentedExceptionMapperTest extends JerseyTest {
 
     interface ErrorInfoVerifier {
-        void verifyXML( Node errorInfoNode );
-        void verifyJson( JsonElement errorInfoElement );
+        void verifyXML(Node errorInfoNode);
+
+        void verifyJson(JsonElement errorInfoElement);
     }
 
     static class ComplexErrorInfoVerifier implements ErrorInfoVerifier {
 
         Map<String, String> expErrorInfo;
 
-        public ComplexErrorInfoVerifier( final Map<String, String> expErrorInfo ) {
+        public ComplexErrorInfoVerifier(final Map<String, String> expErrorInfo) {
             this.expErrorInfo = expErrorInfo;
         }
 
         @Override
-        public void verifyXML( final Node errorInfoNode ) {
+        public void verifyXML(final Node errorInfoNode) {
 
-            Map<String, String> mutableExpMap = Maps.newHashMap( expErrorInfo );
+            Map<String, String> mutableExpMap = Maps.newHashMap(expErrorInfo);
             NodeList childNodes = errorInfoNode.getChildNodes();
-            for( int i = 0; i < childNodes.getLength(); i++ ) {
-                Node child = childNodes.item( i );
-                if( child  instanceof Element ) {
-                    String expValue = mutableExpMap.remove( child.getNodeName() );
-                    assertNotNull( "Found unexpected \"error-info\" child node: " +
-                            child.getNodeName(), expValue );
-                    assertEquals( "Text content for \"error-info\" child node " +
-                            child.getNodeName(), expValue, child.getTextContent() );
+            for (int i = 0; i < childNodes.getLength(); i++) {
+                Node child = childNodes.item(i);
+                if (child instanceof Element) {
+                    String expValue = mutableExpMap.remove(child.getNodeName());
+                    assertNotNull("Found unexpected \"error-info\" child node: " + child.getNodeName(), expValue);
+                    assertEquals("Text content for \"error-info\" child node " + child.getNodeName(), expValue,
+                            child.getTextContent());
                 }
             }
 
-            if( !mutableExpMap.isEmpty() ) {
-                fail( "Missing \"error-info\" child nodes: " + mutableExpMap );
+            if (!mutableExpMap.isEmpty()) {
+                fail("Missing \"error-info\" child nodes: " + mutableExpMap);
             }
         }
 
         @Override
-        public void verifyJson( final JsonElement errorInfoElement ) {
+        public void verifyJson(final JsonElement errorInfoElement) {
 
-            assertTrue( "\"error-info\" Json element is not an Object",
-                    errorInfoElement.isJsonObject() );
+            assertTrue("\"error-info\" Json element is not an Object", errorInfoElement.isJsonObject());
 
             Map<String, String> actualErrorInfo = Maps.newHashMap();
-            for( Entry<String, JsonElement> entry: errorInfoElement.getAsJsonObject().entrySet() ) {
+            for (Entry<String, JsonElement> entry : errorInfoElement.getAsJsonObject().entrySet()) {
                 String leafName = entry.getKey();
                 JsonElement leafElement = entry.getValue();
-                actualErrorInfo.put( leafName, leafElement.getAsString() );
+                actualErrorInfo.put(leafName, leafElement.getAsString());
             }
 
-            Map<String, String> mutableExpMap = Maps.newHashMap( expErrorInfo );
-            for( Entry<String,String> actual: actualErrorInfo.entrySet() ) {
-                String expValue = mutableExpMap.remove( actual.getKey() );
-                assertNotNull( "Found unexpected \"error-info\" child node: " +
-                        actual.getKey(), expValue );
-                assertEquals( "Text content for \"error-info\" child node " +
-                        actual.getKey(), expValue, actual.getValue() );
+            Map<String, String> mutableExpMap = Maps.newHashMap(expErrorInfo);
+            for (Entry<String, String> actual : actualErrorInfo.entrySet()) {
+                String expValue = mutableExpMap.remove(actual.getKey());
+                assertNotNull("Found unexpected \"error-info\" child node: " + actual.getKey(), expValue);
+                assertEquals("Text content for \"error-info\" child node " + actual.getKey(), expValue,
+                        actual.getValue());
             }
 
-            if( !mutableExpMap.isEmpty() ) {
-                fail( "Missing \"error-info\" child nodes: " + mutableExpMap );
+            if (!mutableExpMap.isEmpty()) {
+                fail("Missing \"error-info\" child nodes: " + mutableExpMap);
             }
         }
     }
@@ -143,27 +141,27 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest {
 
         String expTextContent;
 
-        public SimpleErrorInfoVerifier( final String expErrorInfo ) {
+        public SimpleErrorInfoVerifier(final String expErrorInfo) {
             this.expTextContent = expErrorInfo;
         }
 
-        void verifyContent( final String actualContent ) {
-            assertNotNull( "Actual \"error-info\" text content is null", actualContent );
-            assertTrue( "", actualContent.contains( expTextContent ) );
+        void verifyContent(final String actualContent) {
+            assertNotNull("Actual \"error-info\" text content is null", actualContent);
+            assertTrue("", actualContent.contains(expTextContent));
         }
 
         @Override
-        public void verifyXML( final Node errorInfoNode ) {
-            verifyContent( errorInfoNode.getTextContent() );
+        public void verifyXML(final Node errorInfoNode) {
+            verifyContent(errorInfoNode.getTextContent());
         }
 
         @Override
-        public void verifyJson( final JsonElement errorInfoElement ) {
-            verifyContent( errorInfoElement.getAsString() );
+        public void verifyJson(final JsonElement errorInfoElement) {
+            verifyContent(errorInfoElement.getAsString());
         }
     }
 
-    static RestconfService mockRestConf = mock( RestconfService.class );
+    static RestconfService mockRestConf = mock(RestconfService.class);
 
     static XPath XPATH = XPathFactory.newInstance().newXPath();
     static XPathExpression ERROR_LIST;
@@ -175,745 +173,650 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest {
 
     @BeforeClass
     public static void init() throws Exception {
-        ControllerContext.getInstance().setGlobalSchema( TestUtils.loadSchemaContext("/modules") );
+        ControllerContext.getInstance().setGlobalSchema(TestUtils.loadSchemaContext("/modules"));
 
         NamespaceContext nsContext = new NamespaceContext() {
             @Override
-            public Iterator<?> getPrefixes( final String namespaceURI ) {
+            public Iterator<?> getPrefixes(final String namespaceURI) {
                 return null;
             }
 
             @Override
-            public String getPrefix( final String namespaceURI ) {
+            public String getPrefix(final String namespaceURI) {
                 return null;
             }
 
             @Override
-            public String getNamespaceURI( final String prefix ) {
-                return "ietf-restconf".equals( prefix ) ? Draft02.RestConfModule.NAMESPACE : null;
+            public String getNamespaceURI(final String prefix) {
+                return "ietf-restconf".equals(prefix) ? Draft02.RestConfModule.NAMESPACE : null;
             }
         };
 
-        XPATH.setNamespaceContext( nsContext );
-        ERROR_LIST = XPATH.compile( "ietf-restconf:errors/ietf-restconf:error" );
-        ERROR_TYPE = XPATH.compile( "ietf-restconf:error-type" );
-        ERROR_TAG = XPATH.compile( "ietf-restconf:error-tag" );
-        ERROR_MESSAGE = XPATH.compile( "ietf-restconf:error-message" );
-        ERROR_APP_TAG = XPATH.compile( "ietf-restconf:error-app-tag" );
-        ERROR_INFO = XPATH.compile( "ietf-restconf:error-info" );
+        XPATH.setNamespaceContext(nsContext);
+        ERROR_LIST = XPATH.compile("ietf-restconf:errors/ietf-restconf:error");
+        ERROR_TYPE = XPATH.compile("ietf-restconf:error-type");
+        ERROR_TAG = XPATH.compile("ietf-restconf:error-tag");
+        ERROR_MESSAGE = XPATH.compile("ietf-restconf:error-message");
+        ERROR_APP_TAG = XPATH.compile("ietf-restconf:error-app-tag");
+        ERROR_INFO = XPATH.compile("ietf-restconf:error-info");
     }
 
     @Override
     @Before
     public void setUp() throws Exception {
-        reset( mockRestConf );
+        reset(mockRestConf);
         super.setUp();
     }
 
     @Override
     protected Application configure() {
         ResourceConfig resourceConfig = new ResourceConfig();
-        resourceConfig = resourceConfig.registerInstances( mockRestConf, StructuredDataToXmlProvider.INSTANCE,
-                StructuredDataToJsonProvider.INSTANCE );
-        resourceConfig.registerClasses( RestconfDocumentedExceptionMapper.class );
+        resourceConfig = resourceConfig.registerInstances(mockRestConf, StructuredDataToXmlProvider.INSTANCE,
+                StructuredDataToJsonProvider.INSTANCE);
+        resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
         return resourceConfig;
     }
 
-    void stageMockEx( final RestconfDocumentedException ex ) {
-        reset( mockRestConf );
-        when( mockRestConf.readOperationalData( any( String.class ), any( UriInfo.class ) ) ).thenThrow( ex );
+    void stageMockEx(final RestconfDocumentedException ex) {
+        reset(mockRestConf);
+        when(mockRestConf.readOperationalData(any(String.class), any(UriInfo.class))).thenThrow(ex);
     }
 
-    void testJsonResponse( final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType,
+    void testJsonResponse(final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType,
             final ErrorTag expErrorTag, final String expErrorMessage, final String expErrorAppTag,
-            final ErrorInfoVerifier errorInfoVerifier ) throws Exception {
+            final ErrorInfoVerifier errorInfoVerifier) throws Exception {
 
-        stageMockEx( ex );
+        stageMockEx(ex);
 
-        Response resp = target("/operational/foo").request( MediaType.APPLICATION_JSON ).get();
+        Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get();
 
-        InputStream stream = verifyResponse( resp, MediaType.APPLICATION_JSON, expStatus );
+        InputStream stream = verifyResponse(resp, MediaType.APPLICATION_JSON, expStatus);
 
-        verifyJsonResponseBody( stream, expErrorType, expErrorTag, expErrorMessage,
-                expErrorAppTag, errorInfoVerifier );
+        verifyJsonResponseBody(stream, expErrorType, expErrorTag, expErrorMessage, expErrorAppTag, errorInfoVerifier);
     }
 
     @Test
     public void testToJsonResponseWithMessageOnly() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error" ), Status.INTERNAL_SERVER_ERROR,
-                ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error"), Status.INTERNAL_SERVER_ERROR,
+                ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null);
 
         // To test verification code
-        //        String json =
-        //            "{ errors: {" +
-        //            "    error: [{" +
-        //            "      error-tag : \"operation-failed\"" +
-        //            "      ,error-type : \"application\"" +
-        //            "      ,error-message : \"An error occurred\"" +
-        //            "      ,error-info : {" +
-        //            "        session-id: \"123\"" +
-        //            "        ,address: \"1.2.3.4\"" +
-        //            "      }" +
-        //            "    }]" +
-        //            "  }" +
-        //            "}";
+        // String json =
+        // "{ errors: {" +
+        // "    error: [{" +
+        // "      error-tag : \"operation-failed\"" +
+        // "      ,error-type : \"application\"" +
+        // "      ,error-message : \"An error occurred\"" +
+        // "      ,error-info : {" +
+        // "        session-id: \"123\"" +
+        // "        ,address: \"1.2.3.4\"" +
+        // "      }" +
+        // "    }]" +
+        // "  }" +
+        // "}";
         //
-        //        verifyJsonResponseBody( new java.io.StringBufferInputStream(json ), ErrorType.APPLICATION,
-        //            ErrorTag.OPERATION_FAILED, "An error occurred", null,
-        //            com.google.common.collect.ImmutableMap.of( "session-id", "123", "address", "1.2.3.4" ) );
+        // verifyJsonResponseBody( new java.io.StringBufferInputStream(json ),
+        // ErrorType.APPLICATION,
+        // ErrorTag.OPERATION_FAILED, "An error occurred", null,
+        // com.google.common.collect.ImmutableMap.of( "session-id", "123",
+        // "address", "1.2.3.4" ) );
     }
 
     @Test
     public void testToJsonResponseWithInUseErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.IN_USE ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.IN_USE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.IN_USE),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.IN_USE, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithInvalidValueErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.RPC,
-                ErrorTag.INVALID_VALUE ),
-                Status.BAD_REQUEST, ErrorType.RPC,
-                ErrorTag.INVALID_VALUE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.RPC, ErrorTag.INVALID_VALUE),
+                Status.BAD_REQUEST, ErrorType.RPC, ErrorTag.INVALID_VALUE, "mock error", null, null);
 
     }
 
     @Test
     public void testToJsonResponseWithTooBigErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.TRANSPORT,
-                ErrorTag.TOO_BIG ),
-                Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT,
-                ErrorTag.TOO_BIG, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.TRANSPORT, ErrorTag.TOO_BIG),
+                Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT, ErrorTag.TOO_BIG, "mock error", null, null);
 
     }
 
     @Test
     public void testToJsonResponseWithMissingAttributeErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.MISSING_ATTRIBUTE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithBadAttributeErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.BAD_ATTRIBUTE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.BAD_ATTRIBUTE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock error", null, null);
     }
+
     @Test
     public void testToJsonResponseWithUnknownAttributeErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ATTRIBUTE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithBadElementErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.BAD_ELEMENT ),
-                Status.BAD_REQUEST,
-                ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithUnknownElementErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ELEMENT ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithUnknownNamespaceErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_NAMESPACE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithMalformedMessageErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.MALFORMED_MESSAGE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.MALFORMED_MESSAGE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithAccessDeniedErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.ACCESS_DENIED ),
-                Status.FORBIDDEN, ErrorType.PROTOCOL,
-                ErrorTag.ACCESS_DENIED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED),
+                Status.FORBIDDEN, ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithLockDeniedErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.LOCK_DENIED ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.LOCK_DENIED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithResourceDeniedErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.RESOURCE_DENIED ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.RESOURCE_DENIED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithRollbackFailedErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.ROLLBACK_FAILED ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL,
-                ErrorTag.ROLLBACK_FAILED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED),
+                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithDataExistsErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.DATA_EXISTS ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.DATA_EXISTS, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithDataMissingErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.DATA_MISSING ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.DATA_MISSING, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithOperationNotSupportedErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_NOT_SUPPORTED ),
-                Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL,
+                ErrorTag.OPERATION_NOT_SUPPORTED), Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL,
+                ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithOperationFailedErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_FAILED ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_FAILED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED),
+                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithPartialOperationErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.PARTIAL_OPERATION ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL,
-                ErrorTag.PARTIAL_OPERATION, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION),
+                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithErrorAppTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( new RestconfError(
-                ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
-                "mock error", "mock-app-tag" ) ),
-                Status.BAD_REQUEST, ErrorType.APPLICATION,
-                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null );
+        testJsonResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION,
+                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag")), Status.BAD_REQUEST, ErrorType.APPLICATION,
+                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null);
     }
 
     @Test
     public void testToJsonResponseWithMultipleErrors() throws Exception {
 
-        List<RestconfError> errorList = Arrays.asList(
-                new RestconfError( ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1" ),
-                new RestconfError( ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2" ) );
-        stageMockEx( new RestconfDocumentedException( errorList ) );
+        List<RestconfError> errorList = Arrays.asList(new RestconfError(ErrorType.APPLICATION, ErrorTag.LOCK_DENIED,
+                "mock error1"), new RestconfError(ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2"));
+        stageMockEx(new RestconfDocumentedException(errorList));
 
-        Response resp = target("/operational/foo").request( MediaType.APPLICATION_JSON ).get();
+        Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get();
 
-        InputStream stream = verifyResponse( resp, MediaType.APPLICATION_JSON, Status.CONFLICT );
+        InputStream stream = verifyResponse(resp, MediaType.APPLICATION_JSON, Status.CONFLICT);
 
-        JsonArray arrayElement = parseJsonErrorArrayElement( stream );
+        JsonArray arrayElement = parseJsonErrorArrayElement(stream);
 
-        assertEquals( "\"error\" Json array element length", 2, arrayElement.size() );
+        assertEquals("\"error\" Json array element length", 2, arrayElement.size());
 
-        verifyJsonErrorNode( arrayElement.get( 0 ), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED,
-                "mock error1", null, null );
+        verifyJsonErrorNode(arrayElement.get(0), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1", null, null);
 
-        verifyJsonErrorNode( arrayElement.get( 1 ), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED,
-                "mock error2", null, null );
+        verifyJsonErrorNode(arrayElement.get(1), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2", null, null);
     }
 
     @Test
     public void testToJsonResponseWithErrorInfo() throws Exception {
 
         String errorInfo = "<address>1.2.3.4</address> <session-id>123</session-id>";
-        testJsonResponse( new RestconfDocumentedException( new RestconfError(
-                ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
-                "mock error", "mock-app-tag", errorInfo ) ),
-                Status.BAD_REQUEST, ErrorType.APPLICATION,
-                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag",
-                new ComplexErrorInfoVerifier( ImmutableMap.of(
-                        "session-id", "123", "address", "1.2.3.4" ) ) );
+        testJsonResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION,
+                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", errorInfo)), Status.BAD_REQUEST,
+                ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag",
+                new ComplexErrorInfoVerifier(ImmutableMap.of("session-id", "123", "address", "1.2.3.4")));
     }
 
     @Test
     public void testToJsonResponseWithExceptionCause() throws Exception {
 
-        Exception cause = new Exception( "mock exception cause" );
-        testJsonResponse( new RestconfDocumentedException( "mock error", cause ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.APPLICATION,
-                ErrorTag.OPERATION_FAILED, "mock error", null,
-                new SimpleErrorInfoVerifier( cause.getMessage() ) );
+        Exception cause = new Exception("mock exception cause");
+        testJsonResponse(new RestconfDocumentedException("mock error", cause), Status.INTERNAL_SERVER_ERROR,
+                ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null,
+                new SimpleErrorInfoVerifier(cause.getMessage()));
     }
 
-    void testXMLResponse( final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType,
-            final ErrorTag expErrorTag, final String expErrorMessage,
-            final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier ) throws Exception
-    {
-        stageMockEx( ex );
+    void testXMLResponse(final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType,
+            final ErrorTag expErrorTag, final String expErrorMessage, final String expErrorAppTag,
+            final ErrorInfoVerifier errorInfoVerifier) throws Exception {
+        stageMockEx(ex);
 
-        Response resp = target("/operational/foo").request( MediaType.APPLICATION_XML ).get();
+        Response resp = target("/operational/foo").request(MediaType.APPLICATION_XML).get();
 
-        InputStream stream = verifyResponse( resp, MediaType.APPLICATION_XML, expStatus );
+        InputStream stream = verifyResponse(resp, MediaType.APPLICATION_XML, expStatus);
 
-        verifyXMLResponseBody( stream, expErrorType, expErrorTag, expErrorMessage,
-                expErrorAppTag, errorInfoVerifier );
+        verifyXMLResponseBody(stream, expErrorType, expErrorTag, expErrorMessage, expErrorAppTag, errorInfoVerifier);
     }
 
     @Test
     public void testToXMLResponseWithMessageOnly() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error" ), Status.INTERNAL_SERVER_ERROR,
-                ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error"), Status.INTERNAL_SERVER_ERROR,
+                ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null);
 
         // To test verification code
-        //        String xml =
-        //            "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">"+
-        //            "  <error>" +
-        //            "    <error-type>application</error-type>"+
-        //            "    <error-tag>operation-failed</error-tag>"+
-        //            "    <error-message>An error occurred</error-message>"+
-        //            "    <error-info>" +
-        //            "      <session-id>123</session-id>" +
-        //            "      <address>1.2.3.4</address>" +
-        //            "    </error-info>" +
-        //            "  </error>" +
-        //            "</errors>";
+        // String xml =
+        // "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">"+
+        // "  <error>" +
+        // "    <error-type>application</error-type>"+
+        // "    <error-tag>operation-failed</error-tag>"+
+        // "    <error-message>An error occurred</error-message>"+
+        // "    <error-info>" +
+        // "      <session-id>123</session-id>" +
+        // "      <address>1.2.3.4</address>" +
+        // "    </error-info>" +
+        // "  </error>" +
+        // "</errors>";
         //
-        //        verifyXMLResponseBody( new java.io.StringBufferInputStream(xml), ErrorType.APPLICATION,
-        //                ErrorTag.OPERATION_FAILED, "An error occurred", null,
-        //                com.google.common.collect.ImmutableMap.of( "session-id", "123", "address", "1.2.3.4" ) );
+        // verifyXMLResponseBody( new java.io.StringBufferInputStream(xml),
+        // ErrorType.APPLICATION,
+        // ErrorTag.OPERATION_FAILED, "An error occurred", null,
+        // com.google.common.collect.ImmutableMap.of( "session-id", "123",
+        // "address", "1.2.3.4" ) );
     }
 
     @Test
     public void testToXMLResponseWithInUseErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.IN_USE ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.IN_USE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.IN_USE),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.IN_USE, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithInvalidValueErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.RPC,
-                ErrorTag.INVALID_VALUE ),
-                Status.BAD_REQUEST, ErrorType.RPC,
-                ErrorTag.INVALID_VALUE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.RPC, ErrorTag.INVALID_VALUE),
+                Status.BAD_REQUEST, ErrorType.RPC, ErrorTag.INVALID_VALUE, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithTooBigErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.TRANSPORT,
-                ErrorTag.TOO_BIG ),
-                Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT,
-                ErrorTag.TOO_BIG, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.TRANSPORT, ErrorTag.TOO_BIG),
+                Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT, ErrorTag.TOO_BIG, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithMissingAttributeErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.MISSING_ATTRIBUTE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithBadAttributeErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.BAD_ATTRIBUTE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.BAD_ATTRIBUTE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock error", null, null);
     }
+
     @Test
     public void testToXMLResponseWithUnknownAttributeErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ATTRIBUTE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithBadElementErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.BAD_ELEMENT ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.BAD_ELEMENT, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithUnknownElementErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ELEMENT ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithUnknownNamespaceErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_NAMESPACE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithMalformedMessageErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.MALFORMED_MESSAGE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.MALFORMED_MESSAGE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithAccessDeniedErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.ACCESS_DENIED ),
-                Status.FORBIDDEN, ErrorType.PROTOCOL,
-                ErrorTag.ACCESS_DENIED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED),
+                Status.FORBIDDEN, ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithLockDeniedErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.LOCK_DENIED ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.LOCK_DENIED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithResourceDeniedErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.RESOURCE_DENIED ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.RESOURCE_DENIED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithRollbackFailedErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.ROLLBACK_FAILED ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL,
-                ErrorTag.ROLLBACK_FAILED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED),
+                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithDataExistsErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.DATA_EXISTS ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.DATA_EXISTS, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithDataMissingErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.DATA_MISSING ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.DATA_MISSING, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithOperationNotSupportedErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_NOT_SUPPORTED ),
-                Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL,
+                ErrorTag.OPERATION_NOT_SUPPORTED), Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL,
+                ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithOperationFailedErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_FAILED ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_FAILED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED),
+                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithPartialOperationErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.PARTIAL_OPERATION ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL,
-                ErrorTag.PARTIAL_OPERATION, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION),
+                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithErrorAppTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( new RestconfError(
-                ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
-                "mock error", "mock-app-tag" ) ),
-                Status.BAD_REQUEST, ErrorType.APPLICATION,
-                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null );
+        testXMLResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION,
+                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag")), Status.BAD_REQUEST, ErrorType.APPLICATION,
+                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null);
     }
 
     @Test
     public void testToXMLResponseWithErrorInfo() throws Exception {
 
         String errorInfo = "<address>1.2.3.4</address> <session-id>123</session-id>";
-        testXMLResponse( new RestconfDocumentedException( new RestconfError(
-                ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
-                "mock error", "mock-app-tag", errorInfo ) ),
-                Status.BAD_REQUEST, ErrorType.APPLICATION,
-                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag",
-                new ComplexErrorInfoVerifier( ImmutableMap.of(
-                        "session-id", "123", "address", "1.2.3.4" ) ) );
+        testXMLResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION,
+                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", errorInfo)), Status.BAD_REQUEST,
+                ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag",
+                new ComplexErrorInfoVerifier(ImmutableMap.of("session-id", "123", "address", "1.2.3.4")));
     }
 
     @Test
     public void testToXMLResponseWithExceptionCause() throws Exception {
 
-        Exception cause = new Exception( "mock exception cause" );
-        testXMLResponse( new RestconfDocumentedException( "mock error", cause ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.APPLICATION,
-                ErrorTag.OPERATION_FAILED, "mock error", null,
-                new SimpleErrorInfoVerifier( cause.getMessage() ) );
+        Exception cause = new Exception("mock exception cause");
+        testXMLResponse(new RestconfDocumentedException("mock error", cause), Status.INTERNAL_SERVER_ERROR,
+                ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null,
+                new SimpleErrorInfoVerifier(cause.getMessage()));
     }
 
     @Test
     public void testToXMLResponseWithMultipleErrors() throws Exception {
 
-        List<RestconfError> errorList = Arrays.asList(
-                new RestconfError( ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1" ),
-                new RestconfError( ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2" ) );
-        stageMockEx( new RestconfDocumentedException( errorList ) );
+        List<RestconfError> errorList = Arrays.asList(new RestconfError(ErrorType.APPLICATION, ErrorTag.LOCK_DENIED,
+                "mock error1"), new RestconfError(ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2"));
+        stageMockEx(new RestconfDocumentedException(errorList));
 
-        Response resp = target("/operational/foo").request( MediaType.APPLICATION_XML ).get();
+        Response resp = target("/operational/foo").request(MediaType.APPLICATION_XML).get();
 
-        InputStream stream = verifyResponse( resp, MediaType.APPLICATION_XML, Status.CONFLICT );
+        InputStream stream = verifyResponse(resp, MediaType.APPLICATION_XML, Status.CONFLICT);
 
-        Document doc = parseXMLDocument( stream );
+        Document doc = parseXMLDocument(stream);
 
-        NodeList children = getXMLErrorList( doc, 2 );
+        NodeList children = getXMLErrorList(doc, 2);
 
-        verifyXMLErrorNode( children.item( 0 ), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED,
-                "mock error1", null, null );
+        verifyXMLErrorNode(children.item(0), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1", null, null);
 
-        verifyXMLErrorNode( children.item( 1 ), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED,
-                "mock error2", null, null );
+        verifyXMLErrorNode(children.item(1), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2", null, null);
     }
 
     @Test
     public void testToResponseWithAcceptHeader() throws Exception {
 
-        stageMockEx( new RestconfDocumentedException( "mock error" ) );
+        stageMockEx(new RestconfDocumentedException("mock error"));
 
-        Response resp = target("/operational/foo")
-                .request().header( "Accept", MediaType.APPLICATION_JSON ).get();
+        Response resp = target("/operational/foo").request().header("Accept", MediaType.APPLICATION_JSON).get();
 
-        InputStream stream = verifyResponse( resp, MediaType.APPLICATION_JSON,
-                Status.INTERNAL_SERVER_ERROR );
+        InputStream stream = verifyResponse(resp, MediaType.APPLICATION_JSON, Status.INTERNAL_SERVER_ERROR);
 
-        verifyJsonResponseBody( stream, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error",
-                null, null );
+        verifyJsonResponseBody(stream, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null);
     }
 
     @Test
     public void testToResponseWithStatusOnly() throws Exception {
 
-        // The StructuredDataToJsonProvider should throw a RestconfDocumentedException with no data
+        // The StructuredDataToJsonProvider should throw a
+        // RestconfDocumentedException with no data
 
-        when( mockRestConf.readOperationalData( any( String.class ), any( UriInfo.class ) ) )
-            .thenReturn( new StructuredData( null, null, null ) );
+        when(mockRestConf.readOperationalData(any(String.class), any(UriInfo.class))).thenReturn(
+                new StructuredData(null, null, null));
 
-        Response resp = target("/operational/foo").request( MediaType.APPLICATION_JSON ).get();
+        Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get();
 
-        verifyResponse( resp, MediaType.TEXT_PLAIN, Status.NOT_FOUND );
+        verifyResponse(resp, MediaType.TEXT_PLAIN, Status.NOT_FOUND);
     }
 
-    InputStream verifyResponse( final Response resp, final String expMediaType, final Status expStatus ) {
-        assertEquals( "getMediaType", MediaType.valueOf( expMediaType ), resp.getMediaType() );
-        assertEquals( "getStatus", expStatus.getStatusCode(), resp.getStatus() );
+    InputStream verifyResponse(final Response resp, final String expMediaType, final Status expStatus) {
+        assertEquals("getMediaType", MediaType.valueOf(expMediaType), resp.getMediaType());
+        assertEquals("getStatus", expStatus.getStatusCode(), resp.getStatus());
 
         Object entity = resp.getEntity();
-        assertEquals( "Response entity", true, entity instanceof InputStream );
-        InputStream stream = (InputStream)entity;
+        assertEquals("Response entity", true, entity instanceof InputStream);
+        InputStream stream = (InputStream) entity;
         return stream;
     }
 
-    void verifyJsonResponseBody( final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag,
-            final String expErrorMessage, final String expErrorAppTag,
-            final ErrorInfoVerifier errorInfoVerifier ) throws Exception {
+    void verifyJsonResponseBody(final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag,
+            final String expErrorMessage, final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier)
+            throws Exception {
 
-        JsonArray arrayElement = parseJsonErrorArrayElement( stream );
+        JsonArray arrayElement = parseJsonErrorArrayElement(stream);
 
-        assertEquals( "\"error\" Json array element length", 1, arrayElement.size() );
+        assertEquals("\"error\" Json array element length", 1, arrayElement.size());
 
-        verifyJsonErrorNode( arrayElement.get( 0 ),  expErrorType, expErrorTag, expErrorMessage,
-                expErrorAppTag, errorInfoVerifier );
+        verifyJsonErrorNode(arrayElement.get(0), expErrorType, expErrorTag, expErrorMessage, expErrorAppTag,
+                errorInfoVerifier);
     }
 
-    private JsonArray parseJsonErrorArrayElement( final InputStream stream ) throws IOException {
+    private JsonArray parseJsonErrorArrayElement(final InputStream stream) throws IOException {
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        ByteStreams.copy( stream, bos );
+        ByteStreams.copy(stream, bos);
 
-        System.out.println("JSON: "+bos.toString());
+        System.out.println("JSON: " + bos.toString());
 
         JsonParser parser = new JsonParser();
         JsonElement rootElement;
 
         try {
-            rootElement = parser.parse(
-                    new InputStreamReader( new ByteArrayInputStream( bos.toByteArray() ) ) );
-        }
-        catch( Exception e ) {
-            throw new IllegalArgumentException( "Invalid JSON response:\n" + bos.toString(), e );
+            rootElement = parser.parse(new InputStreamReader(new ByteArrayInputStream(bos.toByteArray())));
+        } catch (Exception e) {
+            throw new IllegalArgumentException("Invalid JSON response:\n" + bos.toString(), e);
         }
 
-        assertTrue( "Root element of Json is not an Object", rootElement.isJsonObject() );
+        assertTrue("Root element of Json is not an Object", rootElement.isJsonObject());
 
         Set<Entry<String, JsonElement>> errorsEntrySet = rootElement.getAsJsonObject().entrySet();
-        assertEquals( "Json Object element set count", 1, errorsEntrySet.size() );
+        assertEquals("Json Object element set count", 1, errorsEntrySet.size());
 
         Entry<String, JsonElement> errorsEntry = errorsEntrySet.iterator().next();
         JsonElement errorsElement = errorsEntry.getValue();
-        assertEquals( "First Json element name", "errors", errorsEntry.getKey() );
-        assertTrue( "\"errors\" Json element is not an Object", errorsElement.isJsonObject() );
+        assertEquals("First Json element name", "errors", errorsEntry.getKey());
+        assertTrue("\"errors\" Json element is not an Object", errorsElement.isJsonObject());
 
         Set<Entry<String, JsonElement>> errorListEntrySet = errorsElement.getAsJsonObject().entrySet();
-        assertEquals( "Root \"errors\" element child count", 1, errorListEntrySet.size() );
+        assertEquals("Root \"errors\" element child count", 1, errorListEntrySet.size());
 
         JsonElement errorListElement = errorListEntrySet.iterator().next().getValue();
-        assertEquals( "\"errors\" child Json element name", "error",
-                errorListEntrySet.iterator().next().getKey() );
-        assertTrue( "\"error\" Json element is not an Array", errorListElement.isJsonArray() );
+        assertEquals("\"errors\" child Json element name", "error", errorListEntrySet.iterator().next().getKey());
+        assertTrue("\"error\" Json element is not an Array", errorListElement.isJsonArray());
 
-        // As a final check, make sure there aren't multiple "error" array elements. Unfortunately,
-        // the call above to getAsJsonObject().entrySet() will out duplicate "error" elements. So
+        // As a final check, make sure there aren't multiple "error" array
+        // elements. Unfortunately,
+        // the call above to getAsJsonObject().entrySet() will out duplicate
+        // "error" elements. So
         // we'll use regex on the json string to verify this.
 
-        Matcher matcher = Pattern.compile( "\"error\"[ ]*:[ ]*\\[", Pattern.DOTALL ).matcher( bos.toString() );
-        assertTrue( "Expected 1 \"error\" element", matcher.find() );
-        assertFalse( "Found multiple \"error\" elements", matcher.find() );
+        Matcher matcher = Pattern.compile("\"error\"[ ]*:[ ]*\\[", Pattern.DOTALL).matcher(bos.toString());
+        assertTrue("Expected 1 \"error\" element", matcher.find());
+        assertFalse("Found multiple \"error\" elements", matcher.find());
 
         return errorListElement.getAsJsonArray();
     }
 
-    void verifyJsonErrorNode( final JsonElement errorEntryElement, final ErrorType expErrorType, final ErrorTag expErrorTag,
-            final String expErrorMessage, final String expErrorAppTag,
-            final ErrorInfoVerifier errorInfoVerifier ) {
+    void verifyJsonErrorNode(final JsonElement errorEntryElement, final ErrorType expErrorType,
+            final ErrorTag expErrorTag, final String expErrorMessage, final String expErrorAppTag,
+            final ErrorInfoVerifier errorInfoVerifier) {
 
         JsonElement errorInfoElement = null;
         Map<String, String> leafMap = Maps.newHashMap();
-        for( Entry<String, JsonElement> entry: errorEntryElement.getAsJsonObject().entrySet() ) {
+        for (Entry<String, JsonElement> entry : errorEntryElement.getAsJsonObject().entrySet()) {
             String leafName = entry.getKey();
             JsonElement leafElement = entry.getValue();
 
-            if( "error-info".equals( leafName ) ) {
-                assertNotNull( "Found unexpected \"error-info\" element", errorInfoVerifier );
+            if ("error-info".equals(leafName)) {
+                assertNotNull("Found unexpected \"error-info\" element", errorInfoVerifier);
                 errorInfoElement = leafElement;
-            }
-            else {
-                assertTrue( "\"error\" leaf Json element " + leafName +
-                        " is not a Primitive", leafElement.isJsonPrimitive() );
+            } else {
+                assertTrue("\"error\" leaf Json element " + leafName + " is not a Primitive",
+                        leafElement.isJsonPrimitive());
 
-                leafMap.put( leafName, leafElement.getAsString() );
+                leafMap.put(leafName, leafElement.getAsString());
             }
         }
 
-        assertEquals( "error-type", expErrorType.getErrorTypeTag(), leafMap.remove( "error-type" ) );
-        assertEquals( "error-tag", expErrorTag.getTagValue(), leafMap.remove( "error-tag" ) );
+        assertEquals("error-type", expErrorType.getErrorTypeTag(), leafMap.remove("error-type"));
+        assertEquals("error-tag", expErrorTag.getTagValue(), leafMap.remove("error-tag"));
 
-        verifyOptionalJsonLeaf( leafMap.remove( "error-message" ), expErrorMessage, "error-message" );
-        verifyOptionalJsonLeaf( leafMap.remove( "error-app-tag" ), expErrorAppTag, "error-app-tag" );
+        verifyOptionalJsonLeaf(leafMap.remove("error-message"), expErrorMessage, "error-message");
+        verifyOptionalJsonLeaf(leafMap.remove("error-app-tag"), expErrorAppTag, "error-app-tag");
 
-        if( !leafMap.isEmpty() ) {
-            fail( "Found unexpected Json leaf elements for \"error\" element: " + leafMap );
+        if (!leafMap.isEmpty()) {
+            fail("Found unexpected Json leaf elements for \"error\" element: " + leafMap);
         }
 
-        if( errorInfoVerifier != null ) {
-            assertNotNull( "Missing \"error-info\" element", errorInfoElement );
-            errorInfoVerifier.verifyJson( errorInfoElement );
+        if (errorInfoVerifier != null) {
+            assertNotNull("Missing \"error-info\" element", errorInfoElement);
+            errorInfoVerifier.verifyJson(errorInfoElement);
         }
     }
 
-    void verifyOptionalJsonLeaf( final String actualValue, final String expValue, final String tagName ) {
-        if( expValue != null ) {
-            assertEquals( tagName, expValue, actualValue );
-        }
-        else {
-            assertNull( "Found unexpected \"error\" leaf entry for: " + tagName, actualValue );
+    void verifyOptionalJsonLeaf(final String actualValue, final String expValue, final String tagName) {
+        if (expValue != null) {
+            assertEquals(tagName, expValue, actualValue);
+        } else {
+            assertNull("Found unexpected \"error\" leaf entry for: " + tagName, actualValue);
         }
     }
 
-    void verifyXMLResponseBody( final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag,
-            final String expErrorMessage, final String expErrorAppTag,
-            final ErrorInfoVerifier errorInfoVerifier )
-                    throws Exception {
+    void verifyXMLResponseBody(final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag,
+            final String expErrorMessage, final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier)
+            throws Exception {
 
-        Document doc = parseXMLDocument( stream );
+        Document doc = parseXMLDocument(stream);
 
-        NodeList children = getXMLErrorList( doc, 1 );
+        NodeList children = getXMLErrorList(doc, 1);
 
-        verifyXMLErrorNode( children.item( 0 ), expErrorType, expErrorTag, expErrorMessage,
-                expErrorAppTag, errorInfoVerifier );
+        verifyXMLErrorNode(children.item(0), expErrorType, expErrorTag, expErrorMessage, expErrorAppTag,
+                errorInfoVerifier);
     }
 
-    private Document parseXMLDocument( final InputStream stream ) throws IOException {
+    private Document parseXMLDocument(final InputStream stream) throws IOException {
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         factory.setNamespaceAware(true);
         factory.setCoalescing(true);
@@ -921,60 +824,57 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest {
         factory.setIgnoringComments(true);
 
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        ByteStreams.copy( stream, bos );
+        ByteStreams.copy(stream, bos);
 
-        System.out.println("XML: "+bos.toString());
+        System.out.println("XML: " + bos.toString());
 
         Document doc = null;
         try {
-            doc = factory.newDocumentBuilder().parse( new ByteArrayInputStream( bos.toByteArray() ) );
-        }
-        catch( Exception e ) {
-            throw new IllegalArgumentException( "Invalid XML response:\n" + bos.toString(), e );
+            doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(bos.toByteArray()));
+        } catch (Exception e) {
+            throw new IllegalArgumentException("Invalid XML response:\n" + bos.toString(), e);
         }
         return doc;
     }
 
-    void verifyXMLErrorNode( final Node errorNode, final ErrorType expErrorType, final ErrorTag expErrorTag,
-            final String expErrorMessage, final String expErrorAppTag,
-            final ErrorInfoVerifier errorInfoVerifier ) throws Exception {
+    void verifyXMLErrorNode(final Node errorNode, final ErrorType expErrorType, final ErrorTag expErrorTag,
+            final String expErrorMessage, final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier)
+            throws Exception {
 
-        String errorType = (String)ERROR_TYPE.evaluate( errorNode, XPathConstants.STRING );
-        assertEquals( "error-type", expErrorType.getErrorTypeTag(), errorType );
+        String errorType = (String) ERROR_TYPE.evaluate(errorNode, XPathConstants.STRING);
+        assertEquals("error-type", expErrorType.getErrorTypeTag(), errorType);
 
-        String errorTag = (String)ERROR_TAG.evaluate( errorNode, XPathConstants.STRING );
-        assertEquals( "error-tag", expErrorTag.getTagValue(), errorTag );
+        String errorTag = (String) ERROR_TAG.evaluate(errorNode, XPathConstants.STRING);
+        assertEquals("error-tag", expErrorTag.getTagValue(), errorTag);
 
-        verifyOptionalXMLLeaf( errorNode, ERROR_MESSAGE, expErrorMessage, "error-message" );
-        verifyOptionalXMLLeaf( errorNode, ERROR_APP_TAG, expErrorAppTag, "error-app-tag" );
+        verifyOptionalXMLLeaf(errorNode, ERROR_MESSAGE, expErrorMessage, "error-message");
+        verifyOptionalXMLLeaf(errorNode, ERROR_APP_TAG, expErrorAppTag, "error-app-tag");
 
-        Node errorInfoNode = (Node)ERROR_INFO.evaluate( errorNode, XPathConstants.NODE );
-        if( errorInfoVerifier != null ) {
-            assertNotNull( "Missing \"error-info\" node", errorInfoNode );
+        Node errorInfoNode = (Node) ERROR_INFO.evaluate(errorNode, XPathConstants.NODE);
+        if (errorInfoVerifier != null) {
+            assertNotNull("Missing \"error-info\" node", errorInfoNode);
 
-            errorInfoVerifier.verifyXML( errorInfoNode );
-        }
-        else {
-            assertNull( "Found unexpected \"error-info\" node", errorInfoNode );
+            errorInfoVerifier.verifyXML(errorInfoNode);
+        } else {
+            assertNull("Found unexpected \"error-info\" node", errorInfoNode);
         }
     }
 
-    void verifyOptionalXMLLeaf( final Node fromNode, final XPathExpression xpath, final String expValue,
-            final String tagName ) throws Exception {
-        if( expValue != null ) {
-            String actual = (String)xpath.evaluate( fromNode, XPathConstants.STRING );
-            assertEquals( tagName, expValue, actual );
-        }
-        else {
-            assertNull( "Found unexpected \"error\" leaf entry for: " + tagName,
-                    xpath.evaluate( fromNode, XPathConstants.NODE ) );
+    void verifyOptionalXMLLeaf(final Node fromNode, final XPathExpression xpath, final String expValue,
+            final String tagName) throws Exception {
+        if (expValue != null) {
+            String actual = (String) xpath.evaluate(fromNode, XPathConstants.STRING);
+            assertEquals(tagName, expValue, actual);
+        } else {
+            assertNull("Found unexpected \"error\" leaf entry for: " + tagName,
+                    xpath.evaluate(fromNode, XPathConstants.NODE));
         }
     }
 
-    NodeList getXMLErrorList( final Node fromNode, final int count ) throws Exception {
-        NodeList errorList = (NodeList)ERROR_LIST.evaluate( fromNode, XPathConstants.NODESET );
-        assertNotNull( "Root errors node is empty", errorList );
-        assertEquals( "Root errors node child count", count, errorList.getLength() );
+    NodeList getXMLErrorList(final Node fromNode, final int count) throws Exception {
+        NodeList errorList = (NodeList) ERROR_LIST.evaluate(fromNode, XPathConstants.NODESET);
+        assertNotNull("Root errors node is empty", errorList);
+        assertEquals("Root errors node child count", count, errorList.getLength());
         return errorList;
     }
 }
index a1b87325540e51a65b5918a9674148e9e2cbea26..f0d3fb6822874c332f27307971b909f19ea034e9 100644 (file)
@@ -1,27 +1,24 @@
 /*
-* Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*/
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.sal.restconf.impl.test;
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertThat;
+import static org.opendaylight.controller.sal.common.util.RpcErrors.getRpcError;
 
 import java.util.HashMap;
 import java.util.Map;
-
 import org.hamcrest.BaseMatcher;
 import org.hamcrest.Description;
 import org.hamcrest.Matcher;
 import org.junit.Test;
-
-import static org.opendaylight.controller.sal.common.util.RpcErrors.getRpcError;
-
 import org.opendaylight.controller.sal.restconf.impl.RestconfError;
 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
@@ -40,196 +37,166 @@ public class RestconfErrorTest {
 
         private final String text;
 
-        public Contains( String text ) {
+        public Contains(String text) {
             this.text = text;
         }
 
         @Override
-        public void describeTo( Description desc ) {
-            desc.appendText( "contains " ).appendValue( text );
+        public void describeTo(Description desc) {
+            desc.appendText("contains ").appendValue(text);
         }
 
         @Override
-        public boolean matches( Object arg ) {
-            return arg != null && arg.toString().contains( text );
+        public boolean matches(Object arg) {
+            return arg != null && arg.toString().contains(text);
         }
     }
 
     @Test
-    public void testErrorTagValueOf()
-    {
-        assertEquals( ErrorTag.IN_USE,
-                ErrorTag.valueOfCaseInsensitive( ErrorTag.IN_USE.getTagValue() ) );
+    public void testErrorTagValueOf() {
+        assertEquals(ErrorTag.IN_USE, ErrorTag.valueOfCaseInsensitive(ErrorTag.IN_USE.getTagValue()));
     }
 
     @Test
-    public void testErrorTagValueOfIsLowercase()
-    {
-        assertEquals( "in-use",
-                ErrorTag.IN_USE.getTagValue() );
+    public void testErrorTagValueOfIsLowercase() {
+        assertEquals("in-use", ErrorTag.IN_USE.getTagValue());
     }
 
     @Test
-    public void testErrorTypeGetErrorTypeTagIsLowerCase()
-    {
-       assertEquals( ErrorType.APPLICATION.name().toLowerCase(),
-               ErrorType.APPLICATION.getErrorTypeTag() );
+    public void testErrorTypeGetErrorTypeTagIsLowerCase() {
+        assertEquals(ErrorType.APPLICATION.name().toLowerCase(), ErrorType.APPLICATION.getErrorTypeTag());
     }
 
     @Test
-    public void testErrorTypeValueOf()
-    {
-       assertEquals( ErrorType.APPLICATION,
-                     ErrorType.valueOfCaseInsensitive( ErrorType.APPLICATION.getErrorTypeTag() ) );
+    public void testErrorTypeValueOf() {
+        assertEquals(ErrorType.APPLICATION, ErrorType.valueOfCaseInsensitive(ErrorType.APPLICATION.getErrorTypeTag()));
     }
 
     @Test
-    public void testErrorTagStatusCodes()
-    {
-        Map<String,Integer> lookUpMap = new HashMap<String,Integer>();
-
-        lookUpMap.put( "in-use", 409);
-        lookUpMap.put( "invalid-value", 400);
-        lookUpMap.put( "too-big", 413);
-        lookUpMap.put( "missing-attribute", 400);
-        lookUpMap.put( "bad-attribute", 400);
-        lookUpMap.put( "unknown-attribute", 400);
-        lookUpMap.put( "bad-element", 400);
-        lookUpMap.put( "unknown-element", 400);
-        lookUpMap.put( "unknown-namespace", 400);
-        lookUpMap.put( "access-denied", 403);
-        lookUpMap.put( "lock-denied", 409);
-        lookUpMap.put( "resource-denied", 409);
-        lookUpMap.put( "rollback-failed", 500);
-        lookUpMap.put( "data-exists", 409);
-        lookUpMap.put( "data-missing", 409);
-        lookUpMap.put( "operation-not-supported", 501);
-        lookUpMap.put( "operation-failed", 500);
-        lookUpMap.put( "partial-operation", 500);
-        lookUpMap.put( "malformed-message", 400);
-
-        for( ErrorTag tag : ErrorTag.values() )
-        {
-            Integer expectedStatusCode = lookUpMap.get( tag.getTagValue() );
-            assertNotNull( "Failed to find " + tag.getTagValue(), expectedStatusCode );
-            assertEquals( "Status Code does not match", expectedStatusCode,
-                          Integer.valueOf( tag.getStatusCode() ) );
+    public void testErrorTagStatusCodes() {
+        Map<String, Integer> lookUpMap = new HashMap<String, Integer>();
+
+        lookUpMap.put("in-use", 409);
+        lookUpMap.put("invalid-value", 400);
+        lookUpMap.put("too-big", 413);
+        lookUpMap.put("missing-attribute", 400);
+        lookUpMap.put("bad-attribute", 400);
+        lookUpMap.put("unknown-attribute", 400);
+        lookUpMap.put("bad-element", 400);
+        lookUpMap.put("unknown-element", 400);
+        lookUpMap.put("unknown-namespace", 400);
+        lookUpMap.put("access-denied", 403);
+        lookUpMap.put("lock-denied", 409);
+        lookUpMap.put("resource-denied", 409);
+        lookUpMap.put("rollback-failed", 500);
+        lookUpMap.put("data-exists", 409);
+        lookUpMap.put("data-missing", 409);
+        lookUpMap.put("operation-not-supported", 501);
+        lookUpMap.put("operation-failed", 500);
+        lookUpMap.put("partial-operation", 500);
+        lookUpMap.put("malformed-message", 400);
+
+        for (ErrorTag tag : ErrorTag.values()) {
+            Integer expectedStatusCode = lookUpMap.get(tag.getTagValue());
+            assertNotNull("Failed to find " + tag.getTagValue(), expectedStatusCode);
+            assertEquals("Status Code does not match", expectedStatusCode, Integer.valueOf(tag.getStatusCode()));
         }
     }
 
     @Test
-    public void testRestConfDocumentedException_NoCause()
-    {
+    public void testRestConfDocumentedException_NoCause() {
         String expectedMessage = "Message";
         ErrorType expectedErrorType = ErrorType.RPC;
         ErrorTag expectedErrorTag = ErrorTag.IN_USE;
-        RestconfError e =
-                new RestconfError( expectedErrorType,
-                                                 expectedErrorTag, expectedMessage );
+        RestconfError e = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage);
 
-        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag,
-                              null, (String)null, e);
+        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, null, (String) null, e);
     }
 
     @Test
-    public void testRestConfDocumentedException_WithAppTag()
-    {
+    public void testRestConfDocumentedException_WithAppTag() {
         String expectedMessage = "Message";
         ErrorType expectedErrorType = ErrorType.RPC;
         ErrorTag expectedErrorTag = ErrorTag.IN_USE;
         String expectedErrorAppTag = "application.tag";
 
-        RestconfError e =
-                new RestconfError( expectedErrorType,
-                                                 expectedErrorTag, expectedMessage, expectedErrorAppTag );
+        RestconfError e = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage, expectedErrorAppTag);
 
-        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag,
-                              expectedErrorAppTag, (String)null, e);
+        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag, (String) null,
+                e);
     }
 
     @Test
-    public void testRestConfDocumentedException_WithAppTagErrorInfo()
-    {
+    public void testRestConfDocumentedException_WithAppTagErrorInfo() {
         String expectedMessage = "Message";
         ErrorType expectedErrorType = ErrorType.RPC;
         ErrorTag expectedErrorTag = ErrorTag.IN_USE;
         String expectedErrorAppTag = "application.tag";
         String errorInfo = "<extra><sessionid>session.id</sessionid></extra>";
 
-        RestconfError e = new RestconfError( expectedErrorType,
-                                             expectedErrorTag,
-                                             expectedMessage,
-                                             expectedErrorAppTag,
-                                             errorInfo );
+        RestconfError e = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage, expectedErrorAppTag,
+                errorInfo);
 
-        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag,
-                expectedErrorAppTag, errorInfo, e);
+        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag, errorInfo, e);
     }
 
     @Test
     public void testRestConfErrorWithRpcError() {
 
         // All fields set
-        RpcError rpcError = getRpcError( "mock app-tag", ErrorTag.BAD_ATTRIBUTE.getTagValue(),
-                                         "mock error-info", RpcError.ErrorSeverity.ERROR,
-                                         "mock error-message", RpcError.ErrorType.PROTOCOL,
-                                         new Exception( "mock cause" ) );
+        RpcError rpcError = getRpcError("mock app-tag", ErrorTag.BAD_ATTRIBUTE.getTagValue(), "mock error-info",
+                RpcError.ErrorSeverity.ERROR, "mock error-message", RpcError.ErrorType.PROTOCOL, new Exception(
+                        "mock cause"));
 
-        validateRestConfError( "mock error-message", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE,
-                               "mock app-tag", "mock error-info",
-                               new RestconfError( rpcError ) );
+        validateRestConfError("mock error-message", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock app-tag",
+                "mock error-info", new RestconfError(rpcError));
 
         // All fields set except 'info' - expect error-info set to 'cause'
-        rpcError = getRpcError( "mock app-tag", ErrorTag.BAD_ATTRIBUTE.getTagValue(),
-                                null, RpcError.ErrorSeverity.ERROR,
-                                "mock error-message", RpcError.ErrorType.PROTOCOL,
-                                new Exception( "mock cause" ) );
+        rpcError = getRpcError("mock app-tag", ErrorTag.BAD_ATTRIBUTE.getTagValue(), null,
+                RpcError.ErrorSeverity.ERROR, "mock error-message", RpcError.ErrorType.PROTOCOL, new Exception(
+                        "mock cause"));
 
-        validateRestConfError( "mock error-message", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE,
-                               "mock app-tag", new Contains( "mock cause" ),
-                               new RestconfError( rpcError ) );
+        validateRestConfError("mock error-message", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock app-tag",
+                new Contains("mock cause"), new RestconfError(rpcError));
 
         // Some fields set - expect error-info set to ErrorSeverity
-        rpcError = getRpcError( null, ErrorTag.ACCESS_DENIED.getTagValue(),
-                                null, RpcError.ErrorSeverity.ERROR,
-                                null, RpcError.ErrorType.RPC, null );
+        rpcError = getRpcError(null, ErrorTag.ACCESS_DENIED.getTagValue(), null, RpcError.ErrorSeverity.ERROR, null,
+                RpcError.ErrorType.RPC, null);
 
-        validateRestConfError( null, ErrorType.RPC, ErrorTag.ACCESS_DENIED,
-                               null, "<severity>error</severity>",
-                               new RestconfError( rpcError ) );
+        validateRestConfError(null, ErrorType.RPC, ErrorTag.ACCESS_DENIED, null, "<severity>error</severity>",
+                new RestconfError(rpcError));
 
-        // 'tag' field not mapped to ErrorTag - expect error-tag set to OPERATION_FAILED
-        rpcError = getRpcError( null, "not mapped",
-                                null, RpcError.ErrorSeverity.WARNING,
-                                null, RpcError.ErrorType.TRANSPORT, null );
+        // 'tag' field not mapped to ErrorTag - expect error-tag set to
+        // OPERATION_FAILED
+        rpcError = getRpcError(null, "not mapped", null, RpcError.ErrorSeverity.WARNING, null,
+                RpcError.ErrorType.TRANSPORT, null);
 
-        validateRestConfError( null, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED,
-                               null, "<severity>warning</severity>",
-                               new RestconfError( rpcError ) );
+        validateRestConfError(null, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, null,
+                "<severity>warning</severity>", new RestconfError(rpcError));
 
         // No fields set - edge case
-        rpcError = getRpcError( null, null, null, null, null, null, null );
+        rpcError = getRpcError(null, null, null, null, null, null, null);
 
-        validateRestConfError( null, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
-                               null, (String)null, new RestconfError( rpcError ) );
+        validateRestConfError(null, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, null, (String) null,
+                new RestconfError(rpcError));
     }
 
-    private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType,
-            ErrorTag expectedErrorTag, String expectedErrorAppTag, String errorInfo, RestconfError e) {
+    private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType, ErrorTag expectedErrorTag,
+            String expectedErrorAppTag, String errorInfo, RestconfError e) {
 
-        validateRestConfError( expectedMessage, expectedErrorType, expectedErrorTag,
-                               expectedErrorAppTag, equalTo( errorInfo ), e );
+        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag,
+                equalTo(errorInfo), e);
     }
 
-    private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType,
-            ErrorTag expectedErrorTag, String expectedErrorAppTag,
-            Matcher<String> errorInfoMatcher, RestconfError e) {
+    private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType, ErrorTag expectedErrorTag,
+            String expectedErrorAppTag, Matcher<String> errorInfoMatcher, RestconfError e) {
 
-        assertEquals( "getErrorMessage", expectedMessage, e.getErrorMessage() );
-        assertEquals( "getErrorType", expectedErrorType, e.getErrorType() );
-        assertEquals( "getErrorTag", expectedErrorTag, e.getErrorTag() );
-        assertEquals( "getErrorAppTag", expectedErrorAppTag, e.getErrorAppTag() );
-        assertThat( "getErrorInfo", e.getErrorInfo(), errorInfoMatcher );
-        e.toString(); // really just checking for NPE etc. Don't care about contents.
+        assertEquals("getErrorMessage", expectedMessage, e.getErrorMessage());
+        assertEquals("getErrorType", expectedErrorType, e.getErrorType());
+        assertEquals("getErrorTag", expectedErrorTag, e.getErrorTag());
+        assertEquals("getErrorAppTag", expectedErrorAppTag, e.getErrorAppTag());
+        assertThat("getErrorInfo", e.getErrorInfo(), errorInfoMatcher);
+        e.toString(); // really just checking for NPE etc. Don't care about
+                      // contents.
     }
 }
index e2559f4b70ab27e2e6d990996e84bd8fbfb47045..3794815c894fe1c4cb727a97e423d265c8e6587c 100644 (file)
@@ -16,7 +16,6 @@ import static org.mockito.Mockito.when;
 
 import java.io.FileNotFoundException;
 import java.util.Set;
-
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -40,33 +39,27 @@ public class RestconfImplTest {
 
     @BeforeClass
     public static void init() throws FileNotFoundException {
-        Set<Module> allModules = TestUtils
-                .loadModulesFrom("/full-versions/yangs");
+        Set<Module> allModules = TestUtils.loadModulesFrom("/full-versions/yangs");
         assertNotNull(allModules);
         SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
-        controllerContext = spy( ControllerContext.getInstance() );
+        controllerContext = spy(ControllerContext.getInstance());
         controllerContext.setSchemas(schemaContext);
 
     }
 
     @Before
-    public void initMethod()
-    {
+    public void initMethod() {
         restconfImpl = RestconfImpl.getInstance();
-        restconfImpl.setControllerContext( controllerContext );
+        restconfImpl.setControllerContext(controllerContext);
     }
 
     @Test
     public void testExample() throws FileNotFoundException {
-        CompositeNode loadedCompositeNode = TestUtils.readInputToCnSn(
-                "/parts/ietf-interfaces_interfaces.xml",
+        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));
+        when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(loadedCompositeNode);
+        assertEquals(loadedCompositeNode, brokerFacade.readOperationalData(null));
     }
 
-
 }
index 449b79923edd40e0c21f922ba3ff6c271e45d3c5..ed1529540dc4fedde6fa803b909b5827e1241c79 100644 (file)
@@ -147,10 +147,9 @@ public final class TestUtils {
 
     /**
      *
-     * 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}
+     * 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();
@@ -161,9 +160,8 @@ public final class TestUtils {
     }
 
     /**
-     * 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.
+     * 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) {
@@ -279,8 +277,8 @@ public final class TestUtils {
 
         ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
 
-        messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode, null), null, null, null, null, null,
-                byteArrayOS);
+        messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode, null), null, null, null, null,
+                null, byteArrayOS);
 
         return byteArrayOS.toString();
     }
@@ -298,7 +296,7 @@ public final class TestUtils {
         return result.toString();
     }
 
-    private static Pattern patternForStringsSeparatedByWhiteChars(String ... substrings ) {
+    private static Pattern patternForStringsSeparatedByWhiteChars(String... substrings) {
         StringBuilder pattern = new StringBuilder();
         pattern.append(".*");
         for (String substring : substrings) {
@@ -309,7 +307,7 @@ public final class TestUtils {
         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
     }
 
-    public static boolean containsStringData(String jsonOutput,String ...substrings ) {
+    public static boolean containsStringData(String jsonOutput, String... substrings) {
         Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
         Matcher matcher = pattern.matcher(jsonOutput);
         return matcher.matches();
index efdb7b240c94a9fb9b47aec81d71ff99e61ebff5..18703040ee89ef6c7fff33bb57d9ced739aa6d0f 100644 (file)
@@ -15,10 +15,8 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
 import com.google.common.collect.Iterables;
-
 import java.io.FileNotFoundException;
 import java.util.Set;
-
 import org.junit.BeforeClass;
 import org.junit.Rule;
 import org.junit.Test;
index 5476d71320e9ae7a3a0fce6a9ec87f8dfe80088f..0799fdcff875b02ba6fb134c8f63f593660109d2 100644 (file)
@@ -15,9 +15,7 @@ import java.io.IOException;
 import java.net.URISyntaxException;
 import java.util.List;
 import java.util.Map;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
index e5a737e6d5d868be87fad55215d9be8b952bd0fd..483d90da0d220fc1054929d01008afabb5871175 100644 (file)
@@ -11,9 +11,7 @@ import static org.junit.Assert.assertEquals;
 
 import java.io.IOException;
 import java.net.URISyntaxException;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
index d5759bedb11342ae08eb5bb057ab13ee0a84813f..efcc3743c6938907e25d8dbd6af9e500e3549780 100644 (file)
@@ -11,7 +11,6 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 
index 3617ed9fb0d897adaf654ed96f0f98967811d7d2..ae07571ad93efc192cb0c395420048e8a437631e 100644 (file)
@@ -8,6 +8,7 @@
 package org.opendaylight.controller.sal.restconf.impl.test.structures;
 
 import static org.junit.Assert.assertFalse;
+
 import java.util.HashMap;
 import java.util.Map;
 
@@ -57,14 +58,12 @@ public class LstItem {
     }
 
     public void addLfLst(LfLst lfLst) {
-        assertFalse( "Found multiple leaf list elements for " + lfLst.getName(),
-                    lfLsts.containsKey( lfLst.getName() ) );
+        assertFalse("Found multiple leaf list elements for " + lfLst.getName(), lfLsts.containsKey(lfLst.getName()));
         lfLsts.put(lfLst.getName(), lfLst);
     }
 
     public void addLst(Lst lst) {
-        assertFalse( "Found multiple list elements for " + lst.getName(),
-                     lsts.containsKey( lst.getName() ) );
+        assertFalse("Found multiple list elements for " + lst.getName(), lsts.containsKey(lst.getName()));
         lsts.put(lst.getName(), lst);
     }
 
index 845d54ea1f568388ff6c7ba1400f0e76cac9ccf5..664aad6578c84fab98a3e569d00fa93dd3a1ee8d 100644 (file)
@@ -23,15 +23,13 @@ import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
 import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
 import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
 import io.netty.handler.codec.http.websocketx.WebSocketVersion;
-
 import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.net.URI;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class WebSocketClient  {
+public class WebSocketClient {
 
     private final URI uri;
     private Bootstrap bootstrap = new Bootstrap();;
@@ -40,51 +38,57 @@ public class WebSocketClient  {
     private Channel clientChannel;
     private final EventLoopGroup group = new NioEventLoopGroup();
 
-    public WebSocketClient(URI uri,IClientMessageCallback clientMessageCallback) {
+    public WebSocketClient(URI uri, IClientMessageCallback clientMessageCallback) {
         this.uri = uri;
-        clientHandler = new WebSocketClientHandler(
-                WebSocketClientHandshakerFactory.newHandshaker(
-                        uri, WebSocketVersion.V13, null, false,null),clientMessageCallback); // last null could be replaced with DefaultHttpHeaders
+        clientHandler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri,
+                WebSocketVersion.V13, null, false, null), clientMessageCallback); // last
+                                                                                  // null
+                                                                                  // could
+                                                                                  // be
+                                                                                  // replaced
+                                                                                  // with
+                                                                                  // DefaultHttpHeaders
         initialize();
     }
-    private void initialize(){
+
+    private void initialize() {
 
         String protocol = uri.getScheme();
         if (!"http".equals(protocol)) {
             throw new IllegalArgumentException("Unsupported protocol: " + protocol);
         }
 
-        bootstrap.group(group)
-                .channel(NioSocketChannel.class)
-                .handler(new ChannelInitializer<SocketChannel>() {
-                    @Override
-                    public void initChannel(SocketChannel ch) throws Exception {
-                        ChannelPipeline pipeline = ch.pipeline();
-                        pipeline.addLast("http-codec", new HttpClientCodec());
-                        pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
-                        pipeline.addLast("ws-handler", clientHandler);
-                    }
-                });
+        bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
+            @Override
+            public void initChannel(SocketChannel ch) throws Exception {
+                ChannelPipeline pipeline = ch.pipeline();
+                pipeline.addLast("http-codec", new HttpClientCodec());
+                pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
+                pipeline.addLast("ws-handler", clientHandler);
+            }
+        });
     }
-    public void connect() throws InterruptedException{
+
+    public void connect() throws InterruptedException {
         System.out.println("WebSocket Client connecting");
-        clientChannel  = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel();
+        clientChannel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel();
         clientHandler.handshakeFuture().sync();
     }
 
-    public void writeAndFlush(String message){
+    public void writeAndFlush(String message) {
         clientChannel.writeAndFlush(new TextWebSocketFrame(message));
     }
-    public void writeAndFlush(Object message){
+
+    public void writeAndFlush(Object message) {
         clientChannel.writeAndFlush(message);
     }
 
-    public void ping(){
-        clientChannel.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[]{1, 2, 3, 4, 5, 6})));
+    public void ping() {
+        clientChannel.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 })));
     }
 
     public void close(String reasonText) throws InterruptedException {
-        CloseWebSocketFrame closeWebSocketFrame = new CloseWebSocketFrame(1000,reasonText);
+        CloseWebSocketFrame closeWebSocketFrame = new CloseWebSocketFrame(1000, reasonText);
         clientChannel.writeAndFlush(closeWebSocketFrame);
 
         // WebSocketClientHandler will close the connection when the server
@@ -122,7 +126,7 @@ public class WebSocketClient  {
         @Override
         public void onMessageReceived(Object message) {
             if (message instanceof TextWebSocketFrame) {
-                logger.info("received message {}"+ ((TextWebSocketFrame)message).text());
+                logger.info("received message {}" + ((TextWebSocketFrame) message).text());
             }
         }
     }
index 0a16e254ccc6cd6c1a2f838cb04917477ce7869d..e07d8c48f0f2c9ba253a1282f4bf0e453ae19e3f 100644 (file)
@@ -18,7 +18,6 @@ import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
 import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
 import io.netty.handler.codec.http.websocketx.WebSocketFrame;
 import io.netty.util.CharsetUtil;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -29,8 +28,7 @@ public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object>
     private ChannelPromise handshakeFuture;
     private final IClientMessageCallback messageListener;
 
-
-    public WebSocketClientHandler(WebSocketClientHandshaker handshaker,IClientMessageCallback listener) {
+    public WebSocketClientHandler(WebSocketClientHandshaker handshaker, IClientMessageCallback listener) {
         this.handshaker = handshaker;
         this.messageListener = listener;
     }
@@ -92,4 +90,3 @@ public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object>
         ctx.close();
     }
 }
-
index d9ef2ef243986bb63960f8212f4ab2bbf81346f6..70f0f050dc9fdea84f186537eafbcad6779d7e53 100644 (file)
@@ -15,12 +15,10 @@ import static org.mockito.Mockito.mock;
 import java.io.FileNotFoundException;
 import java.io.UnsupportedEncodingException;
 import java.net.URI;
-
 import javax.ws.rs.client.Entity;
 import javax.ws.rs.core.Application;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.JerseyTest;
 import org.junit.BeforeClass;
@@ -55,10 +53,10 @@ public class RestStream extends JerseyTest {
     @Override
     protected Application configure() {
         /* enable/disable Jersey logs to console */
-//         enable(TestProperties.LOG_TRAFFIC);
-//         enable(TestProperties.DUMP_ENTITY);
-//         enable(TestProperties.RECORD_LOG_LEVEL);
-//         set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
+        // enable(TestProperties.LOG_TRAFFIC);
+        // enable(TestProperties.DUMP_ENTITY);
+        // enable(TestProperties.RECORD_LOG_LEVEL);
+        // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
         ResourceConfig resourceConfig = new ResourceConfig();
         resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
                 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
@@ -72,13 +70,15 @@ public class RestStream extends JerseyTest {
         Response responseWithStreamName = post(uri, MediaType.APPLICATION_XML, getRpcInput());
         String xmlResponse = responseWithStreamName.readEntity(String.class);
         assertNotNull(xmlResponse);
-        assertTrue(xmlResponse.contains("<stream-name>ietf-interfaces:interfaces/ietf-interfaces:interface/eth0</stream-name>"));
+        assertTrue(xmlResponse
+                .contains("<stream-name>ietf-interfaces:interfaces/ietf-interfaces:interface/eth0</stream-name>"));
 
         uri = "/streams/stream/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0";
         Response responseWithRedirectionUri = get(uri, MediaType.APPLICATION_XML);
         final URI websocketServerUri = responseWithRedirectionUri.getLocation();
         assertNotNull(websocketServerUri);
-        assertEquals(websocketServerUri.toString(), "http://localhost:8181/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0");
+        assertEquals(websocketServerUri.toString(),
+                "http://localhost:8181/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0");
     }
 
     private Response post(String uri, String mediaType, String data) {
index 62159ccad6c0edf76e4e8ac75282935e80c06450..5a5a621d930b68fc240140f76b086a0d57bc0a3c 100644 (file)
@@ -10,7 +10,6 @@ package org.opendaylight.controller.sal.restconf.impl.xml.to.cnsn.test;
 import static org.junit.Assert.assertNotNull;
 
 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;
@@ -21,13 +20,12 @@ public class XmlAugmentedElementToCnSnTest {
 
     @Test
     public void loadDataAugmentedSchemaMoreEqualNamesTest() {
-        loadAndNormalizeData("/common/augment/xml/dataa.xml", "/common/augment/yang", "main","cont");
-        loadAndNormalizeData("/common/augment/xml/datab.xml", "/common/augment/yang", "main","cont");
+        loadAndNormalizeData("/common/augment/xml/dataa.xml", "/common/augment/yang", "main", "cont");
+        loadAndNormalizeData("/common/augment/xml/datab.xml", "/common/augment/yang", "main", "cont");
     }
 
     private void loadAndNormalizeData(String xmlPath, String yangPath, String topLevelElementName, String moduleName) {
-        CompositeNode compNode = TestUtils.readInputToCnSn(xmlPath, false,
-                XmlToCompositeNodeProvider.INSTANCE);
+        CompositeNode compNode = TestUtils.readInputToCnSn(xmlPath, false, XmlToCompositeNodeProvider.INSTANCE);
         assertNotNull(compNode);
         Set<Module> modules = TestUtils.loadModulesFrom(yangPath);
 
@@ -35,5 +33,4 @@ public class XmlAugmentedElementToCnSnTest {
         TestUtils.normalizeCompositeNode(compNode, modules, topLevelElementName + ":" + moduleName);
     }
 
-
 }
index e5b0bf507d03212bf2efedaaa18cc2f28f734567..6c11bc1861995879818ce31b3d6d75696c2decf7 100644 (file)
@@ -13,7 +13,6 @@ import static org.junit.Assert.assertTrue;
 
 import java.util.List;
 import java.util.Set;
-
 import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
@@ -30,8 +29,7 @@ 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.
+     * top level element represents container. second level element is list with two elements.
      */
     @Test
     public void testXmlDataContainer() {
@@ -202,8 +200,7 @@ public class XmlLeafrefToCnSnTest {
 
     /**
      *
-     * Test case like <lf11 xmlns="namespace1"
-     * xmlns:x="namespace">identity</lf11>
+     * Test case like <lf11 xmlns="namespace1" xmlns:x="namespace">identity</lf11>
      */
 
     @Test
@@ -214,8 +211,7 @@ public class XmlLeafrefToCnSnTest {
 
     /**
      *
-     * Test case like <cont1 xmlns="namespace1"> <lf11
-     * xmlns:x="namespace">identity</lf11> </cont1>
+     * Test case like <cont1 xmlns="namespace1"> <lf11 xmlns:x="namespace">identity</lf11> </cont1>
      */
     @Test
     public void testIdentityrefDefaultNmspcInParrentElement() {
@@ -225,8 +221,7 @@ public class XmlLeafrefToCnSnTest {
 
     /**
      *
-     * Test case like <cont1 xmlns="namespace1" xmlns:x="namespace">
-     * <lf11>x:identity</lf11> </cont1>
+     * Test case like <cont1 xmlns="namespace1" xmlns:x="namespace"> <lf11>x:identity</lf11> </cont1>
      */
     @Ignore
     @Test
@@ -237,8 +232,7 @@ public class XmlLeafrefToCnSnTest {
 
     /**
      *
-     * Test case like (without namespace in xml) <cont1> <lf11>x:identity</lf11>
-     * </cont1>
+     * Test case like (without namespace in xml) <cont1> <lf11>x:identity</lf11> </cont1>
      */
     @Test
     public void testIdentityrefNoNmspcValueWithPrefix() {
@@ -248,8 +242,7 @@ public class XmlLeafrefToCnSnTest {
 
     /**
      *
-     * Test case like (without namespace in xml) <cont1> <lf11>identity</lf11>
-     * </cont1>
+     * Test case like (without namespace in xml) <cont1> <lf11>identity</lf11> </cont1>
      */
     @Test
     public void testIdentityrefNoNmspcValueWithoutPrefix() {
@@ -322,8 +315,8 @@ public class XmlLeafrefToCnSnTest {
         assertEquals((short) 100, cont1_lf11.getValue());
     }
 
-    private void testIdentityrefToCnSn(final String xmlPath, final String yangPath, final String moduleName, final String schemaName,
-            final int moduleCount, final String resultLocalName, final String resultNamespace) {
+    private void testIdentityrefToCnSn(final String xmlPath, final String yangPath, final String moduleName,
+            final String schemaName, final int moduleCount, final String resultLocalName, final String resultNamespace) {
         CompositeNode compositeNode = TestUtils.readInputToCnSn(xmlPath, false, XmlToCompositeNodeProvider.INSTANCE);
         assertNotNull(compositeNode);
 
index 5cda4a7f52014dc4a9ab3572d9073877ec12e74e..e2621d635bc3dab04629beffcb15c3d111b9eb21 100644 (file)
@@ -14,7 +14,6 @@ import static org.junit.Assert.assertTrue;
 
 import java.io.ByteArrayInputStream;
 import java.io.InputStream;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
@@ -57,26 +56,26 @@ public class XmlToCnSnTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     @Test
-    public void testXmlBlankInput() throws Exception{
-        InputStream inputStream = new ByteArrayInputStream( "".getBytes() );
-        CompositeNode compositeNode =
-                XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream);
+    public void testXmlBlankInput() throws Exception {
+        InputStream inputStream = new ByteArrayInputStream("".getBytes());
+        CompositeNode compositeNode = XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null,
+                inputStream);
 
-        assertNull( compositeNode );
+        assertNull(compositeNode);
     }
 
     @Test
-    public void testXmlBlankInputUnmarkableStream() throws Exception{
-        InputStream inputStream = new ByteArrayInputStream( "".getBytes() ){
+    public void testXmlBlankInputUnmarkableStream() throws Exception {
+        InputStream inputStream = new ByteArrayInputStream("".getBytes()) {
             @Override
             public boolean markSupported() {
                 return false;
             }
         };
-        CompositeNode compositeNode =
-                XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream);
+        CompositeNode compositeNode = XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null,
+                inputStream);
 
-        assertNull( compositeNode );
+        assertNull(compositeNode);
     }
 
 }
index 2e533e720e0760f6abca5b84663c52ce170a4899..baf7d1e9ae7a9f61ccdf8b33cdefe728e4c16cee 100644 (file)
@@ -4,7 +4,7 @@ module test-module {
 
   revision 2014-01-09 {
   }
-  
+
   container interfaces {
     container class {
         leaf name {
@@ -18,7 +18,7 @@ module test-module {
         }
     }
   }
-  
+
   container cont {
     container cont1 {
         leaf lf11 {
@@ -34,9 +34,18 @@ module test-module {
             type string;
         }
     }
-  }   
-  
+  }
   
+  list lst-with-composite-key {
+    key "key1 key2";
+    leaf key1 {
+        type string;
+    }
+    leaf key2 {
+        type uint8;
+    }
+  }
+
   rpc rpc-test {
     input {
       container cont {
@@ -48,16 +57,11 @@ module test-module {
                 type string;
             }
         }
-      }    
+      }
     }
     output {
         container cont-output {
         }
-    } 
-  
+    }
   }
-  
-  
-
 }
\ No newline at end of file
index c770bde9206c03bba89027bc77b5fcb835e8dd03..1360a54d6fbaf2609067f1617337e8af76ec7852 100644 (file)
@@ -60,6 +60,7 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
     }
 
     private State state = State.IDLE;
+    private final Promise<S> promise;
     private final Timer timer;
     private final long connectionTimeoutMillis;
 
@@ -68,6 +69,7 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
             L sessionListener, long connectionTimeoutMillis) {
         super(promise, channel);
         this.sessionPreferences = sessionPreferences;
+        this.promise = promise;
         this.timer = timer;
         this.sessionListener = sessionListener;
         this.connectionTimeoutMillis = connectionTimeoutMillis;
@@ -106,28 +108,40 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
 
         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
 
+        // FIXME, make sessionPreferences return HelloMessage, move NetconfHelloMessage to API
+        sendMessage((NetconfHelloMessage)helloMessage);
+
+        replaceHelloMessageOutboundHandler();
+        changeState(State.OPEN_WAIT);
+
         timeout = this.timer.newTimeout(new TimerTask() {
             @Override
             public void run(final Timeout timeout) {
                 synchronized (this) {
                     if (state != State.ESTABLISHED) {
+
                         logger.debug("Connection timeout after {}, session is in state {}", timeout, state);
-                        final IllegalStateException cause = new IllegalStateException(
-                                "Session was not established after " + timeout);
-                        negotiationFailed(cause);
+
+                        // Do not fail negotiation if promise is done or canceled
+                        // It would result in setting result of the promise second time and that throws exception
+                        if (isPromiseFinished() == false) {
+                            // FIXME BUG-1365 calling "negotiation failed" closes the channel, but the channel does not get closed if data is still being transferred
+                            // Loopback connection initiation might
+                            negotiationFailed(new IllegalStateException("Session was not established after " + timeout));
+                        }
+
                         changeState(State.FAILED);
                     } else if(channel.isOpen()) {
                         channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
                     }
                 }
             }
-        }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
 
-        // FIXME, make sessionPreferences return HelloMessage, move NetconfHelloMessage to API
-        sendMessage((NetconfHelloMessage)helloMessage);
+            private boolean isPromiseFinished() {
+                return promise.isDone() || promise.isCancelled();
+            }
 
-        replaceHelloMessageOutboundHandler();
-        changeState(State.OPEN_WAIT);
+        }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
     }
 
     private void cancelTimeout() {