Merge "Bug 460 - Fix warning throughout netconf subsystem"
authorEd Warnicke <eaw@cisco.com>
Mon, 28 Apr 2014 12:18:40 +0000 (12:18 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Mon, 28 Apr 2014 12:18:40 +0000 (12:18 +0000)
97 files changed:
opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/PropertiesProvider.java
opendaylight/config/config-persister-api/src/test/java/org/opendaylight/controller/config/persist/test/PropertiesProviderTest.java
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/DepTestImplModuleFactory.java
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/IdentityTestModuleFactory.java
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModuleFactory.java
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/TestImplModuleFactory.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/AttributeIfcSwitchStatement.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/fromxml/AttributeConfigElement.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/fromxml/ObjectNameAttributeReadingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/fromxml/ObjectXmlReader.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/fromxml/SimpleIdentityRefAttributeReadingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/mapping/ArrayAttributeMappingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/mapping/CompositeAttributeMappingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/mapping/ObjectMapper.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/mapping/ObjectNameAttributeMappingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/mapping/SimpleAttributeMappingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/mapping/UnionCompositeAttributeMappingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/resolving/ArrayAttributeResolvingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/resolving/AttributeResolvingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/resolving/CompositeAttributeResolvingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/resolving/ObjectResolver.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/resolving/SimpleAttributeResolvingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/resolving/UnionCompositeAttributeResolvingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/AbstractAttributeWritingStrategy.java [new file with mode: 0644]
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/CompositeAttributeWritingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/ObjectXmlWriter.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/RuntimeBeanEntryWritingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleAttributeWritingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleBinaryAttributeWritingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleIdentityRefAttributeWritingStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/config/Config.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/config/InstanceConfig.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/config/ModuleConfig.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/config/ServiceRegistryWrapper.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/config/Services.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/rpc/ModuleRpcs.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/runtime/InstanceRuntime.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/runtime/ModuleRuntime.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/runtime/Runtime.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/AbstractConfigNetconfOperation.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/editconfig/DeleteEditConfigStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/editconfig/EditConfig.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/editconfig/EditConfigXmlParser.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/editconfig/EditStrategyType.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/editconfig/MergeEditConfigStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/editconfig/ReplaceEditConfigStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/get/Get.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/getconfig/GetConfig.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/runtimerpc/RuntimeRpc.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/runtimerpc/RuntimeRpcElementResolved.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/Activator.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationProvider.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceFactoryImpl.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImpl.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/transactions/TransactionProvider.java
opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandler.java
opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/PersisterAggregator.java
opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/PropertiesProviderAdapterImpl.java
opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterTest.java
opendaylight/netconf/ietf-netconf-monitoring/src/main/java/org/opendaylight/yang/gen/v1/urn/ietf/params/xml/ns/yang/ietf/netconf/monitoring/rev101004/netconf/state/schemas/LocationBuilder.java
opendaylight/netconf/netconf-client/src/main/java/org/opendaylight/controller/netconf/client/NetconfClient.java [new file with mode: 0644]
opendaylight/netconf/netconf-client/src/main/java/org/opendaylight/controller/netconf/client/NetconfClientDispatcher.java
opendaylight/netconf/netconf-client/src/main/java/org/opendaylight/controller/netconf/client/SimpleNetconfClientSessionListener.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/CapabilityProviderImpl.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/DefaultCommitNotificationProducer.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/NetconfServerSessionListener.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultCommit.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/NetconfImplActivator.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/NetconfMonitoringServiceImpl.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/osgi/NetconfOperationRouterImpl.java
opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfMonitoringITTest.java
opendaylight/netconf/netconf-mapping-api/src/main/java/org/opendaylight/controller/netconf/mapping/api/HandlingPriority.java
opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/Get.java
opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/MonitoringConstants.java
opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringActivator.java
opendaylight/netconf/netconf-monitoring/src/main/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringOperationService.java
opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/NetconfSSHServer.java
opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/authentication/AuthProvider.java
opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/authentication/AuthProviderInterface.java
opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/osgi/NetconfSSHActivator.java
opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/threads/SocketThread.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ChunkedFramingMechanismEncoder.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/EOMFramingMechanismEncoder.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/FramingMechanismHandlerFactory.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/NetconfChunkAggregator.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/NetconfEOMAggregator.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/NetconfXMLToHelloMessageDecoder.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/NetconfXMLToMessageDecoder.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/authentication/LoginPassword.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshClient.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshClientAdapter.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/ChannelInputStream.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageConstants.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/SendErrorExceptionUtil.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/osgi/NetconfConfigUtil.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlElement.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlUtil.java

index 2df07b1..3d4757b 100644 (file)
@@ -26,4 +26,14 @@ public class PropertiesProviderTest implements PropertiesProvider {
     public String getFullKeyForReporting(String key) {
         return null;
     }
+
+    @Override
+    public String getPrefix() {
+        return null;
+    }
+
+    @Override
+    public String getPropertyWithoutPrefix(String fullKey) {
+        return null;
+    }
 }
index 330f804..ae6ae67 100644 (file)
@@ -10,7 +10,7 @@
 *
 * Generated from: yang module name: config-test-impl yang module local name: impl-dep
 * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
-* Generated at: Fri Apr 25 09:12:08 CEST 2014
+* Generated at: Fri Apr 25 11:50:32 CEST 2014
 *
 * Do not modify this file unless it is present under src/main directory
 */
index b57d1dc..0701226 100644 (file)
@@ -10,7 +10,7 @@
 *
 * Generated from: yang module name: config-test-impl yang module local name: impl-identity-test
 * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
-* Generated at: Fri Apr 25 09:12:08 CEST 2014
+* Generated at: Fri Apr 25 11:50:32 CEST 2014
 *
 * Do not modify this file unless it is present under src/main directory
 */
index 74a0549..3baee6c 100644 (file)
@@ -10,7 +10,7 @@
 *
 * Generated from: yang module name: config-test-impl yang module local name: impl-netconf
 * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
-* Generated at: Fri Apr 25 09:12:08 CEST 2014
+* Generated at: Fri Apr 25 11:50:32 CEST 2014
 *
 * Do not modify this file unless it is present under src/main directory
 */
index 9680bff..6f9118b 100644 (file)
@@ -10,7 +10,7 @@
 *
 * Generated from: yang module name: config-test-impl yang module local name: impl
 * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
-* Generated at: Fri Apr 25 09:12:08 CEST 2014
+* Generated at: Fri Apr 25 11:50:32 CEST 2014
 *
 * Do not modify this file unless it is present under src/main directory
 */
index 54d24a4..c08be06 100644 (file)
@@ -23,7 +23,7 @@ import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
 
 public abstract class AttributeIfcSwitchStatement<T> {
 
-    protected AttributeIfc lastAttribute;
+    private AttributeIfc lastAttribute;
 
     public T switchAttribute(AttributeIfc attributeIfc) {
 
@@ -39,8 +39,9 @@ public abstract class AttributeIfcSwitchStatement<T> {
                     return caseJavaUnionAttribute(openType);
                 } else if(((JavaAttribute)attributeIfc).isIdentityRef()) {
                     return caseJavaIdentityRefAttribute(openType);
-                } else
+                } else {
                     return caseJavaAttribute(openType);
+                }
             } catch (UnknownOpenTypeException e) {
                 throw getIllegalArgumentException(attributeIfc);
             }
@@ -58,6 +59,10 @@ public abstract class AttributeIfcSwitchStatement<T> {
         throw getIllegalArgumentException(attributeIfc);
     }
 
+    public AttributeIfc getLastAttribute() {
+        return lastAttribute;
+    }
+
     protected T caseJavaIdentityRefAttribute(OpenType<?> openType) {
         return caseJavaAttribute(openType);
     }
index dbc1b48..dcc2fa1 100644 (file)
@@ -9,6 +9,7 @@
 package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
 
 import com.google.common.base.Optional;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.AttributeResolvingStrategy;
 
 import javax.management.openmbean.OpenType;
@@ -39,7 +40,7 @@ public class AttributeConfigElement {
     }
 
     public void resolveValue(AttributeResolvingStrategy<?, ? extends OpenType<?>> attributeResolvingStrategy,
-            String attrName) {
+            String attrName) throws NetconfDocumentedException {
         resolvedValue = attributeResolvingStrategy.parseAttribute(attrName, value);
         Optional<?> resolvedDefault = attributeResolvingStrategy.parseAttribute(attrName, dafaultValue);
         resolvedDefaultValue = resolvedDefault.isPresent() ? resolvedDefault.get() : null;
index 5f44c16..bf9eee7 100644 (file)
@@ -55,7 +55,7 @@ public class ObjectNameAttributeReadingStrategy extends AbstractAttributeReading
     public static String checkPrefixAndExtractServiceName(XmlElement typeElement, Map.Entry<String, String> prefixNamespace) throws NetconfDocumentedException {
         String serviceName = typeElement.getTextContent();
 
-        Preconditions.checkState(prefixNamespace.equals("") == false, "Service %s value not prefixed with namespace",
+        Preconditions.checkState(!prefixNamespace.equals(""), "Service %s value not prefixed with namespace",
                 XmlNetconfConstants.TYPE_KEY);
         String prefix = prefixNamespace.getKey() + PREFIX_SEPARATOR;
         Preconditions.checkState(serviceName.startsWith(prefix),
index 61db74f..61ea76b 100644 (file)
@@ -50,31 +50,31 @@ public class ObjectXmlReader extends AttributeIfcSwitchStatement<AttributeReadin
 
     @Override
     protected AttributeReadingStrategy caseJavaBinaryAttribute(OpenType<?> openType) {
-        return new SimpleBinaryAttributeReadingStrategy(lastAttribute.getNullableDefault());
+        return new SimpleBinaryAttributeReadingStrategy(getLastAttribute().getNullableDefault());
     }
 
     @Override
     protected AttributeReadingStrategy caseJavaUnionAttribute(OpenType<?> openType) {
         String mappingKey = JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION;
-        return new SimpleUnionAttributeReadingStrategy(lastAttribute.getNullableDefault(), mappingKey);
+        return new SimpleUnionAttributeReadingStrategy(getLastAttribute().getNullableDefault(), mappingKey);
     }
 
     @Override
     public AttributeReadingStrategy caseJavaSimpleAttribute(SimpleType<?> openType) {
-        return new SimpleAttributeReadingStrategy(lastAttribute.getNullableDefault());
+        return new SimpleAttributeReadingStrategy(getLastAttribute().getNullableDefault());
     }
 
     @Override
     public AttributeReadingStrategy caseJavaArrayAttribute(ArrayType<?> openType) {
-        SimpleAttributeReadingStrategy innerStrategy = new SimpleAttributeReadingStrategy(lastAttribute.getNullableDefault());
-        return new ArrayAttributeReadingStrategy(lastAttribute.getNullableDefault(), innerStrategy);
+        SimpleAttributeReadingStrategy innerStrategy = new SimpleAttributeReadingStrategy(getLastAttribute().getNullableDefault());
+        return new ArrayAttributeReadingStrategy(getLastAttribute().getNullableDefault(), innerStrategy);
     }
 
     @Override
     public AttributeReadingStrategy caseJavaCompositeAttribute(CompositeType openType) {
         Preconditions.checkState(openType.keySet().size() == 1, "Unexpected number of elements for open type %s, should be 1", openType);
         String mappingKey = openType.keySet().iterator().next();
-        return new SimpleCompositeAttributeReadingStrategy(lastAttribute.getNullableDefault(), mappingKey);
+        return new SimpleCompositeAttributeReadingStrategy(getLastAttribute().getNullableDefault(), mappingKey);
     }
 
     @Override
@@ -83,18 +83,18 @@ public class ObjectXmlReader extends AttributeIfcSwitchStatement<AttributeReadin
         Set<String> keys = ((CompositeType) openType).keySet();
         Preconditions.checkState(keys.size() == 1, "Unexpected number of elements for open type %s, should be 1", openType);
         String mappingKey = keys.iterator().next();
-        return new SimpleIdentityRefAttributeReadingStrategy(lastAttribute.getNullableDefault(), mappingKey, identityMap);
+        return new SimpleIdentityRefAttributeReadingStrategy(getLastAttribute().getNullableDefault(), mappingKey, identityMap);
     }
 
     @Override
     protected AttributeReadingStrategy caseDependencyAttribute(SimpleType<?> openType) {
-        return new ObjectNameAttributeReadingStrategy(lastAttribute.getNullableDefault());
+        return new ObjectNameAttributeReadingStrategy(getLastAttribute().getNullableDefault());
     }
 
     @Override
     protected AttributeReadingStrategy caseTOAttribute(CompositeType openType) {
-        Preconditions.checkState(lastAttribute instanceof TOAttribute);
-        Map<String, AttributeIfc> inner = ((TOAttribute)lastAttribute).getYangPropertiesToTypesMap();
+        Preconditions.checkState(getLastAttribute() instanceof TOAttribute);
+        Map<String, AttributeIfc> inner = ((TOAttribute)getLastAttribute()).getYangPropertiesToTypesMap();
 
         Map<String, AttributeReadingStrategy> innerStrategies = Maps.newHashMap();
 
@@ -104,21 +104,21 @@ public class ObjectXmlReader extends AttributeIfcSwitchStatement<AttributeReadin
             innerStrategies.put(innerAttrEntry.getKey(), innerStrat);
         }
 
-        return new CompositeAttributeReadingStrategy(lastAttribute.getNullableDefault(), innerStrategies);
+        return new CompositeAttributeReadingStrategy(getLastAttribute().getNullableDefault(), innerStrategies);
     }
 
     @Override
     protected AttributeReadingStrategy caseListAttribute(ArrayType<?> openType) {
-        Preconditions.checkState(lastAttribute instanceof ListAttribute);
-        AttributeReadingStrategy innerStrategy = prepareReadingStrategy(key, ((ListAttribute) lastAttribute).getInnerAttribute());
-        return new ArrayAttributeReadingStrategy(lastAttribute.getNullableDefault(), innerStrategy);
+        Preconditions.checkState(getLastAttribute() instanceof ListAttribute);
+        AttributeReadingStrategy innerStrategy = prepareReadingStrategy(key, ((ListAttribute) getLastAttribute()).getInnerAttribute());
+        return new ArrayAttributeReadingStrategy(getLastAttribute().getNullableDefault(), innerStrategy);
     }
 
     @Override
     protected AttributeReadingStrategy caseListDependeciesAttribute(ArrayType<?> openType) {
-        Preconditions.checkState(lastAttribute instanceof ListDependenciesAttribute);
+        Preconditions.checkState(getLastAttribute() instanceof ListDependenciesAttribute);
         AttributeReadingStrategy innerStrategy = caseDependencyAttribute(SimpleType.OBJECTNAME);
-        return new ArrayAttributeReadingStrategy(lastAttribute.getNullableDefault(), innerStrategy);
+        return new ArrayAttributeReadingStrategy(getLastAttribute().getNullableDefault(), innerStrategy);
     }
 
 }
index 58f91a7..8e7ba70 100644 (file)
@@ -54,9 +54,9 @@ public class SimpleIdentityRefAttributeReadingStrategy extends SimpleAttributeRe
                     revision = date;
                 }
             }
-        } else
+        } else {
             revision = revisions.keySet().iterator().next();
-
+        }
 
         return QName.create(URI.create(namespace), revision, localName).toString();
     }
index 30436bb..54ffe08 100644 (file)
@@ -30,8 +30,9 @@ public class ArrayAttributeMappingStrategy extends AbstractAttributeMappingStrat
 
     @Override
     public Optional<List<Object>> mapAttribute(Object value) {
-        if (value == null)
+        if (value == null){
             return Optional.absent();
+        }
 
         Preconditions.checkArgument(value.getClass().isArray(), "Value has to be instanceof Array ");
 
@@ -39,19 +40,11 @@ public class ArrayAttributeMappingStrategy extends AbstractAttributeMappingStrat
 
         for (int i = 0; i < Array.getLength(value); i++) {
             Object innerValue = Array.get(value, i);
-            // String expectedClassName =
-            // getOpenType().getElementOpenType().getClassName();
-            // String realClassName = value.getClass().getName();
-
-            // Preconditions.checkState(realClassName.contains(expectedClassName),
-            // "Element in collection/array should be of type " +
-            // expectedClassName + " but was "
-            // + realClassName + " for attribute: " + getOpenType());
-
             Optional<?> mapAttribute = innerElementStrategy.mapAttribute(innerValue);
 
-            if (mapAttribute.isPresent())
+            if (mapAttribute.isPresent()){
                 retVal.add(mapAttribute.get());
+            }
         }
 
         return Optional.of(retVal);
index 368e1f1..594953e 100644 (file)
@@ -35,8 +35,9 @@ public class CompositeAttributeMappingStrategy extends
 
     @Override
     public Optional<Map<String, Object>> mapAttribute(Object value) {
-        if (value == null)
+        if (value == null){
             return Optional.absent();
+        }
 
         Util.checkType(value, CompositeDataSupport.class);
 
@@ -54,8 +55,9 @@ public class CompositeAttributeMappingStrategy extends
 
         for (String jmxName : jmxToJavaNameMapping.keySet()) {
             Optional<?> mapped = mapInnerAttribute(compositeData, jmxName, expectedType.getDescription(jmxName));
-            if(mapped.isPresent())
+            if(mapped.isPresent()){
                 retVal.put(jmxToJavaNameMapping.get(jmxName), mapped.get());
+            }
         }
 
         return Optional.of(retVal);
@@ -66,8 +68,7 @@ public class CompositeAttributeMappingStrategy extends
 
         AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = innerStrategies
                 .get(jmxName);
-        Optional<?> mapAttribute = attributeMappingStrategy.mapAttribute(innerValue);
-        return mapAttribute;
+        return attributeMappingStrategy.mapAttribute(innerValue);
     }
 
 }
index 506d7d6..01844f2 100644 (file)
@@ -112,7 +112,7 @@ public class ObjectMapper extends AttributeIfcSwitchStatement<AttributeMappingSt
     @Override
     protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseDependencyAttribute(
             SimpleType<?> openType) {
-        return new ObjectNameAttributeMappingStrategy(openType, dependencyTracker,
+        return new ObjectNameAttributeMappingStrategy(openType,
                 serviceNameOfDepAttr, namespaceOfDepAttr);
     }
 
@@ -120,10 +120,10 @@ public class ObjectMapper extends AttributeIfcSwitchStatement<AttributeMappingSt
     protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseTOAttribute(CompositeType openType) {
         Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies = Maps.newHashMap();
 
-        Preconditions.checkState(lastAttribute instanceof TOAttribute);
-        TOAttribute lastTO = (TOAttribute) lastAttribute;
+        Preconditions.checkState(getLastAttribute() instanceof TOAttribute);
+        TOAttribute lastTO = (TOAttribute) getLastAttribute();
 
-        for (Entry<String, AttributeIfc> innerAttrEntry : ((TOAttribute)lastAttribute).getJmxPropertiesToTypesMap().entrySet()) {
+        for (Entry<String, AttributeIfc> innerAttrEntry : ((TOAttribute)getLastAttribute()).getJmxPropertiesToTypesMap().entrySet()) {
             innerStrategies.put(innerAttrEntry.getKey(), prepareStrategy(innerAttrEntry.getValue()));
         }
 
@@ -133,14 +133,14 @@ public class ObjectMapper extends AttributeIfcSwitchStatement<AttributeMappingSt
 
     @Override
     protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseListAttribute(ArrayType<?> openType) {
-        Preconditions.checkState(lastAttribute instanceof ListAttribute);
+        Preconditions.checkState(getLastAttribute() instanceof ListAttribute);
         return new ArrayAttributeMappingStrategy(openType,
-                prepareStrategy(((ListAttribute) lastAttribute).getInnerAttribute()));
+                prepareStrategy(((ListAttribute) getLastAttribute()).getInnerAttribute()));
     }
 
     @Override
     protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseListDependeciesAttribute(ArrayType<?> openType) {
-        Preconditions.checkState(lastAttribute instanceof ListDependenciesAttribute);
+        Preconditions.checkState(getLastAttribute() instanceof ListDependenciesAttribute);
         return new ArrayAttributeMappingStrategy(openType, caseDependencyAttribute(SimpleType.OBJECTNAME));
     }
 
index 83e8086..b827a5b 100644 (file)
@@ -10,31 +10,28 @@ package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attri
 
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
-
 import javax.management.ObjectName;
 import javax.management.openmbean.SimpleType;
+import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
+import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
 
 public class ObjectNameAttributeMappingStrategy extends
         AbstractAttributeMappingStrategy<ObjectNameAttributeMappingStrategy.MappedDependency, SimpleType<?>> {
 
-    private final ServiceRegistryWrapper tracker;
     private final String serviceName;
     private final String namespace;
 
-    public ObjectNameAttributeMappingStrategy(SimpleType<?> openType, ServiceRegistryWrapper dependencyTracker, String serviceName, String namespace) {
+    public ObjectNameAttributeMappingStrategy(SimpleType<?> openType,  String serviceName, String namespace) {
         super(openType);
-        this.tracker = dependencyTracker;
         this.serviceName = serviceName;
         this.namespace = namespace;
     }
 
     @Override
     public Optional<MappedDependency> mapAttribute(Object value) {
-        if (value == null)
+        if (value == null){
             return Optional.absent();
+        }
 
         String expectedClass = getOpenType().getClassName();
         String realClass = value.getClass().getName();
index d92b7c4..7dbf4f4 100644 (file)
@@ -25,8 +25,9 @@ public class SimpleAttributeMappingStrategy extends AbstractAttributeMappingStra
 
     @Override
     public Optional<String> mapAttribute(Object value) {
-        if (value == null)
+        if (value == null){
             return Optional.absent();
+        }
 
         String expectedClass = getOpenType().getClassName();
         String realClass = value.getClass().getName();
index 81a1e53..1754fc7 100644 (file)
@@ -26,9 +26,9 @@ public class UnionCompositeAttributeMappingStrategy extends
 
     @Override
     protected Optional<?> mapInnerAttribute(CompositeDataSupport compositeData, String jmxName, String description) {
-        if(description.equals(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION) == false)
+        if(!description.equals(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION)){
             return Optional.absent();
-
+        }
         return super.mapInnerAttribute(compositeData, jmxName, description);
     }
 }
index adee8be..f0d7960 100644 (file)
@@ -9,6 +9,7 @@
 package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving;
 
 import com.google.common.base.Optional;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -33,7 +34,7 @@ final class ArrayAttributeResolvingStrategy extends AbstractAttributeResolvingSt
     }
 
     @Override
-    public Optional<Object> parseAttribute(String attrName, Object value) {
+    public Optional<Object> parseAttribute(String attrName, Object value) throws NetconfDocumentedException {
         if (value == null) {
             return Optional.absent();
         }
@@ -45,31 +46,31 @@ final class ArrayAttributeResolvingStrategy extends AbstractAttributeResolvingSt
 
         if (innerTypeResolvingStrategy.getOpenType() instanceof CompositeType) {
             innerTypeClass = CompositeDataSupport.class;
-        } else
+        } else {
             try {
                 innerTypeClass = Class.forName(getOpenType().getElementOpenType().getClassName());
             } catch (ClassNotFoundException e) {
-                throw new RuntimeException("Unable to locate class for "
+                throw new IllegalStateException("Unable to locate class for "
                         + getOpenType().getElementOpenType().getClassName(), e);
             }
+        }
 
         Object parsedArray = null;
 
         if (getOpenType().isPrimitiveArray()) {
             Class<?> primitiveType = getPrimitiveType(innerTypeClass);
             parsedArray = Array.newInstance(primitiveType, valueList.size());
-        } else
+        } else {
             parsedArray = Array.newInstance(innerTypeClass, valueList.size());
+        }
 
         int i = 0;
         for (Object innerValue : valueList) {
             Optional<?> parsedElement = innerTypeResolvingStrategy.parseAttribute(attrName + "_" + i, innerValue);
-
-            if (!parsedElement.isPresent())
+            if (!parsedElement.isPresent()){
                 continue;
-
+            }
             Array.set(parsedArray, i, parsedElement.get());
-            // parsedArray[i] = parsedElement.get();
             i++;
         }
 
@@ -94,7 +95,7 @@ final class ArrayAttributeResolvingStrategy extends AbstractAttributeResolvingSt
         try {
             return (Class<?>) innerTypeClass.getField("TYPE").get(null);
         } catch (Exception e) {
-            throw new RuntimeException("Unable to determine primitive type to " + innerTypeClass);
+            throw new IllegalStateException("Unable to determine primitive type to " + innerTypeClass);
         }
     }
 
index 0bb274a..599d813 100644 (file)
@@ -11,6 +11,7 @@ package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attri
 import com.google.common.base.Optional;
 
 import javax.management.openmbean.OpenType;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 
 /**
  * Create real object from String or Map that corresponds to given opentype.
@@ -18,5 +19,5 @@ import javax.management.openmbean.OpenType;
 public interface AttributeResolvingStrategy<T, O extends OpenType<?>> {
     O getOpenType();
 
-    Optional<T> parseAttribute(String attrName, Object value);
+    Optional<T> parseAttribute(String attrName, Object value) throws NetconfDocumentedException;
 }
index e8e97f9..83ebf65 100644 (file)
@@ -11,6 +11,7 @@ package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attri
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Maps;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -41,7 +42,7 @@ class CompositeAttributeResolvingStrategy extends
     }
 
     @Override
-    public Optional<CompositeDataSupport> parseAttribute(String attrName, Object value) {
+    public Optional<CompositeDataSupport> parseAttribute(String attrName, Object value) throws NetconfDocumentedException {
 
         if (value == null) {
             return Optional.absent();
@@ -75,7 +76,7 @@ class CompositeAttributeResolvingStrategy extends
         try {
             parsedValue = new CompositeDataSupport(getOpenType(), items);
         } catch (OpenDataException e) {
-            throw new RuntimeException("An error occured during restoration of composite type " + this
+            throw new IllegalStateException("An error occured during restoration of composite type " + this
                     + " for attribute " + attrName + " from value " + value, e);
         }
 
index 82c8c1e..4a4281a 100644 (file)
@@ -106,8 +106,8 @@ public class ObjectResolver extends AttributeIfcSwitchStatement<AttributeResolvi
 
     @Override
     protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseTOAttribute(CompositeType openType) {
-        Preconditions.checkState(lastAttribute instanceof TOAttribute);
-        TOAttribute toAttribute = (TOAttribute) lastAttribute;
+        Preconditions.checkState(getLastAttribute() instanceof TOAttribute);
+        TOAttribute toAttribute = (TOAttribute) getLastAttribute();
 
         Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerMap = Maps.newHashMap();
 
@@ -122,14 +122,14 @@ public class ObjectResolver extends AttributeIfcSwitchStatement<AttributeResolvi
 
     @Override
     protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseListAttribute(ArrayType<?> openType) {
-        Preconditions.checkState(lastAttribute instanceof ListAttribute);
-        AttributeIfc innerAttribute = ((ListAttribute) lastAttribute).getInnerAttribute();
+        Preconditions.checkState(getLastAttribute() instanceof ListAttribute);
+        AttributeIfc innerAttribute = ((ListAttribute) getLastAttribute()).getInnerAttribute();
         return new ArrayAttributeResolvingStrategy(prepareStrategy(innerAttribute), openType);
     }
 
     @Override
     protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseListDependeciesAttribute(ArrayType<?> openType) {
-        Preconditions.checkState(lastAttribute instanceof ListDependenciesAttribute);
+        Preconditions.checkState(getLastAttribute() instanceof ListDependenciesAttribute);
         return new ArrayAttributeResolvingStrategy(caseDependencyAttribute(SimpleType.OBJECTNAME), openType);
     }
 
index e1b8ecf..26709db 100644 (file)
@@ -10,6 +10,9 @@ package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attri
 
 import com.google.common.base.Optional;
 import com.google.common.collect.Maps;
+import java.lang.reflect.InvocationTargetException;
+import java.text.ParseException;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -35,7 +38,7 @@ final class SimpleAttributeResolvingStrategy extends AbstractAttributeResolvingS
     }
 
     @Override
-    public Optional<Object> parseAttribute(String attrName, Object value) {
+    public Optional<Object> parseAttribute(String attrName, Object value) throws NetconfDocumentedException {
         if (value == null) {
             return Optional.absent();
         }
@@ -70,32 +73,42 @@ final class SimpleAttributeResolvingStrategy extends AbstractAttributeResolvingS
     }
 
     static interface Resolver {
-        Object resolveObject(Class<?> type, String attrName, String value);
+        Object resolveObject(Class<?> type, String attrName, String value) throws NetconfDocumentedException;
     }
 
     static class DefaultResolver implements Resolver {
 
         @Override
-        public Object resolveObject(Class<?> type, String attrName, String value) {
+        public Object resolveObject(Class<?> type, String attrName, String value) throws NetconfDocumentedException {
             try {
-                Object parsedValue = parseObject(type, value);
-                return parsedValue;
+                return parseObject(type, value);
             } catch (Exception e) {
-                throw new RuntimeException("Unable to resolve attribute " + attrName + " from " + value, e);
+                throw new NetconfDocumentedException("Unable to resolve attribute " + attrName + " from " + value,
+                        NetconfDocumentedException.ErrorType.application,
+                        NetconfDocumentedException.ErrorTag.operation_failed,
+                        NetconfDocumentedException.ErrorSeverity.error);
             }
         }
 
-        protected Object parseObject(Class<?> type, String value) throws Exception {
-            Method method = type.getMethod("valueOf", String.class);
-            Object parsedValue = method.invoke(null, value);
-            return parsedValue;
+        protected Object parseObject(Class<?> type, String value) throws NetconfDocumentedException {
+            Method method = null;
+            try {
+                method = type.getMethod("valueOf", String.class);
+                return method.invoke(null, value);
+            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
+                logger.trace("Error parsing object {}",e);
+                throw new NetconfDocumentedException("Error parsing object.",
+                        NetconfDocumentedException.ErrorType.application,
+                        NetconfDocumentedException.ErrorTag.operation_failed,
+                        NetconfDocumentedException.ErrorSeverity.error);
+            }
         }
     }
 
     static class StringResolver extends DefaultResolver {
 
         @Override
-        protected Object parseObject(Class<?> type, String value) throws Exception {
+        protected Object parseObject(Class<?> type, String value) {
             return value;
         }
     }
@@ -103,7 +116,7 @@ final class SimpleAttributeResolvingStrategy extends AbstractAttributeResolvingS
     static class BigIntegerResolver extends DefaultResolver {
 
         @Override
-        protected Object parseObject(Class<?> type, String value) throws Exception {
+        protected Object parseObject(Class<?> type, String value) {
             return new BigInteger(value);
         }
     }
@@ -111,7 +124,7 @@ final class SimpleAttributeResolvingStrategy extends AbstractAttributeResolvingS
     static class BigDecimalResolver extends DefaultResolver {
 
         @Override
-        protected Object parseObject(Class<?> type, String value) throws Exception {
+        protected Object parseObject(Class<?> type, String value) {
             return new BigDecimal(value);
         }
     }
@@ -119,16 +132,23 @@ final class SimpleAttributeResolvingStrategy extends AbstractAttributeResolvingS
     static class CharResolver extends DefaultResolver {
 
         @Override
-        protected Object parseObject(Class<?> type, String value) throws Exception {
+        protected Object parseObject(Class<?> type, String value)  {
             return new Character(value.charAt(0));
         }
     }
 
     static class DateResolver extends DefaultResolver {
-
         @Override
-        protected Object parseObject(Class<?> type, String value) throws Exception {
-            return Util.readDate(value);
+        protected Object parseObject(Class<?> type, String value) throws NetconfDocumentedException {
+            try {
+                return Util.readDate(value);
+            } catch (ParseException e) {
+                logger.trace("Unable parse value {} due to  {}",value, e);
+                throw new NetconfDocumentedException("Unable to parse value "+value+" as date.",
+                        NetconfDocumentedException.ErrorType.application,
+                        NetconfDocumentedException.ErrorTag.operation_failed,
+                        NetconfDocumentedException.ErrorSeverity.error);
+            }
         }
     }
 
index bc99ecf..cdebcfa 100644 (file)
@@ -34,10 +34,11 @@ final class UnionCompositeAttributeResolvingStrategy extends CompositeAttributeR
         Map<String, Object> newMap = Maps.newHashMap();
 
         for (String key : openType.keySet()) {
-            if (openType.getDescription(key).equals(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION))
+            if (openType.getDescription(key).equals(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION)){
                 newMap.put(key, valueMap.get(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION));
-            else
+            } else {
                 newMap.put(key, null);
+            }
         }
         return newMap;
     }
diff --git a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/AbstractAttributeWritingStrategy.java b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/AbstractAttributeWritingStrategy.java
new file mode 100644 (file)
index 0000000..61465f9
--- /dev/null
@@ -0,0 +1,14 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
+
+public abstract class AbstractAttributeWritingStrategy {
+    protected Object preprocess(Object value) {
+        return value;
+    }
+}
index 051f365..b17842b 100644 (file)
@@ -20,9 +20,9 @@ import com.google.common.base.Optional;
 
 public class CompositeAttributeWritingStrategy implements AttributeWritingStrategy {
 
-    protected final String key;
-    protected final Document document;
-    protected final Map<String, AttributeWritingStrategy> innerStrats;
+    private final String key;
+    private final Document document;
+    private final Map<String, AttributeWritingStrategy> innerStrats;
 
     public CompositeAttributeWritingStrategy(Document document, String key,
             Map<String, AttributeWritingStrategy> innerStrats) {
@@ -49,4 +49,16 @@ public class CompositeAttributeWritingStrategy implements AttributeWritingStrate
         }
         parentElement.appendChild(innerNode);
     }
+
+    public String getKey() {
+        return key;
+    }
+
+    public Document getDocument() {
+        return document;
+    }
+
+    public Map<String, AttributeWritingStrategy> getInnerStrats() {
+        return innerStrats;
+    }
 }
index 8d63bb0..4e07ec8 100644 (file)
@@ -90,11 +90,11 @@ public class ObjectXmlWriter extends AttributeIfcSwitchStatement<AttributeWritin
 
     @Override
     protected AttributeWritingStrategy caseTOAttribute(CompositeType openType) {
-        Preconditions.checkState(lastAttribute instanceof TOAttribute);
+        Preconditions.checkState(getLastAttribute() instanceof TOAttribute);
 
         Map<String, AttributeWritingStrategy> innerStrats = Maps.newHashMap();
         String currentKey = key;
-        for (Entry<String, AttributeIfc> innerAttrEntry : ((TOAttribute) lastAttribute).getYangPropertiesToTypesMap().entrySet()) {
+        for (Entry<String, AttributeIfc> innerAttrEntry : ((TOAttribute) getLastAttribute()).getYangPropertiesToTypesMap().entrySet()) {
 
             AttributeWritingStrategy innerStrategy = prepareWritingStrategy(innerAttrEntry.getKey(),
                     innerAttrEntry.getValue(), document);
@@ -106,8 +106,8 @@ public class ObjectXmlWriter extends AttributeIfcSwitchStatement<AttributeWritin
 
     @Override
     protected AttributeWritingStrategy caseListAttribute(ArrayType<?> openType) {
-        Preconditions.checkState(lastAttribute instanceof ListAttribute);
-        AttributeIfc innerAttribute = ((ListAttribute) lastAttribute).getInnerAttribute();
+        Preconditions.checkState(getLastAttribute() instanceof ListAttribute);
+        AttributeIfc innerAttribute = ((ListAttribute) getLastAttribute()).getInnerAttribute();
 
         AttributeWritingStrategy innerStrategy = prepareWritingStrategy(key, innerAttribute, document);
         return new ArrayAttributeWritingStrategy(innerStrategy);
@@ -115,7 +115,7 @@ public class ObjectXmlWriter extends AttributeIfcSwitchStatement<AttributeWritin
 
     @Override
     protected AttributeWritingStrategy caseListDependeciesAttribute(ArrayType<?> openType) {
-        Preconditions.checkState(lastAttribute instanceof ListDependenciesAttribute);
+        Preconditions.checkState(getLastAttribute() instanceof ListDependenciesAttribute);
         AttributeWritingStrategy innerStrategy = caseDependencyAttribute(SimpleType.OBJECTNAME);
         return new ArrayAttributeWritingStrategy(innerStrategy);
     }
index b2555f7..a74afd0 100644 (file)
@@ -8,15 +8,14 @@
 
 package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
 
-import java.util.Map;
-import java.util.Map.Entry;
-
+import com.google.common.base.Optional;
 import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-import com.google.common.base.Optional;
+import java.util.Map;
+import java.util.Map.Entry;
 
 public class RuntimeBeanEntryWritingStrategy extends CompositeAttributeWritingStrategy {
 
@@ -36,7 +35,7 @@ public class RuntimeBeanEntryWritingStrategy extends CompositeAttributeWritingSt
     public void writeElement(Element parentElement, String namespace, Object value) {
         Util.checkType(value, Map.class);
 
-        Element innerNode = XmlUtil.createElement(document, key, Optional.<String>absent());
+        Element innerNode = XmlUtil.createElement(getDocument(), getKey(), Optional.<String>absent());
 
         Map<?, ?> map = (Map<?, ?>) value;
 
@@ -46,7 +45,7 @@ public class RuntimeBeanEntryWritingStrategy extends CompositeAttributeWritingSt
             // bean
             Util.checkType(runtimeBeanInstanceMappingEntry.getValue(), Map.class);
             Map<?, ?> innerMap = (Map<?, ?>) runtimeBeanInstanceMappingEntry.getValue();
-            Element runtimeInstanceNode = XmlUtil.createElement(document, "_"
+            Element runtimeInstanceNode = XmlUtil.createElement(getDocument(), "_"
                     + (String) runtimeBeanInstanceMappingEntry.getKey(), Optional.<String>absent());
             innerNode.appendChild(runtimeInstanceNode);
 
@@ -57,7 +56,7 @@ public class RuntimeBeanEntryWritingStrategy extends CompositeAttributeWritingSt
                 String innerKey = (String) innerObjectEntry.getKey();
                 Object innerValue = innerObjectEntry.getValue();
 
-                innerStrats.get(innerKey).writeElement(runtimeInstanceNode, namespace, innerValue);
+                getInnerStrats().get(innerKey).writeElement(runtimeInstanceNode, namespace, innerValue);
             }
         }
         parentElement.appendChild(innerNode);
index bb5a67c..854f99c 100644 (file)
@@ -8,20 +8,20 @@
 
 package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
 
-import static com.google.common.base.Preconditions.checkState;
-import static java.lang.String.format;
-
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Multimap;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Date;
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
-
 import javax.management.ObjectName;
-
 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
@@ -29,24 +29,15 @@ import org.opendaylight.controller.netconf.confignetconfconnector.operations.edi
 import org.opendaylight.controller.netconf.util.xml.XmlElement;
 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
+import static com.google.common.base.Preconditions.checkState;
 
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Multimap;
 
 public class Config {
-    private final Logger logger = LoggerFactory.getLogger(Config.class);
 
     private final Map<String/* Namespace from yang file */,
             Map<String /* Name of module entry from yang file */, ModuleConfig>> moduleConfigs;
-    private final Map<String, ModuleConfig> moduleNamesToConfigs;
 
     private final Map<String, Map<Date, EditConfig.IdentityMapping>> identityMap;
 
@@ -56,11 +47,6 @@ public class Config {
 
     public Config(Map<String, Map<String, ModuleConfig>> moduleConfigs, Map<String, Map<Date,EditConfig.IdentityMapping>> identityMap) {
         this.moduleConfigs = moduleConfigs;
-        Map<String, ModuleConfig> moduleNamesToConfigs = new HashMap<>();
-        for (Entry<String, Map<String, ModuleConfig>> entry : moduleConfigs.entrySet()) {
-            moduleNamesToConfigs.putAll(entry.getValue());
-        }
-        this.moduleNamesToConfigs = Collections.unmodifiableMap(moduleNamesToConfigs);
         this.identityMap = identityMap;
     }
 
@@ -82,8 +68,9 @@ public class Config {
                 // TODO, this code does not support same module names from different namespaces
                 // Namespace should be present in ObjectName
 
-                if (instances == null)
+                if (instances == null){
                     continue;
+                }
 
                 innerRetVal.put(moduleName, instances);
 
@@ -104,11 +91,6 @@ public class Config {
         return retVal;
     }
 
-    // public Element toXml(Set<ObjectName> instancesToMap, String namespace,
-    // Document document) {
-    // return toXml(instancesToMap, Optional.of(namespace), document);
-    // }
-
     public Element toXml(Set<ObjectName> instancesToMap, Optional<String> maybeNamespace, Document document,
             Element dataElement, ServiceRegistryWrapper serviceTracker) {
 
@@ -264,10 +246,12 @@ public class Config {
         Optional<XmlElement> modulesOpt = getModulesElement(parent);
 
         List<XmlElement> recognised = Lists.newArrayList();
-        if(servicesOpt.isPresent())
+        if(servicesOpt.isPresent()){
             recognised.add(servicesOpt.get());
-        if(modulesOpt.isPresent())
+        }
+        if(modulesOpt.isPresent()){
             recognised.add(modulesOpt.get());
+        }
 
         parent.checkUnrecognisedElements(recognised);
     }
@@ -275,7 +259,7 @@ public class Config {
     private String getFactoryName(String factoryNameWithPrefix, String prefixOrEmptyString) {
         checkState(
                 factoryNameWithPrefix.startsWith(prefixOrEmptyString),
-                format("Internal error: text " + "content '%s' of type node does not start with prefix '%s'",
+                String.format("Internal error: text " + "content '%s' of type node does not start with prefix '%s'",
                         factoryNameWithPrefix, prefixOrEmptyString));
 
         int factoryNameAfterPrefixIndex;
index 1da9fab..0fe5fad 100644 (file)
@@ -63,26 +63,24 @@ public final class InstanceConfig {
         Map<String, Object> toXml = Maps.newHashMap();
 
         for (Entry<String, AttributeIfc> configDefEntry : jmxToAttrConfig.entrySet()) {
-
             // Skip children runtime beans as they are mapped by InstanceRuntime
-            if (configDefEntry.getValue() instanceof RuntimeBeanEntry)
+            if (configDefEntry.getValue() instanceof RuntimeBeanEntry){
                 continue;
-
+            }
             Object value = configRegistryClient.getAttributeCurrentValue(on, configDefEntry.getKey());
             try {
                 AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = mappingStrategies
                         .get(configDefEntry.getKey());
                 Optional<?> a = attributeMappingStrategy.mapAttribute(value);
-                if (a.isPresent() == false)
+                if (!a.isPresent()){
                     continue;
-
+                }
                 toXml.put(configDefEntry.getValue().getAttributeYangName(), a.get());
             } catch (Exception e) {
                 throw new IllegalStateException("Unable to map value " + value + " to attribute "
                         + configDefEntry.getKey(), e);
             }
         }
-
         return toXml;
     }
 
index f3d75d0..a5a625a 100644 (file)
@@ -8,12 +8,9 @@
 
 package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
 
-import java.util.Collection;
-import java.util.Date;
-import java.util.Map;
-
-import javax.management.ObjectName;
-
+import com.google.common.base.Optional;
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.Multimap;
 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
@@ -25,9 +22,10 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-import com.google.common.base.Optional;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Multimap;
+import javax.management.ObjectName;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Map;
 
 public class ModuleConfig {
 
@@ -64,7 +62,7 @@ public class ModuleConfig {
         Element root = XmlUtil.createElement(document, XmlNetconfConstants.MODULE_KEY, Optional.<String>absent());
         // Xml.addNamespaceAttr(document, root, namespace);
 
-        final String prefix = getPrefix(namespace);
+        final String prefix = getPrefix();
         Element typeElement = XmlUtil.createPrefixedTextElement(document, XmlUtil.createPrefixedValue(prefix, XmlNetconfConstants.TYPE_KEY), prefix,
                 moduleName, Optional.<String>of(namespace));
         // Xml.addNamespaceAttr(document, typeElement,
@@ -82,12 +80,8 @@ public class ModuleConfig {
         return root;
     }
 
-    private String getPrefix(String namespace) {
-        // if(namespace.contains(":")==false)
+    private String getPrefix() {
         return XmlNetconfConstants.PREFIX;
-        // return namespace.substring(namespace.lastIndexOf(':') + 1,
-        // namespace.length());
-
     }
 
     public ModuleElementResolved fromXml(XmlElement moduleElement, ServiceRegistryWrapper depTracker, String instanceName,
index 8d2d149..1f63555 100644 (file)
@@ -35,7 +35,9 @@ public class ServiceRegistryWrapper {
     public boolean hasRefName(String namespace, String serviceName, ObjectName on) {
         String qname = configServiceRefRegistry.getServiceInterfaceName(namespace, serviceName);
         Map<String, ObjectName> forQName = configServiceRefRegistry.getServiceMapping().get(qname);
-        if(forQName==null) return false;
+        if(forQName==null){
+            return false;
+        }
         return forQName.values().contains(on);
     }
 
@@ -70,7 +72,7 @@ public class ServiceRegistryWrapper {
         Map<String, Map<String, Map<String, String>>> retVal = Maps.newHashMap();
 
         Map<String, Map<String, ObjectName>> serviceMapping = configServiceRefRegistry.getServiceMapping();
-        for (String serviceQName : serviceMapping.keySet())
+        for (String serviceQName : serviceMapping.keySet()){
             for (String refName : serviceMapping.get(serviceQName).keySet()) {
 
                 ObjectName on = serviceMapping.get(serviceQName).get(refName);
@@ -91,11 +93,12 @@ public class ServiceRegistryWrapper {
                     serviceToRefs.put(localName, refsToSis);
                 }
 
-                Preconditions.checkState(refsToSis.containsKey(refName) == false,
+                Preconditions.checkState(!refsToSis.containsKey(refName),
                         "Duplicate reference name %s for service %s:%s, now for instance %s", refName, namespace,
                         localName, on);
                 refsToSis.put(refName, si.toString());
             }
+        }
 
         return retVal;
     }
@@ -108,10 +111,11 @@ public class ServiceRegistryWrapper {
         Map<String, Map<String, String>> serviceNameToRefNameToInstance = getMappedServices().get(namespace);
 
         Map<String, String> refNameToInstance;
-        if(serviceNameToRefNameToInstance == null || serviceNameToRefNameToInstance.containsKey(serviceName) == false) {
+        if(serviceNameToRefNameToInstance == null || !serviceNameToRefNameToInstance.containsKey(serviceName)) {
             refNameToInstance = Collections.emptyMap();
-        } else
+        } else {
             refNameToInstance = serviceNameToRefNameToInstance.get(serviceName);
+        }
 
         final Set<String> refNamesAsSet = toSet(refNameToInstance.keySet());
         if (refNamesAsSet.contains(refName)) {
@@ -135,12 +139,13 @@ public class ServiceRegistryWrapper {
     }
 
     private String findAvailableRefName(String refName, Set<String> refNamesAsSet) {
-        String intitialRefName = refName;
+        String availableRefName = "";
 
         while (true) {
-            refName = intitialRefName + "_" + suffix++;
-            if (refNamesAsSet.contains(refName) == false)
-                return refName;
+            availableRefName = refName + "_" + suffix++;
+            if (!refNamesAsSet.contains(availableRefName)){
+                return availableRefName;
+            }
         }
     }
 }
index f9df717..eb5c018 100644 (file)
@@ -8,33 +8,27 @@
 
 package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
 
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.management.ObjectName;
-
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.ObjectNameAttributeReadingStrategy;
 import org.opendaylight.controller.netconf.util.xml.XmlElement;
 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
+import javax.management.ObjectName;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 public final class Services {
 
-    private static final Logger logger = LoggerFactory.getLogger(Services.class);
-
     private static final String PROVIDER_KEY = "provider";
     private static final String NAME_KEY = "name";
     public static final String TYPE_KEY = "type";
@@ -98,7 +92,7 @@ public final class Services {
             XmlElement typeElement = service.getOnlyChildElement(TYPE_KEY);
             Entry<String, String> prefixNamespace = typeElement.findNamespaceOfTextContent();
 
-            Preconditions.checkState(prefixNamespace.getKey()!=null && prefixNamespace.getKey().equals("") == false, "Type attribute was not prefixed");
+            Preconditions.checkState(prefixNamespace.getKey()!=null && !prefixNamespace.getKey().equals(""), "Type attribute was not prefixed");
 
             Map<String, Map<String, String>> namespaceToServices = retVal.get(prefixNamespace.getValue());
             if(namespaceToServices == null) {
@@ -169,7 +163,7 @@ public final class Services {
         public static ServiceInstance fromString(String instanceId) {
             instanceId = instanceId.trim();
             Matcher matcher = p.matcher(instanceId);
-            if(matcher.matches() == false) {
+            if(!matcher.matches()) {
                 matcher = pDeprecated.matcher(instanceId);
             }
 
@@ -237,23 +231,30 @@ public final class Services {
 
         @Override
         public boolean equals(Object obj) {
-            if (this == obj)
+            if (this == obj){
                 return true;
-            if (obj == null)
+            }
+            if (obj == null){
                 return false;
-            if (getClass() != obj.getClass())
+            }
+            if (getClass() != obj.getClass()){
                 return false;
+            }
             ServiceInstance other = (ServiceInstance) obj;
             if (instanceName == null) {
-                if (other.instanceName != null)
+                if (other.instanceName != null){
                     return false;
-            } else if (!instanceName.equals(other.instanceName))
+                }
+            } else if (!instanceName.equals(other.instanceName)){
                 return false;
+            }
             if (moduleName == null) {
-                if (other.moduleName != null)
+                if (other.moduleName != null){
                     return false;
-            } else if (!moduleName.equals(other.moduleName))
+                }
+            } else if (!moduleName.equals(other.moduleName)){
                 return false;
+            }
             return true;
         }
 
index a081890..28b1417 100644 (file)
@@ -17,12 +17,12 @@ import java.util.Map;
 
 public final class ModuleRpcs {
 
-    Map<String, String> yangToJavaNames = Maps.newHashMap();
-    Map<String, Map<String, InstanceRuntimeRpc>> rpcMapping = Maps.newHashMap();
+    private final Map<String, String> yangToJavaNames = Maps.newHashMap();
+    private final Map<String, Map<String, InstanceRuntimeRpc>> rpcMapping = Maps.newHashMap();
 
     public void addNameMapping(RuntimeBeanEntry runtimeEntry) {
         String yangName = runtimeEntry.getYangName();
-        Preconditions.checkState(yangToJavaNames.containsKey(yangName) == false,
+        Preconditions.checkState(!yangToJavaNames.containsKey(yangName),
                 "RuntimeBean %s found twice in same namespace", yangName);
         yangToJavaNames.put(yangName, runtimeEntry.getJavaNamePrefix());
     }
@@ -35,7 +35,7 @@ public final class ModuleRpcs {
             rpcMapping.put(yangName, map);
         }
 
-        Preconditions.checkState(map.containsKey(rpc.getYangName()) == false, "Rpc %s for runtime bean %s added twice",
+        Preconditions.checkState(!map.containsKey(rpc.getYangName()), "Rpc %s for runtime bean %s added twice",
                 rpc.getYangName(), yangName);
         map.put(rpc.getYangName(), new InstanceRuntimeRpc(rpc));
     }
@@ -55,4 +55,12 @@ public final class ModuleRpcs {
         Preconditions.checkState(rpc != null, "No rpc found for runtime bean %s with name %s", rbeName, rpcName);
         return rpc;
     }
+
+    public Map<String, String> getYangToJavaNames() {
+        return yangToJavaNames;
+    }
+
+    public Map<String, Map<String, InstanceRuntimeRpc>> getRpcMapping() {
+        return rpcMapping;
+    }
 }
index 8c3b351..6a49275 100644 (file)
@@ -8,22 +8,19 @@
 
 package org.opendaylight.controller.netconf.confignetconfconnector.mapping.runtime;
 
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import javax.management.ObjectName;
-
+import com.google.common.base.Optional;
+import com.google.common.base.Predicate;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.Sets;
 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.InstanceConfig;
 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-import com.google.common.base.Optional;
-import com.google.common.base.Predicate;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Sets;
+import javax.management.ObjectName;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
 
 public class InstanceRuntime {
 
@@ -48,20 +45,23 @@ public class InstanceRuntime {
      * root + any number of additional properties
      */
     private Set<ObjectName> findChildren(ObjectName innerRootBean, Set<ObjectName> childRbeOns) {
-        final Hashtable<String, String> wantedProperties = innerRootBean.getKeyPropertyList();
+        final Map<String, String> wantedProperties = innerRootBean.getKeyPropertyList();
 
         return Sets.newHashSet(Collections2.filter(childRbeOns, new Predicate<ObjectName>() {
 
             @Override
             public boolean apply(ObjectName on) {
-                Hashtable<String, String> localProperties = on.getKeyPropertyList();
+                Map<String, String> localProperties = on.getKeyPropertyList();
                 for (Entry<String, String> propertyEntry : wantedProperties.entrySet()) {
-                    if (!localProperties.containsKey(propertyEntry.getKey()))
+                    if (!localProperties.containsKey(propertyEntry.getKey())){
                         return false;
-                    if (!localProperties.get(propertyEntry.getKey()).equals(propertyEntry.getValue()))
+                    }
+                    if (!localProperties.get(propertyEntry.getKey()).equals(propertyEntry.getValue())){
                         return false;
-                    if (localProperties.size() <= wantedProperties.size())
+                    }
+                    if (localProperties.size() <= wantedProperties.size()){
                         return false;
+                    }
                 }
                 return true;
             }
@@ -77,10 +77,12 @@ public class InstanceRuntime {
 
             @Override
             public boolean apply(ObjectName on) {
-                if (on.getKeyPropertyList().size() != keyListSize + 1)
+                if (on.getKeyPropertyList().size() != keyListSize + 1){
                     return false;
-                if (!on.getKeyPropertyList().containsKey(string))
+                }
+                if (!on.getKeyPropertyList().containsKey(string)){
                     return false;
+                }
                 return true;
             }
         }));
index 4936d1d..59767fe 100644 (file)
@@ -20,11 +20,9 @@ import java.util.Set;
 
 public class ModuleRuntime {
 
-    private final String moduleName;
     private final InstanceRuntime instanceRuntime;
 
     public ModuleRuntime(String moduleName, InstanceRuntime instanceRuntime) {
-        this.moduleName = moduleName;
         this.instanceRuntime = instanceRuntime;
     }
 
@@ -34,8 +32,9 @@ public class ModuleRuntime {
 
     private ObjectName findRoot(Collection<ObjectName> runtimeBeanOns) {
         for (ObjectName objectName : runtimeBeanOns) {
-            if (objectName.getKeyPropertyList().size() == 3)
+            if (objectName.getKeyPropertyList().size() == 3){
                 return objectName;
+            }
         }
         throw new IllegalStateException("Root runtime bean not found among " + runtimeBeanOns);
     }
index 8fc3ee1..439dea2 100644 (file)
@@ -85,7 +85,7 @@ public class Runtime {
 
                     Element runtimeXml;
                     ModuleConfig moduleConfig = moduleConfigs.get(localNamespace).get(moduleName);
-                    if(instanceToRbe==null || instanceToRbe.containsKey(instanceName) == false) {
+                    if(instanceToRbe==null || !instanceToRbe.containsKey(instanceName)) {
                         runtimeXml = moduleConfig.toXml(instanceON, serviceRegistry, document, localNamespace);
                     } else {
                         ModuleRuntime moduleRuntime = moduleRuntimes.get(localNamespace).get(moduleName);
@@ -101,14 +101,4 @@ public class Runtime {
         return root;
     }
 
-    private ObjectName findInstance(Collection<ObjectName> objectNames, String instanceName) {
-        for (ObjectName objectName : objectNames) {
-            String name = ObjectNameUtil.getInstanceName(objectName);
-            if(name.equals(instanceName))
-                return objectName;
-        }
-
-        throw new UnsupportedOperationException("Unable to find config bean instance under name " + instanceName + " among " + objectNames);
-    }
-
 }
index cd99ac4..c421710 100644 (file)
@@ -13,11 +13,15 @@ import org.opendaylight.controller.netconf.util.mapping.AbstractLastNetconfOpera
 
 public abstract class AbstractConfigNetconfOperation extends AbstractLastNetconfOperation {
 
-    protected final ConfigRegistryClient configRegistryClient;
+    private final ConfigRegistryClient configRegistryClient;
 
     protected AbstractConfigNetconfOperation(ConfigRegistryClient configRegistryClient,
             String netconfSessionIdForReporting) {
         super(netconfSessionIdForReporting);
         this.configRegistryClient = configRegistryClient;
     }
+
+    public ConfigRegistryClient getConfigRegistryClient() {
+        return configRegistryClient;
+    }
 }
index e88863c..c5fadb0 100644 (file)
@@ -8,8 +8,9 @@
 
 package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
 
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Multimap;
+import java.util.Map;
+import javax.management.InstanceNotFoundException;
+import javax.management.ObjectName;
 import org.opendaylight.controller.config.util.ConfigTransactionClient;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
@@ -18,23 +19,10 @@ import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import java.util.Map;
-
 public class DeleteEditConfigStrategy extends AbstractEditConfigStrategy {
 
     private static final Logger logger = LoggerFactory.getLogger(DeleteEditConfigStrategy.class);
 
-    private final Multimap<String, String> providedServices;
-
-    public DeleteEditConfigStrategy() {
-        this.providedServices = HashMultimap.create();
-    }
-
-    public DeleteEditConfigStrategy(Multimap<String, String> providedServices) {
-        this.providedServices = providedServices;
-    }
 
     @Override
     void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
index 428ddb3..3ea2605 100644 (file)
@@ -72,11 +72,11 @@ public class EditConfig extends AbstractConfigNetconfOperation {
             final EditConfigXmlParser.EditConfigExecution editConfigExecution) throws NetconfDocumentedException, NetconfConfigHandlingException {
 
         if (editConfigExecution.shouldTest()) {
-            executeTests(configRegistryClient, editConfigExecution);
+            executeTests(getConfigRegistryClient(), editConfigExecution);
         }
 
         if (editConfigExecution.shouldSet()) {
-            executeSet(configRegistryClient, editConfigExecution);
+            executeSet(getConfigRegistryClient(), editConfigExecution);
         }
 
         logger.trace("Operation {} successful", EditConfigXmlParser.EDIT_CONFIG);
@@ -224,7 +224,7 @@ public class EditConfig extends AbstractConfigNetconfOperation {
 
         void addIdSchemaNode(IdentitySchemaNode node) {
             String name = node.getQName().getLocalName();
-            Preconditions.checkState(identityNameToSchemaNode.containsKey(name) == false);
+            Preconditions.checkState(!identityNameToSchemaNode.containsKey(name));
             identityNameToSchemaNode.put(name, node);
         }
 
@@ -250,7 +250,7 @@ public class EditConfig extends AbstractConfigNetconfOperation {
             }
 
             Date revision = module.getRevision();
-            Preconditions.checkState(revisionsByNamespace.containsKey(revision) == false,
+            Preconditions.checkState(!revisionsByNamespace.containsKey(revision),
                     "Duplicate revision %s for namespace %s", revision, namespace);
 
             IdentityMapping identityMapping = revisionsByNamespace.get(revision);
@@ -306,8 +306,8 @@ public class EditConfig extends AbstractConfigNetconfOperation {
     protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
 
         EditConfigXmlParser.EditConfigExecution editConfigExecution;
-        Config cfg = getConfigMapping(configRegistryClient, yangStoreSnapshot);
-        editConfigExecution = editConfigXmlParser.fromXml(xml, cfg, transactionProvider, configRegistryClient);
+        Config cfg = getConfigMapping(getConfigRegistryClient(), yangStoreSnapshot);
+        editConfigExecution = editConfigXmlParser.fromXml(xml, cfg, transactionProvider, getConfigRegistryClient());
 
         Element responseInternal;
         responseInternal = getResponseInternal(document, editConfigExecution);
index de69795..547ffcd 100644 (file)
@@ -98,9 +98,10 @@ public class EditConfigXmlParser {
                 .getOnlyChildElementWithSameNamespaceOptionally(EditConfigXmlParser.ERROR_OPTION_KEY);
         if (errorOptionElement.isPresent()) {
             String errorOptionParsed = errorOptionElement.get().getTextContent();
-            if (false == errorOptionParsed.equals(EditConfigXmlParser.DEFAULT_ERROR_OPTION))
+            if (!errorOptionParsed.equals(EditConfigXmlParser.DEFAULT_ERROR_OPTION)){
                 throw new UnsupportedOperationException("Only " + EditConfigXmlParser.DEFAULT_ERROR_OPTION
                         + " supported for " + EditConfigXmlParser.ERROR_OPTION_KEY + ", was " + errorOptionParsed);
+            }
         }
 
         // Default op
index 2f41def..6b81603 100644 (file)
@@ -65,7 +65,7 @@ public enum EditStrategyType {
         case replace:
             return new ReplaceEditConfigStrategy(providedServices);
         case delete:
-            return new DeleteEditConfigStrategy(providedServices);
+            return new DeleteEditConfigStrategy();
         case remove:
             return new RemoveEditConfigStrategy();
         case none:
index 0a72547..3e5707c 100644 (file)
@@ -54,8 +54,9 @@ public class MergeEditConfigStrategy extends AbstractEditConfigStrategy {
         for (Entry<String, String> namespaceToService : providedServices.entries()) {
 
             if(services.hasRefName(namespaceToService.getKey(),
-                    namespaceToService.getValue(), on))
+                    namespaceToService.getValue(), on)){
                 continue;
+            }
 
             String refName = services.getNewDefaultRefName(namespaceToService.getKey(), namespaceToService.getValue(),
                     ObjectNameUtil.getFactoryName(on), ObjectNameUtil.getInstanceName(on));
index b61fcba..bc3082f 100644 (file)
@@ -55,8 +55,9 @@ public class ReplaceEditConfigStrategy extends AbstractEditConfigStrategy {
         for (Entry<String, String> namespaceToService : providedServices.entries()) {
 
             if(services.hasRefName(namespaceToService.getKey(),
-                    namespaceToService.getValue(), on))
+                    namespaceToService.getValue(), on)){
                 continue;
+            }
 
             String refName = services.getNewDefaultRefName(namespaceToService.getKey(), namespaceToService.getValue(),
                     ObjectNameUtil.getFactoryName(on), ObjectNameUtil.getInstanceName(on));
index dd0e53b..4665c2c 100644 (file)
@@ -69,12 +69,14 @@ public class Get extends AbstractConfigNetconfOperation {
                 RuntimeBeanEntry root = null;
                 for (RuntimeBeanEntry rbe : mbe.getRuntimeBeans()) {
                     cache.put(rbe, new InstanceConfig(configRegistryClient, rbe.getYangPropertiesToTypesMap()));
-                    if (rbe.isRoot())
+                    if (rbe.isRoot()){
                         root = rbe;
+                    }
                 }
 
-                if (root == null)
+                if (root == null){
                     continue;
+                }
 
                 InstanceRuntime rootInstanceRuntime = createInstanceRuntime(root, cache);
                 ModuleRuntime moduleRuntime = new ModuleRuntime(module, rootInstanceRuntime);
@@ -108,8 +110,9 @@ public class Get extends AbstractConfigNetconfOperation {
         xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
 
         // Filter option - unsupported
-        if (xml.getChildElements(XmlNetconfConstants.FILTER).size() != 0)
+        if (xml.getChildElements(XmlNetconfConstants.FILTER).size() != 0){
             throw new UnsupportedOperationException("Unsupported option " + XmlNetconfConstants.FILTER + " for " + XmlNetconfConstants.GET);
+        }
     }
 
     @Override
@@ -121,21 +124,21 @@ public class Get extends AbstractConfigNetconfOperation {
     protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
         checkXml(xml);
 
-        final Set<ObjectName> runtimeBeans = configRegistryClient.lookupRuntimeBeans();
+        final Set<ObjectName> runtimeBeans = getConfigRegistryClient().lookupRuntimeBeans();
 
         //Transaction provider required only for candidate datastore
         final Set<ObjectName> configBeans = Datastore.getInstanceQueryStrategy(Datastore.running, null)
-                .queryInstances(configRegistryClient);
+                .queryInstances(getConfigRegistryClient());
 
-        final Map<String, Map<String, ModuleRuntime>> moduleRuntimes = createModuleRuntimes(configRegistryClient,
+        final Map<String, Map<String, ModuleRuntime>> moduleRuntimes = createModuleRuntimes(getConfigRegistryClient(),
                 yangStoreSnapshot.getModuleMXBeanEntryMap());
         final Map<String, Map<String, ModuleConfig>> moduleConfigs = EditConfig.transformMbeToModuleConfigs(
-                configRegistryClient, yangStoreSnapshot.getModuleMXBeanEntryMap());
+                getConfigRegistryClient(), yangStoreSnapshot.getModuleMXBeanEntryMap());
 
         final Runtime runtime = new Runtime(moduleRuntimes, moduleConfigs);
 
         ObjectName txOn = transactionProvider.getOrCreateTransaction();
-        ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(txOn);
+        ConfigTransactionClient ta = getConfigRegistryClient().getConfigTransactionClient(txOn);
         final Element element = runtime.toXml(runtimeBeans, configBeans, document, new ServiceRegistryWrapper(ta));
 
         logger.trace("{} operation successful", XmlNetconfConstants.GET);
index 11d3e32..82e07c1 100644 (file)
@@ -66,9 +66,10 @@ public class GetConfig extends AbstractConfigNetconfOperation {
         Datastore sourceDatastore = Datastore.valueOf(sourceParsed);
 
         // Filter option - unsupported
-        if (xml.getChildElements(XmlNetconfConstants.FILTER).size() != 0)
+        if (xml.getChildElements(XmlNetconfConstants.FILTER).size() != 0){
             throw new UnsupportedOperationException("Unsupported option " + XmlNetconfConstants.FILTER + " for "
                     + GET_CONFIG);
+        }
 
         return sourceDatastore;
 
@@ -104,6 +105,6 @@ public class GetConfig extends AbstractConfigNetconfOperation {
     public Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
         Datastore source;
         source = fromXml(xml);
-        return getResponseInternal(document, configRegistryClient, source);
+        return getResponseInternal(document, getConfigRegistryClient(), source);
     }
 }
index 5a30fc8..7790e09 100644 (file)
@@ -139,8 +139,9 @@ public class RuntimeRpc extends AbstractConfigNetconfOperation {
         final Optional<XmlElement> contextInstanceElement = operationElement
                 .getOnlyChildElementOptionally(CONTEXT_INSTANCE);
 
-        if (contextInstanceElement.isPresent() == false)
+        if (!contextInstanceElement.isPresent()){
             return HandlingPriority.CANNOT_HANDLE;
+        }
 
         final RuntimeRpcElementResolved id = RuntimeRpcElementResolved.fromXpath(contextInstanceElement.get()
                 .getTextContent(), netconfOperationName, netconfOperationNamespace);
@@ -182,7 +183,7 @@ public class RuntimeRpc extends AbstractConfigNetconfOperation {
 
         logger.debug("Invoking operation {} on {} with arguments {}", execution.operationName, execution.on,
                 execution.attributes);
-        final Object result = executeOperation(configRegistryClient, execution.on, execution.operationName,
+        final Object result = executeOperation(getConfigRegistryClient(), execution.on, execution.operationName,
                 execution.attributes);
 
         logger.trace("Operation {} called successfully on {} with arguments {} with result {}", execution.operationName,
@@ -225,7 +226,7 @@ public class RuntimeRpc extends AbstractConfigNetconfOperation {
 
         for (XmlElement xmlElement : xml.getChildElements()) {
             final String name = xmlElement.getName();
-            if (CONTEXT_INSTANCE.equals(name) == false) { // skip context
+            if (!CONTEXT_INSTANCE.equals(name)) { // skip context
                                                           // instance child node
                                                           // because it
                                                           // specifies
index 0f0b122..5cf7f30 100644 (file)
@@ -93,12 +93,12 @@ public final class RuntimeRpcElementResolved {
                 RuntimeRpc.CONTEXT_INSTANCE, xpath, elementName, xpathPatternBlueprint);
 
         PatternGroupResolver groups = new PatternGroupResolver(matcher.group("key1"), matcher.group("value1"),
-                matcher.group("key2"), matcher.group("value2"), matcher.group("additional"));
+                matcher.group("value2"), matcher.group("additional"));
 
         String moduleName = groups.getModuleName();
         String instanceName = groups.getInstanceName();
 
-        HashMap<String, String> additionalAttributes = groups.getAdditionalKeys(elementName, moduleName);
+        Map<String, String> additionalAttributes = groups.getAdditionalKeys(elementName, moduleName);
 
         return new RuntimeRpcElementResolved(namespace, moduleName, instanceName, groups.getRuntimeBeanYangName(),
                 additionalAttributes);
@@ -106,15 +106,14 @@ public final class RuntimeRpcElementResolved {
 
     private static final class PatternGroupResolver {
 
-        private final String key1, key2, value1, value2;
+        private final String key1, value1, value2;
         private final String additional;
         private String runtimeBeanYangName;
 
-        PatternGroupResolver(String key1, String value1, String key2, String value2, String additional) {
+        PatternGroupResolver(String key1, String value1,  String value2, String additional) {
             this.key1 = Preconditions.checkNotNull(key1);
             this.value1 = Preconditions.checkNotNull(value1);
 
-            this.key2 = Preconditions.checkNotNull(key2);
             this.value2 = Preconditions.checkNotNull(value2);
 
             this.additional = Preconditions.checkNotNull(additional);
@@ -128,13 +127,14 @@ public final class RuntimeRpcElementResolved {
             return key1.equals(XmlNetconfConstants.NAME_KEY) ? value1 : value2;
         }
 
-        HashMap<String, String> getAdditionalKeys(String elementName, String moduleName) {
+        Map<String, String> getAdditionalKeys(String elementName, String moduleName) {
             HashMap<String, String> additionalAttributes = Maps.newHashMap();
 
             runtimeBeanYangName = moduleName;
             for (String additionalKeyValue : additional.split("/")) {
-                if (Strings.isNullOrEmpty(additionalKeyValue))
+                if (Strings.isNullOrEmpty(additionalKeyValue)){
                     continue;
+                }
                 Matcher matcher = additionalPattern.matcher(additionalKeyValue);
                 Preconditions
                         .checkState(
index 421870c..3ba92b0 100644 (file)
@@ -73,7 +73,7 @@ public class Activator implements BundleActivator {
     }
 
     @Override
-    public void stop(BundleContext context) throws Exception {
+    public void stop(BundleContext context) {
         if (configRegistryLookup != null) {
             configRegistryLookup.interrupt();
         }
index 09966b8..7f4f8fc 100644 (file)
@@ -24,17 +24,11 @@ import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import java.util.Set;
 
 final class NetconfOperationProvider {
-    private final YangStoreSnapshot yangStoreSnapshot;
     private final Set<NetconfOperation> operations;
-    private final ConfigRegistryClient configRegistryClient;
-    private final TransactionProvider transactionProvider;
 
     NetconfOperationProvider(YangStoreSnapshot yangStoreSnapshot, ConfigRegistryClient configRegistryClient,
             TransactionProvider transactionProvider, String netconfSessionIdForReporting) {
 
-        this.yangStoreSnapshot = yangStoreSnapshot;
-        this.configRegistryClient = configRegistryClient;
-        this.transactionProvider = transactionProvider;
         operations = setUpOperations(yangStoreSnapshot, configRegistryClient, transactionProvider,
                 netconfSessionIdForReporting);
     }
index b8b7fcb..12469f6 100644 (file)
@@ -52,7 +52,7 @@ public class NetconfOperationServiceFactoryImpl implements NetconfOperationServi
                     Thread.sleep(ATTEMPT_TIMEOUT_MS);
                 } catch (InterruptedException e1) {
                     Thread.currentThread().interrupt();
-                    throw new RuntimeException("Interrupted while reattempting connection", e1);
+                    throw new IllegalStateException("Interrupted while reattempting connection", e1);
                 }
             }
         }
index c6248df..1069858 100644 (file)
@@ -61,8 +61,9 @@ public class NetconfOperationServiceImpl implements NetconfOperationService {
         for (Map<String, ModuleMXBeanEntry> moduleNameToMBE : moduleMXBeanEntryMap.values()) {
             for (ModuleMXBeanEntry moduleMXBeanEntry : moduleNameToMBE.values()) {
                 String moduleSeenByYangStore = moduleMXBeanEntry.getYangModuleQName().toString();
-                if(modulesSeenByConfig.contains(moduleSeenByYangStore) == false)
+                if(!modulesSeenByConfig.contains(moduleSeenByYangStore)){
                     missingModulesFromConfig.add(moduleSeenByYangStore);
+                }
             }
         }
 
@@ -149,7 +150,7 @@ public class NetconfOperationServiceImpl implements NetconfOperationService {
         }
     }
 
-    private static class YangStoreCapability extends BasicCapability {
+    private static final class YangStoreCapability extends BasicCapability {
 
         private final String content;
         private final String revision;
index 756a38e..250af68 100644 (file)
@@ -34,6 +34,7 @@ public class TransactionProvider implements AutoCloseable {
     private final String netconfSessionIdForReporting;
     private ObjectName transaction;
     private final List<ObjectName> allOpenedTransactions = new ArrayList<>();
+    private static final String  NO_TRANSACTION_FOUND_FOR_SESSION = "No transaction found for session ";
 
     public TransactionProvider(ConfigRegistryClient configRegistryClient, String netconfSessionIdForReporting) {
         this.configRegistryClient = configRegistryClient;
@@ -56,11 +57,12 @@ public class TransactionProvider implements AutoCloseable {
 
     public Optional<ObjectName> getTransaction() {
 
-        if (transaction == null)
+        if (transaction == null){
             return Optional.absent();
+        }
 
         // Transaction was already closed somehow
-        if (isStillOpenTransaction(transaction) == false) {
+        if (!isStillOpenTransaction(transaction)) {
             logger.warn("Fixing illegal state: transaction {} was closed in {}", transaction,
                     netconfSessionIdForReporting);
             transaction = null;
@@ -70,8 +72,7 @@ public class TransactionProvider implements AutoCloseable {
     }
 
     private boolean isStillOpenTransaction(ObjectName transaction) {
-        boolean isStillOpenTransaction = configRegistryClient.getOpenConfigs().contains(transaction);
-        return isStillOpenTransaction;
+        return configRegistryClient.getOpenConfigs().contains(transaction);
     }
 
     public synchronized ObjectName getOrCreateTransaction() {
@@ -126,7 +127,7 @@ public class TransactionProvider implements AutoCloseable {
     public synchronized void abortTransaction() {
         logger.debug("Aborting current transaction");
         Optional<ObjectName> taON = getTransaction();
-        Preconditions.checkState(taON.isPresent(), "No transaction found for session " + netconfSessionIdForReporting);
+        Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + netconfSessionIdForReporting);
 
         ConfigTransactionClient transactionClient = configRegistryClient.getConfigTransactionClient(taON.get());
         transactionClient.abortConfig();
@@ -143,7 +144,7 @@ public class TransactionProvider implements AutoCloseable {
 
     public void validateTransaction() throws ValidationException {
         Optional<ObjectName> taON = getTransaction();
-        Preconditions.checkState(taON.isPresent(), "No transaction found for session " + netconfSessionIdForReporting);
+        Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + netconfSessionIdForReporting);
 
         ConfigTransactionClient transactionClient = configRegistryClient.getConfigTransactionClient(taON.get());
         transactionClient.validateConfig();
@@ -171,10 +172,11 @@ public class TransactionProvider implements AutoCloseable {
             try {
                 transactionClient.destroyModule(instance);
             } catch (InstanceNotFoundException e) {
-                if (isTest)
+                if (isTest){
                     logger.debug("Unable to clean configuration in transactiom {}", taON, e);
-                else
+                } else {
                     logger.warn("Unable to clean configuration in transactiom {}", taON, e);
+                }
 
                 throw new IllegalStateException("Unable to clean configuration in transactiom " + taON, e);
             }
@@ -187,7 +189,7 @@ public class TransactionProvider implements AutoCloseable {
 
     public void wipeTransaction() {
         Optional<ObjectName> taON = getTransaction();
-        Preconditions.checkState(taON.isPresent(), "No transaction found for session " + netconfSessionIdForReporting);
+        Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + netconfSessionIdForReporting);
         wipeInternal(taON.get(), false, null);
     }
 
index 1616857..40a15be 100644 (file)
@@ -50,7 +50,7 @@ public class ConfigPersisterNotificationHandler implements Closeable {
         try {
             mBeanServerConnection.addNotificationListener(DefaultCommitOperationMXBean.OBJECT_NAME, listener, null, null);
         } catch (InstanceNotFoundException | IOException e) {
-            throw new RuntimeException("Cannot register as JMX listener to netconf", e);
+            throw new IllegalStateException("Cannot register as JMX listener to netconf", e);
         }
     }
 
@@ -79,9 +79,8 @@ class ConfigPersisterNotificationListener implements NotificationListener {
 
     @Override
     public void handleNotification(Notification notification, Object handback) {
-        if (notification instanceof NetconfJMXNotification == false) {
+        if (!(notification instanceof NetconfJMXNotification))
             return;
-        }
 
         // Socket should not be closed at this point
         // Activator unregisters this as JMX listener before close is called
index 31a4f08..a0e7974 100644 (file)
@@ -9,20 +9,19 @@
 package org.opendaylight.controller.netconf.persist.impl;
 
 import com.google.common.annotations.VisibleForTesting;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.ListIterator;
 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
 import org.opendaylight.controller.config.persist.api.Persister;
+import org.opendaylight.controller.config.persist.api.PropertiesProvider;
 import org.opendaylight.controller.config.persist.api.StorageAdapter;
 import org.opendaylight.controller.netconf.persist.impl.osgi.ConfigPersisterActivator;
-import org.opendaylight.controller.netconf.persist.impl.osgi.PropertiesProviderBaseImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.ListIterator;
-
 /**
  * {@link Persister} implementation that delegates persisting functionality to
  * underlying {@link Persister} storages. Each storage has unique id, class, readonly value.
@@ -88,7 +87,7 @@ public final class PersisterAggregator implements Persister {
         }
     }
 
-    private static PersisterWithConfiguration loadConfiguration(final String index, final PropertiesProviderBaseImpl propertiesProvider) {
+    private static PersisterWithConfiguration loadConfiguration(final String index, final PropertiesProvider propertiesProvider) {
 
         String classKey = index + "." + ConfigPersisterActivator.STORAGE_ADAPTER_CLASS_PROP_SUFFIX;
         String storageAdapterClass = propertiesProvider.getProperty(classKey);
@@ -102,7 +101,7 @@ public final class PersisterAggregator implements Persister {
         try {
             Class<?> clazz = Class.forName(storageAdapterClass);
             boolean implementsCorrectIfc = StorageAdapter.class.isAssignableFrom(clazz);
-            if (implementsCorrectIfc == false) {
+            if (!implementsCorrectIfc) {
                 throw new IllegalArgumentException("Storage adapter " + clazz + " does not implement " + StorageAdapter.class);
             }
             storageAdapter = StorageAdapter.class.cast(clazz.newInstance());
@@ -131,10 +130,10 @@ public final class PersisterAggregator implements Persister {
 
     }
 
-    public static PersisterAggregator createFromProperties(PropertiesProviderBaseImpl propertiesProvider) {
+    public static PersisterAggregator createFromProperties(PropertiesProvider propertiesProvider) {
         List<PersisterWithConfiguration> persisterWithConfigurations = new ArrayList<>();
         String prefixes = propertiesProvider.getProperty("active");
-        if (prefixes!=null && prefixes.isEmpty() == false) {
+        if (prefixes!=null && !prefixes.isEmpty()) {
             String [] keys = prefixes.split(",");
             for (String index: keys) {
                 persisterWithConfigurations.add(PersisterAggregator.loadConfiguration(index, propertiesProvider));
@@ -169,7 +168,7 @@ public final class PersisterAggregator implements Persister {
             } catch (IOException e) {
                 throw new RuntimeException("Error while calling loadLastConfig on " +  persisterWithConfiguration, e);
             }
-            if (configs.isEmpty() == false) {
+            if (!configs.isEmpty()) {
                 logger.debug("Found non empty configs using {}:{}", persisterWithConfiguration, configs);
                 return configs;
             }
index d9466ff..238661f 100644 (file)
@@ -8,13 +8,12 @@
 package org.opendaylight.controller.netconf.persist.impl;
 
 import org.opendaylight.controller.config.persist.api.PropertiesProvider;
-import org.opendaylight.controller.netconf.persist.impl.osgi.PropertiesProviderBaseImpl;
 
 public class PropertiesProviderAdapterImpl implements PropertiesProvider {
-    private final PropertiesProviderBaseImpl inner;
+    private final PropertiesProvider inner;
     private final String index;
 
-    public PropertiesProviderAdapterImpl(PropertiesProviderBaseImpl inner, String index) {
+    public PropertiesProviderAdapterImpl(PropertiesProvider inner, String index) {
         this.inner = inner;
         this.index = index;
     }
@@ -29,6 +28,12 @@ public class PropertiesProviderAdapterImpl implements PropertiesProvider {
         return inner.getPrefix() + "." + index + ".properties";
     }
 
+    @Override
+    public String getPropertyWithoutPrefix(String fullKey) {
+        return inner.getPropertyWithoutPrefix(fullKey);
+    }
+
+
     @Override
     public String getFullKeyForReporting(String key) {
         return getPrefix()  + "." + key;
index b1bf232..e02e27a 100644 (file)
@@ -81,7 +81,7 @@ public class ConfigPersisterTest {
 
     // this means pushing of config was successful
     public void assertCannotRegisterAsJMXListener_pushWasSuccessful() {
-        handler.assertException(RuntimeException.class, "Cannot register as JMX listener to netconf");
+        handler.assertException(IllegalStateException.class, "Cannot register as JMX listener to netconf");
     }
 
     public NetconfOperationService getWorkingService(Document document) throws SAXException, IOException, NetconfDocumentedException {
diff --git a/opendaylight/netconf/netconf-client/src/main/java/org/opendaylight/controller/netconf/client/NetconfClient.java b/opendaylight/netconf/netconf-client/src/main/java/org/opendaylight/controller/netconf/client/NetconfClient.java
new file mode 100644 (file)
index 0000000..d98211d
--- /dev/null
@@ -0,0 +1,171 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.netconf.client;
+
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GlobalEventExecutor;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.Set;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.opendaylight.controller.netconf.api.NetconfMessage;
+import org.opendaylight.protocol.framework.NeverReconnectStrategy;
+import org.opendaylight.protocol.framework.ReconnectStrategy;
+import org.opendaylight.protocol.framework.TimedReconnectStrategy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Stopwatch;
+import com.google.common.collect.Sets;
+
+/**
+ * @deprecated Use {@link NetconfClientDispatcher.createClient()} or {@link NetconfClientDispatcher.createReconnectingClient()} instead.
+ */
+@Deprecated
+public class NetconfClient implements Closeable {
+
+    private static final Logger logger = LoggerFactory.getLogger(NetconfClient.class);
+
+    public static final int DEFAULT_CONNECT_TIMEOUT = 5000;
+    private final NetconfClientDispatcher dispatch;
+    private final String label;
+    private final NetconfClientSession clientSession;
+    private final NetconfClientSessionListener sessionListener;
+    private final long sessionId;
+    private final InetSocketAddress address;
+
+    // TODO test reconnecting constructor
+    public NetconfClient(String clientLabelForLogging, InetSocketAddress address, int connectionAttempts,
+            int attemptMsTimeout, NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
+        this(clientLabelForLogging, address, getReconnectStrategy(connectionAttempts, attemptMsTimeout),
+                netconfClientDispatcher);
+    }
+
+    private NetconfClient(String clientLabelForLogging, InetSocketAddress address, ReconnectStrategy strat, NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
+        this.label = clientLabelForLogging;
+        dispatch = netconfClientDispatcher;
+        sessionListener = new SimpleNetconfClientSessionListener();
+        Future<NetconfClientSession> clientFuture = dispatch.createClient(address, sessionListener, strat);
+        this.address = address;
+        clientSession = get(clientFuture);
+        this.sessionId = clientSession.getSessionId();
+    }
+
+    private NetconfClientSession get(Future<NetconfClientSession> clientFuture) throws InterruptedException {
+        try {
+            return clientFuture.get();
+        } catch (CancellationException e) {
+            throw new RuntimeException("Cancelling " + this, e);
+        } catch (ExecutionException e) {
+            throw new IllegalStateException("Unable to create " + this, e);
+        }
+    }
+
+    public static NetconfClient clientFor(String clientLabelForLogging, InetSocketAddress address, ReconnectStrategy strategy, NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
+        return new NetconfClient(clientLabelForLogging,address,strategy,netconfClientDispatcher);
+    }
+
+    public static NetconfClient clientFor(String clientLabelForLogging, InetSocketAddress address,
+            ReconnectStrategy strategy, NetconfClientDispatcher netconfClientDispatcher, NetconfClientSessionListener listener) throws InterruptedException {
+        return new NetconfClient(clientLabelForLogging,address,strategy,netconfClientDispatcher,listener);
+    }
+
+    public NetconfClient(String clientLabelForLogging, InetSocketAddress address, int connectTimeoutMs,
+            NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
+        this(clientLabelForLogging, address,
+                new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, connectTimeoutMs), netconfClientDispatcher);
+    }
+
+    public NetconfClient(String clientLabelForLogging, InetSocketAddress address,
+            NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
+        this(clientLabelForLogging, address, new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE,
+                DEFAULT_CONNECT_TIMEOUT), netconfClientDispatcher);
+    }
+
+    public NetconfClient(String clientLabelForLogging, InetSocketAddress address, ReconnectStrategy strategy,
+            NetconfClientDispatcher netconfClientDispatcher, NetconfClientSessionListener listener) throws InterruptedException{
+        this.label = clientLabelForLogging;
+        dispatch = netconfClientDispatcher;
+        sessionListener = listener;
+        Future<NetconfClientSession> clientFuture = dispatch.createClient(address, sessionListener, strategy);
+        this.address = address;
+        clientSession = get(clientFuture);
+        this.sessionId = clientSession.getSessionId();
+    }
+
+    public Future<NetconfMessage> sendRequest(NetconfMessage message) {
+        return ((SimpleNetconfClientSessionListener)sessionListener).sendRequest(message);
+    }
+
+    /**
+     * @deprecated Use {@link sendRequest} instead
+     */
+    @Deprecated
+    public NetconfMessage sendMessage(NetconfMessage message) throws ExecutionException, InterruptedException, TimeoutException {
+        return sendMessage(message, 5, 1000);
+    }
+
+    /**
+     * @deprecated Use {@link sendRequest} instead
+     */
+    @Deprecated
+    public NetconfMessage sendMessage(NetconfMessage message, int attempts, int attemptMsDelay) throws ExecutionException, InterruptedException, TimeoutException {
+        final Stopwatch stopwatch = new Stopwatch().start();
+
+        try {
+            return sendRequest(message).get(attempts * attemptMsDelay, TimeUnit.MILLISECONDS);
+        } finally {
+            stopwatch.stop();
+            logger.debug("Total time spent waiting for response from {}: {} ms", address, stopwatch.elapsed(TimeUnit.MILLISECONDS));
+        }
+    }
+
+    @Override
+    public void close() throws IOException {
+        clientSession.close();
+    }
+
+    public NetconfClientDispatcher getNetconfClientDispatcher() {
+        return dispatch;
+    }
+
+    private static ReconnectStrategy getReconnectStrategy(int connectionAttempts, int attemptMsTimeout) {
+        return new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, attemptMsTimeout, 1000, 1.0, null,
+                Long.valueOf(connectionAttempts), null);
+    }
+
+    @Override
+    public String toString() {
+        final StringBuffer sb = new StringBuffer("NetconfClient{");
+        sb.append("label=").append(label);
+        sb.append(", sessionId=").append(sessionId);
+        sb.append('}');
+        return sb.toString();
+    }
+
+    public long getSessionId() {
+        return sessionId;
+    }
+
+    public Set<String> getCapabilities() {
+        Preconditions.checkState(clientSession != null, "Client was not initialized successfully");
+        return Sets.newHashSet(clientSession.getServerCapabilities());
+    }
+
+    public NetconfClientSession getClientSession() {
+        return clientSession;
+    }
+}
index 20da6aa..c7c723c 100644 (file)
@@ -79,7 +79,7 @@ public class NetconfClientDispatcher extends AbstractDispatcher<NetconfClientSes
         });
     }
 
-    private static class ClientChannelInitializer extends AbstractChannelInitializer<NetconfClientSession> {
+    private static final class ClientChannelInitializer extends AbstractChannelInitializer<NetconfClientSession> {
 
         private final NetconfClientSessionNegotiatorFactory negotiatorFactory;
         private final NetconfClientSessionListener sessionListener;
index 504e4c9..524f0b5 100644 (file)
@@ -26,8 +26,8 @@ import com.google.common.base.Preconditions;
 
 public class SimpleNetconfClientSessionListener implements NetconfClientSessionListener {
     private static final class RequestEntry {
-        final Promise<NetconfMessage> promise;
-        final NetconfMessage request;
+        private final Promise<NetconfMessage> promise;
+        private final NetconfMessage request;
 
         public RequestEntry(Promise<NetconfMessage> future, NetconfMessage request) {
             this.promise = Preconditions.checkNotNull(future);
index 6a86ecd..91385ba 100644 (file)
@@ -68,12 +68,11 @@ public class CapabilityProviderImpl implements CapabilityProvider {
             final Set<Capability> caps = netconfOperationService.getCapabilities();
 
             for (Capability cap : caps) {
-                if (cap.getModuleName().isPresent() == false)
-                    continue;
-                if (cap.getRevision().isPresent() == false)
-                    continue;
-                if (cap.getCapabilitySchema().isPresent() == false)
+                if (!cap.getModuleName().isPresent()
+                        || !cap.getRevision().isPresent()
+                        || !cap.getCapabilitySchema().isPresent()){
                     continue;
+                }
 
                 final String currentModuleName = cap.getModuleName().get();
                 Map<String, String> revisionMap = mappedModulesToRevisionToSchema.get(currentModuleName);
index 4461054..6c7f9d9 100644 (file)
@@ -42,7 +42,7 @@ public class DefaultCommitNotificationProducer extends NotificationBroadcasterSu
         try {
             mbs.registerMBean(instance, on);
         } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
-            throw new RuntimeException("Unable to register " + instance + " as " + on, e);
+            throw new IllegalStateException("Unable to register " + instance + " as " + on, e);
         }
     }
 
index b3245ff..75be1f8 100644 (file)
@@ -9,6 +9,8 @@
 package org.opendaylight.controller.netconf.impl;
 
 
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
@@ -26,9 +28,6 @@ import org.w3c.dom.Document;
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
 
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableMap;
-
 public class NetconfServerSessionListener implements NetconfSessionListener<NetconfServerSession> {
 
     static final Logger logger = LoggerFactory.getLogger(NetconfServerSessionListener.class);
@@ -97,8 +96,9 @@ public class NetconfServerSessionListener implements NetconfSessionListener<Netc
             // TODO: should send generic error or close session?
             logger.error("Unexpected exception", e);
             session.onIncommingRpcFail();
-            throw new RuntimeException("Unable to process incoming message " + netconfMessage, e);
+            throw new IllegalStateException("Unable to process incoming message " + netconfMessage, e);
         } catch (NetconfDocumentedException e) {
+            logger.trace("Error occured while processing mesage {}",e);
             session.onOutgoingRpcError();
             session.onIncommingRpcFail();
             SendErrorExceptionUtil.sendErrorMessage(session, e, netconfMessage);
index d6940a1..d454543 100644 (file)
@@ -64,14 +64,14 @@ public class DefaultCommit extends AbstractNetconfOperation {
 
     @Override
     public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
-        Preconditions.checkArgument(subsequentOperation.isExecutionTermination() == false,
+        Preconditions.checkArgument(!subsequentOperation.isExecutionTermination(),
                 "Subsequent netconf operation expected by %s", this);
 
         if (isCommitWithoutNotification(requestMessage)) {
             logger.debug("Skipping commit notification");
         } else {
             // Send commit notification if commit was not issued by persister
-            requestMessage = removePersisterAttributes(requestMessage);
+            removePersisterAttributes(requestMessage);
             Element cfgSnapshot = getConfigSnapshot(operationRouter);
             logger.debug("Config snapshot retrieved successfully {}", cfgSnapshot);
             notificationProducer.sendCommitNotification("ok", cfgSnapshot, cap.getCapabilities());
@@ -90,10 +90,8 @@ public class DefaultCommit extends AbstractNetconfOperation {
         return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1);
     }
 
-    private Document removePersisterAttributes(Document message) {
-        final Element documentElement = message.getDocumentElement();
-        documentElement.removeAttribute(NOTIFY_ATTR);
-        return message;
+    private void removePersisterAttributes(Document message) {
+        message.getDocumentElement().removeAttribute(NOTIFY_ATTR);
     }
 
     private boolean isCommitWithoutNotification(Document message) {
@@ -108,9 +106,9 @@ public class DefaultCommit extends AbstractNetconfOperation {
 
         String attr = xmlElement.getAttribute(NOTIFY_ATTR);
 
-        if (attr == null || attr.equals(""))
+        if (attr == null || attr.equals("")){
             return false;
-        else if (attr.equals(Boolean.toString(false))) {
+        else if (attr.equals(Boolean.toString(false))) {
             logger.debug("Commit operation received with notify=false attribute {}", message);
             return true;
         } else {
index bbd07e4..303047d 100644 (file)
@@ -39,7 +39,7 @@ public class NetconfImplActivator implements BundleActivator {
     private ServiceRegistration<NetconfMonitoringService> regMonitoring;
 
     @Override
-    public void start(final BundleContext context) throws Exception {
+    public void start(final BundleContext context)  {
         InetSocketAddress address = NetconfConfigUtil.extractTCPNetconfAddress(context,
                 "TCP is not configured, netconf not available.", false);
 
@@ -85,7 +85,7 @@ public class NetconfImplActivator implements BundleActivator {
     }
 
     @Override
-    public void stop(final BundleContext context) throws Exception {
+    public void stop(final BundleContext context) {
         logger.info("Shutting down netconf because YangStoreService service was removed");
 
         commitNot.close();
index a7560fa..81fac5f 100644 (file)
@@ -51,7 +51,7 @@ public class NetconfMonitoringServiceImpl implements NetconfMonitoringService, S
     @Override
     public void onSessionUp(NetconfManagementSession session) {
         logger.debug("Session {} up", session);
-        Preconditions.checkState(sessions.contains(session) == false, "Session %s was already added", session);
+        Preconditions.checkState(!sessions.contains(session), "Session %s was already added", session);
         sessions.add(session);
     }
 
index c2ab36f..ff96ad7 100644 (file)
@@ -17,9 +17,9 @@ import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCommit;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultGetSchema;
+import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultNetconfOperation;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultStartExi;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultStopExi;
-import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultNetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
@@ -33,6 +33,7 @@ import org.w3c.dom.Document;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.Map;
+import java.util.NavigableMap;
 import java.util.Set;
 import java.util.TreeMap;
 
@@ -83,7 +84,7 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter {
         for (NetconfOperationService netconfOperationService : netconfOperationServiceSnapshot.getServices()) {
             final Set<NetconfOperation> netOpsFromService = netconfOperationService.getNetconfOperations();
             for (NetconfOperation netconfOperation : netOpsFromService) {
-                Preconditions.checkState(result.contains(netconfOperation) == false,
+                Preconditions.checkState(!result.contains(netconfOperation),
                         "Netconf operation %s already present", netconfOperation);
                 result.add(netconfOperation);
             }
@@ -97,9 +98,10 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter {
         Preconditions.checkNotNull(allNetconfOperations, "Operation router was not initialized properly");
 
         NetconfOperationExecution netconfOperationExecution;
-        String messageAsString = XmlUtil.toString(message);
 
+        String messageAsString = "";
         try {
+            messageAsString = XmlUtil.toString(message);
             netconfOperationExecution = getNetconfOperationWithHighestPriority(message, session);
         } catch (IllegalArgumentException | IllegalStateException e) {
             logger.warn("Unable to handle rpc {} on session {}", messageAsString, session, e);
@@ -155,7 +157,7 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter {
     private NetconfOperationExecution getNetconfOperationWithHighestPriority(
             Document message, NetconfServerSession session) throws NetconfDocumentedException {
 
-        TreeMap<HandlingPriority, NetconfOperation> sortedByPriority = getSortedNetconfOperationsWithCanHandle(
+        NavigableMap<HandlingPriority, NetconfOperation> sortedByPriority = getSortedNetconfOperationsWithCanHandle(
                 message, session);
 
         Preconditions.checkArgument(sortedByPriority.isEmpty() == false,
@@ -174,9 +176,9 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter {
             if (netconfOperation instanceof DefaultNetconfOperation) {
                 ((DefaultNetconfOperation) netconfOperation).setNetconfSession(session);
             }
-            if (handlingPriority.equals(HandlingPriority.CANNOT_HANDLE) == false) {
+            if (!handlingPriority.equals(HandlingPriority.CANNOT_HANDLE)) {
 
-                Preconditions.checkState(sortedPriority.containsKey(handlingPriority) == false,
+                Preconditions.checkState(!sortedPriority.containsKey(handlingPriority),
                         "Multiple %s available to handle message %s with priority %s",
                         NetconfOperation.class.getName(), message, handlingPriority);
                 sortedPriority.put(handlingPriority, netconfOperation);
@@ -220,7 +222,7 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter {
         }
 
         public static NetconfOperationExecution createExecutionChain(
-                TreeMap<HandlingPriority, NetconfOperation> sortedByPriority, HandlingPriority handlingPriority) {
+                NavigableMap<HandlingPriority, NetconfOperation> sortedByPriority, HandlingPriority handlingPriority) {
             NetconfOperation netconfOperation = sortedByPriority.get(handlingPriority);
             HandlingPriority subsequentHandlingPriority = sortedByPriority.lowerKey(handlingPriority);
 
index 92caea1..8d9e839 100644 (file)
@@ -17,12 +17,12 @@ import org.junit.Test;
 import org.mockito.Mock;
 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
 import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.controller.netconf.client.test.TestingNetconfClient;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
+import org.opendaylight.controller.netconf.client.test.TestingNetconfClient;
 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
+import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
index 05122be..c08db90 100644 (file)
@@ -11,7 +11,7 @@ package org.opendaylight.controller.netconf.mapping.api;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 
-public class HandlingPriority implements Comparable<HandlingPriority> {
+public final class HandlingPriority implements Comparable<HandlingPriority> {
 
     public static final HandlingPriority CANNOT_HANDLE = new HandlingPriority();
     public static final HandlingPriority HANDLE_WITH_DEFAULT_PRIORITY = new HandlingPriority(Integer.MIN_VALUE);
@@ -51,34 +51,42 @@ public class HandlingPriority implements Comparable<HandlingPriority> {
 
     @Override
     public int compareTo(HandlingPriority o) {
-        if (this == o)
+        if (this == o){
             return 0;
-        if (this == CANNOT_HANDLE)
+        }
+        if (this.equals(CANNOT_HANDLE)){
             return -1;
-        if (o == CANNOT_HANDLE)
+        }
+        if (o.equals(CANNOT_HANDLE)){
             return 1;
+        }
 
-        if (priority > o.priority)
+        if (priority > o.priority){
             return 1;
-        if (priority == o.priority)
+        }
+        if (priority.equals(o.priority)){
             return 0;
-        if (priority < o.priority)
+        }
+        if (priority < o.priority){
             return -1;
-
+        }
         throw new IllegalStateException("Unexpected state");
     }
 
     @Override
     public boolean equals(Object o) {
-        if (this == o)
+        if (this == o){
             return true;
-        if (!(o instanceof HandlingPriority))
+        }
+        if (!(o instanceof HandlingPriority)){
             return false;
+        }
 
         HandlingPriority that = (HandlingPriority) o;
 
-        if (priority != null ? !priority.equals(that.priority) : that.priority != null)
+        if (priority != null ? !priority.equals(that.priority) : that.priority != null){
             return false;
+        }
 
         return true;
     }
index 6449c3e..c277e20 100644 (file)
@@ -7,7 +7,6 @@
  */
 package org.opendaylight.controller.netconf.monitoring;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.Maps;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
@@ -63,8 +62,12 @@ public class Get extends AbstractNetconfOperation {
     @Override
     public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation)
             throws NetconfDocumentedException {
-        Preconditions.checkArgument(subsequentOperation.isExecutionTermination() == false,
-                "Subsequent netconf operation expected by %s", this);
+        if (subsequentOperation.isExecutionTermination()){
+            throw new NetconfDocumentedException(String.format("Subsequent netconf operation expected by %s", this),
+                    NetconfDocumentedException.ErrorType.application,
+                    NetconfDocumentedException.ErrorTag.operation_failed,
+                    NetconfDocumentedException.ErrorSeverity.error);
+        }
 
         try {
             Document innerResult = subsequentOperation.execute(requestMessage);
index 200cd34..d14464d 100644 (file)
@@ -7,8 +7,11 @@
  */
 package org.opendaylight.controller.netconf.monitoring;
 
-public class MonitoringConstants {
+public final class MonitoringConstants {
 
+    private MonitoringConstants(){
+        // not called - private constructor for utility class
+    }
     public static final String MODULE_NAME = "ietf-netconf-monitoring";
     public static final String MODULE_REVISION = "2010-10-04";
 
index de04484..14c4735 100644 (file)
@@ -21,14 +21,14 @@ public class NetconfMonitoringActivator implements BundleActivator {
     private NetconfMonitoringServiceTracker monitor;
 
     @Override
-    public void start(final BundleContext context) throws Exception {
+    public void start(final BundleContext context)  {
         monitor = new NetconfMonitoringServiceTracker(context);
         monitor.open();
 
     }
 
     @Override
-    public void stop(final BundleContext context) throws Exception {
+    public void stop(final BundleContext context) {
         if(monitor!=null) {
             try {
                 monitor.close();
index a42bc09..731aad6 100644 (file)
@@ -7,30 +7,20 @@
 */
 package org.opendaylight.controller.netconf.monitoring.osgi;
 
-import java.io.File;
-import java.io.IOException;
-import java.net.URL;
-import java.util.HashSet;
+import com.google.common.base.Optional;
+import com.google.common.collect.Sets;
 import java.util.List;
 import java.util.Set;
-
 import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
 import org.opendaylight.controller.netconf.mapping.api.Capability;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
 import org.opendaylight.controller.netconf.monitoring.Get;
 import org.opendaylight.controller.netconf.monitoring.MonitoringConstants;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
-
-import com.google.common.base.Charsets;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Sets;
-import com.google.common.io.Files;
 
 public class NetconfMonitoringOperationService implements NetconfOperationService {
 
-    public static final HashSet<Capability> CAPABILITIES = Sets.<Capability>newHashSet(new Capability() {
+    public static final Set<Capability> CAPABILITIES = Sets.<Capability>newHashSet(new Capability() {
 
         @Override
         public String getCapabilityUri() {
@@ -69,18 +59,6 @@ public class NetconfMonitoringOperationService implements NetconfOperationServic
         this.monitor = monitor;
     }
 
-    private static String readSchema() {
-        String schemaLocation = "/META-INF/yang/ietf-netconf-monitoring.yang";
-        URL resource = Schemas.class.getClassLoader().getResource(schemaLocation);
-        Preconditions.checkNotNull(resource, "Unable to read schema content from %s", schemaLocation);
-        File file = new File(resource.getFile());
-        try {
-            return Files.toString(file, Charsets.UTF_8);
-        } catch (IOException e) {
-            throw new RuntimeException("Unable to load schema from " + schemaLocation, e);
-        }
-    }
-
     @Override
     public Set<Capability> getCapabilities() {
         return CAPABILITIES;
index c2d0679..51054dd 100644 (file)
@@ -20,7 +20,7 @@ import java.net.ServerSocket;
 import java.util.concurrent.atomic.AtomicLong;
 
 @ThreadSafe
-public class NetconfSSHServer implements Runnable {
+public final class NetconfSSHServer implements Runnable {
 
     private ServerSocket ss = null;
     private static final Logger logger =  LoggerFactory.getLogger(NetconfSSHServer.class);
@@ -29,12 +29,12 @@ public class NetconfSSHServer implements Runnable {
     private final AuthProvider authProvider;
     private boolean up = false;
 
-    private NetconfSSHServer(int serverPort,InetSocketAddress clientAddress, AuthProvider authProvider) throws Exception{
+    private NetconfSSHServer(int serverPort,InetSocketAddress clientAddress, AuthProvider authProvider) throws IllegalStateException, IOException {
 
         logger.trace("Creating SSH server socket on port {}",serverPort);
         this.ss = new ServerSocket(serverPort);
         if (!ss.isBound()){
-            throw new Exception("Socket can't be bound to requested port :"+serverPort);
+            throw new IllegalStateException("Socket can't be bound to requested port :"+serverPort);
         }
         logger.trace("Server socket created.");
         this.clientAddress = clientAddress;
@@ -42,11 +42,11 @@ public class NetconfSSHServer implements Runnable {
         this.up = true;
     }
 
-    public static NetconfSSHServer start(int serverPort, InetSocketAddress clientAddress,AuthProvider authProvider) throws Exception {
+    public static NetconfSSHServer start(int serverPort, InetSocketAddress clientAddress,AuthProvider authProvider) throws IllegalStateException, IOException {
         return new NetconfSSHServer(serverPort, clientAddress,authProvider);
     }
 
-    public void stop() throws Exception {
+    public void stop() throws IOException {
         up = false;
         logger.trace("Closing SSH server socket.");
         ss.close();
index 2d38048..6ddc8eb 100644 (file)
@@ -38,9 +38,9 @@ public class AuthProvider implements AuthProviderInterface {
     }
 
     @Override
-    public boolean authenticated(String username, String password) throws Exception {
+    public boolean authenticated(String username, String password) {
         if (AuthProvider.um == null) {
-            throw new Exception("No usermanager service available.");
+            throw new IllegalStateException("No usermanager service available.");
         }
         AuthResultEnum authResult = AuthProvider.um.authenticate(username, password);
         return authResult.equals(AuthResultEnum.AUTH_ACCEPT) || authResult.equals(AuthResultEnum.AUTH_ACCEPT_LOC);
index 8e40578..fad0f79 100644 (file)
@@ -12,7 +12,7 @@ import org.opendaylight.controller.usermanager.IUserManager;
 
 public interface AuthProviderInterface {
 
-    public boolean authenticated(String username, String password) throws Exception;
+    public boolean authenticated(String username, String password) throws IllegalStateException;
     public char[] getPEMAsCharArray() throws Exception;
     public void removeUserManagerService();
     public void addUserManagerService(IUserManager userManagerService);
index 112bf67..5b88030 100644 (file)
@@ -45,7 +45,7 @@ public class NetconfSSHActivator implements BundleActivator{
     private IUserManager iUserManager;
     private BundleContext context = null;
 
-    ServiceTrackerCustomizer<IUserManager, IUserManager> customizer = new ServiceTrackerCustomizer<IUserManager, IUserManager>(){
+    private ServiceTrackerCustomizer<IUserManager, IUserManager> customizer = new ServiceTrackerCustomizer<IUserManager, IUserManager>(){
         @Override
         public IUserManager addingService(ServiceReference<IUserManager> reference) {
             logger.trace("Service {} added, let there be SSH bridge.", reference);
@@ -72,19 +72,19 @@ public class NetconfSSHActivator implements BundleActivator{
 
 
     @Override
-    public void start(BundleContext context) throws Exception {
+    public void start(BundleContext context)  {
         this.context = context;
         listenForManagerService();
     }
 
     @Override
-    public void stop(BundleContext context) throws Exception {
+    public void stop(BundleContext context) throws IOException {
         if (server != null){
             server.stop();
             logger.trace("Netconf SSH bridge is down ...");
         }
     }
-    private void startSSHServer() throws Exception {
+    private void startSSHServer() throws IllegalStateException, IOException {
         logger.trace("Starting netconf SSH  bridge.");
         Optional<InetSocketAddress> sshSocketAddressOptional = NetconfConfigUtil.extractSSHNetconfAddress(context, EXCEPTION_MESSAGE);
         InetSocketAddress tcpSocketAddress = NetconfConfigUtil.extractTCPNetconfAddress(context,
@@ -94,14 +94,18 @@ public class NetconfSSHActivator implements BundleActivator{
             String path = NetconfConfigUtil.getPrivateKeyPath(context);
             path = path.replace("\\", "/");  // FIXME: shouldn't this convert lines to system dependent path separator?
             if (path.equals("")){
-                throw new Exception("Missing netconf.ssh.pk.path key in configuration file.");
+                throw new IllegalStateException("Missing netconf.ssh.pk.path key in configuration file.");
             }
 
             File privateKeyFile = new File(path);
-            String privateKeyPEMString;
+            String privateKeyPEMString = null;
             if (privateKeyFile.exists() == false) {
                 // generate & save to file
-                privateKeyPEMString = PEMGenerator.generateTo(privateKeyFile);
+                try {
+                    privateKeyPEMString = PEMGenerator.generateTo(privateKeyFile);
+                } catch (Exception e) {
+                    logger.error("Exception occured while generating PEM string {}",e);
+                }
             } else {
                 // read from file
                 try (FileInputStream fis = new FileInputStream(path)) {
@@ -111,7 +115,12 @@ public class NetconfSSHActivator implements BundleActivator{
                     throw new IllegalStateException("Error reading RSA key from file " + path);
                 }
             }
-            AuthProvider authProvider = new AuthProvider(iUserManager, privateKeyPEMString);
+            AuthProvider authProvider = null;
+            try {
+                authProvider = new AuthProvider(iUserManager, privateKeyPEMString);
+            } catch (Exception e) {
+                logger.error("Error instantiating AuthProvider {}",e);
+            }
             this.server = NetconfSSHServer.start(sshSocketAddressOptional.get().getPort(),tcpSocketAddress,authProvider);
 
             Thread serverThread = new  Thread(server,"netconf SSH server thread");
@@ -120,10 +129,10 @@ public class NetconfSSHActivator implements BundleActivator{
             logger.trace("Netconf SSH  bridge up and running.");
         } else {
             logger.trace("No valid connection configuration for SSH bridge found.");
-            throw new Exception("No valid connection configuration for SSH bridge found.");
+            throw new IllegalStateException("No valid connection configuration for SSH bridge found.");
         }
     }
-    private void onUserManagerFound(IUserManager userManager) throws Exception{
+    private void onUserManagerFound(IUserManager userManager) throws IOException {
         if (server!=null && server.isUp()){
            server.addUserManagerService(userManager);
         } else {
index ce26910..d6566c8 100644 (file)
@@ -112,18 +112,18 @@ public class SocketThread implements Runnable, ServerAuthenticationCallback, Ser
                                     if (netconf_ssh_input != null) {
                                         netconf_ssh_input.join();
                                     }
-                                } catch (InterruptedException e) {
+                                } catch (InterruptedException e1) {
                                     Thread.currentThread().interrupt();
-                                    logger.error("netconf_ssh_input join error ", e);
+                                    logger.error("netconf_ssh_input join error ", e1);
                                 }
 
                                 try {
                                     if (netconf_ssh_output != null) {
                                         netconf_ssh_output.join();
                                     }
-                                } catch (InterruptedException e) {
+                                } catch (InterruptedException e2) {
                                     Thread.currentThread().interrupt();
-                                    logger.error("netconf_ssh_output join error ", e);
+                                    logger.error("netconf_ssh_output join error ", e2);
                                 }
                             }
                         } else {
index ccc80a7..8f4590c 100644 (file)
@@ -40,7 +40,7 @@ public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf
     }
 
     @Override
-    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
+    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out)  {
         while (msg.readableBytes() > chunkSize) {
             ByteBuf chunk = Unpooled.buffer(chunkSize);
             chunk.writeBytes(createChunkHeader(chunkSize));
index a3efe8a..8df62a6 100644 (file)
@@ -16,7 +16,7 @@ import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants
 
 public class EOMFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
     @Override
-    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
+    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) {
         out.writeBytes(msg);
         out.writeBytes(NetconfMessageConstants.END_OF_MESSAGE);
     }
index 1f7a32d..bac83e4 100644 (file)
@@ -15,11 +15,13 @@ import org.slf4j.LoggerFactory;
 import io.netty.buffer.ByteBuf;
 import io.netty.handler.codec.MessageToByteEncoder;
 
-public class FramingMechanismHandlerFactory {
+public final class FramingMechanismHandlerFactory {
 
     private static final Logger logger = LoggerFactory.getLogger(FramingMechanismHandlerFactory.class);
 
-    private FramingMechanismHandlerFactory() {}
+    private FramingMechanismHandlerFactory() {
+        // not called - private constructor for utility class
+    }
 
     public static MessageToByteEncoder<ByteBuf> createHandler(FramingMechanism framingMechanism) {
         logger.debug("{} framing mechanism was selected.", framingMechanism);
index 219e92c..9f9f419 100644 (file)
@@ -21,6 +21,8 @@ import io.netty.handler.codec.ByteToMessageDecoder;
 
 public class NetconfChunkAggregator extends ByteToMessageDecoder {
     private final static Logger logger = LoggerFactory.getLogger(NetconfChunkAggregator.class);
+    private static final String GOT_PARAM_WHILE_WAITING_FOR_PARAM = "Got byte {} while waiting for {}";
+    private static final String GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM = "Got byte {} while waiting for {}-{}";
     public static final int DEFAULT_MAXIMUM_CHUNK_SIZE = 16 * 1024 * 1024;
 
     private static enum State {
@@ -40,17 +42,35 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder {
     private long chunkSize;
     private CompositeByteBuf chunk;
 
+    private void checkNewLine(byte b,String errorMessage){
+        if (b != '\n') {
+            logger.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM, b, (byte)'\n');
+            throw new IllegalStateException(errorMessage);
+        }
+    }
+
+    private void checkHash(byte b,String errorMessage){
+        if (b != '#') {
+            logger.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM, b, (byte)'#');
+            throw new IllegalStateException(errorMessage);
+        }
+    }
+
+    private void checkChunkSize(){
+        if (chunkSize > maxChunkSize) {
+            logger.debug("Parsed chunk size {}, maximum allowed is {}", chunkSize, maxChunkSize);
+            throw new IllegalStateException("Maximum chunk size exceeded");
+        }
+
+    }
     @Override
-    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
+    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws IllegalStateException {
         while (in.isReadable()) {
             switch (state) {
             case HEADER_ONE:
             {
                 final byte b = in.readByte();
-                if (b != '\n') {
-                    logger.debug("Got byte {} while waiting for {}", b, (byte)'\n');
-                    throw new IllegalStateException("Malformed chunk header encountered (byte 0)");
-                }
+                checkNewLine(b, "Malformed chunk header encountered (byte 0)");
 
                 state = State.HEADER_TWO;
 
@@ -60,10 +80,7 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder {
             case HEADER_TWO:
             {
                 final byte b = in.readByte();
-                if (b != '#') {
-                    logger.debug("Got byte {} while waiting for {}", b, (byte)'#');
-                    throw new IllegalStateException("Malformed chunk header encountered (byte 1)");
-                }
+                checkHash(b, "Malformed chunk header encountered (byte 1)");
 
                 state = State.HEADER_LENGTH_FIRST;
                 break;
@@ -84,17 +101,13 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder {
                 }
 
                 if (b < '0' || b > '9') {
-                    logger.debug("Got byte {} while waiting for {}-{}", b, (byte)'0', (byte)'9');
+                    logger.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, b, (byte)'0', (byte)'9');
                     throw new IllegalStateException("Invalid chunk size encountered");
                 }
 
                 chunkSize *= 10;
                 chunkSize += b - '0';
-
-                if (chunkSize > maxChunkSize) {
-                    logger.debug("Parsed chunk size {}, maximum allowed is {}", chunkSize, maxChunkSize);
-                    throw new IllegalStateException("Maximum chunk size exceeded");
-                }
+                checkChunkSize();
                 break;
             }
             case DATA:
@@ -109,18 +122,13 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder {
                     in.discardReadBytes();
                     return;
                 }
-
                 aggregateChunks(in.readBytes((int) chunkSize));
                 state = State.FOOTER_ONE;
                 break;
             case FOOTER_ONE:
             {
                 final byte b = in.readByte();
-                if (b != '\n') {
-                    logger.debug("Got byte {} while waiting for {}", b, (byte)'\n');
-                    throw new IllegalStateException("Malformed chunk footer encountered (byte 0)");
-                }
-
+                checkNewLine(b,"Malformed chunk footer encountered (byte 0)");
                 state = State.FOOTER_TWO;
                 chunkSize = 0;
                 break;
@@ -128,12 +136,7 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder {
             case FOOTER_TWO:
             {
                 final byte b = in.readByte();
-
-                if (b != '#') {
-                    logger.debug("Got byte {} while waiting for {}", b, (byte)'#');
-                    throw new IllegalStateException("Malformed chunk footer encountered (byte 1)");
-                }
-
+                checkHash(b,"Malformed chunk footer encountered (byte 1)");
                 state = State.FOOTER_THREE;
                 break;
             }
@@ -144,28 +147,14 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder {
                 // In this state, either header-of-new-chunk or message-end is expected
                 // Depends on the next character
 
-                if (isHeaderLengthFirst(b)) {
-                    // Extract header length#1 from new chunk
-                    chunkSize = processHeaderLengthFirst(b);
-                    // Proceed with next chunk processing
-                    state = State.HEADER_LENGTH_OTHER;
-                } else if (b == '#') {
-                    state = State.FOOTER_FOUR;
-                } else {
-                    logger.debug("Got byte {} while waiting for {} or {}-{}", b, (byte) '#', (byte) '1', (byte) '9');
-                    throw new IllegalStateException("Malformed chunk footer encountered (byte 2)");
-                }
+                extractNewChunkOrMessageEnd(b);
 
                 break;
             }
             case FOOTER_FOUR:
             {
                 final byte b = in.readByte();
-                if (b != '\n') {
-                    logger.debug("Got byte {} while waiting for {}", b, (byte)'\n');
-                    throw new IllegalStateException("Malformed chunk footer encountered (byte 3)");
-                }
-
+                checkNewLine(b,"Malformed chunk footer encountered (byte 3)");
                 state = State.HEADER_ONE;
                 out.add(chunk);
                 chunk = null;
@@ -177,6 +166,20 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder {
         in.discardReadBytes();
     }
 
+    private void extractNewChunkOrMessageEnd(byte b) {
+        if (isHeaderLengthFirst(b)) {
+            // Extract header length#1 from new chunk
+            chunkSize = processHeaderLengthFirst(b);
+            // Proceed with next chunk processing
+            state = State.HEADER_LENGTH_OTHER;
+        } else if (b == '#') {
+            state = State.FOOTER_FOUR;
+        } else {
+            logger.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, b, (byte) '#', (byte) '1', (byte) '9');
+            throw new IllegalStateException("Malformed chunk footer encountered (byte 2)");
+        }
+    }
+
     private void initChunk() {
         chunk = Unpooled.compositeBuffer();
     }
@@ -189,8 +192,8 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder {
     }
 
     private static int processHeaderLengthFirst(byte b) {
-        if (isHeaderLengthFirst(b) == false) {
-            logger.debug("Got byte {} while waiting for {}-{}", b, (byte)'1', (byte)'9');
+        if (!isHeaderLengthFirst(b)) {
+            logger.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, b, (byte)'1', (byte)'9');
             throw new IllegalStateException("Invalid chunk size encountered (byte 0)");
         }
 
index 9435e6f..8b1bb36 100644 (file)
@@ -24,7 +24,7 @@ public class NetconfEOMAggregator extends ByteToMessageDecoder {
     private final static Logger logger = LoggerFactory.getLogger(NetconfEOMAggregator.class);
 
     @Override
-    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
+    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
         int index = indexOfSequence(in, NetconfMessageConstants.END_OF_MESSAGE);
         if (index == -1) {
             logger.debug("Message is not complete, read again.");
index c4808e0..b930b65 100644 (file)
@@ -13,10 +13,12 @@ import io.netty.channel.ChannelHandlerContext;
 import io.netty.handler.codec.ByteToMessageDecoder;
 
 import java.io.ByteArrayInputStream;
+import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.util.Arrays;
 import java.util.List;
 
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
@@ -28,6 +30,7 @@ import org.w3c.dom.Document;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Charsets;
 import com.google.common.collect.ImmutableList;
+import org.xml.sax.SAXException;
 
 /**
  * Customized NetconfXMLToMessageDecoder that reads additional header with
@@ -48,7 +51,7 @@ public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder
 
     @Override
     @VisibleForTesting
-    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
+    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws IOException, SAXException, NetconfDocumentedException {
         if (in.readableBytes() == 0) {
             LOG.debug("No more content in incoming buffer.");
             return;
index 06a4dc7..89f76f3 100644 (file)
@@ -13,6 +13,7 @@ import io.netty.buffer.ByteBufUtil;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.handler.codec.ByteToMessageDecoder;
 
+import java.io.IOException;
 import java.util.List;
 
 import org.opendaylight.controller.netconf.api.NetconfMessage;
@@ -21,13 +22,14 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import com.google.common.annotations.VisibleForTesting;
+import org.xml.sax.SAXException;
 
 public final class NetconfXMLToMessageDecoder extends ByteToMessageDecoder {
     private static final Logger LOG = LoggerFactory.getLogger(NetconfXMLToMessageDecoder.class);
 
     @Override
     @VisibleForTesting
-    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
+    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws IOException, SAXException {
         if (in.readableBytes() != 0) {
             LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
             out.add(new NetconfMessage(XmlUtil.readXmlToDocument(new ByteBufInputStream(in))));
index 4aa274c..c482e77 100644 (file)
@@ -29,7 +29,7 @@ public class LoginPassword extends AuthenticationHandler {
     public void authenticate(Connection connection) throws IOException {
         boolean isAuthenticated = connection.authenticateWithPassword(username, password);
 
-        if (isAuthenticated == false) {
+        if (!isAuthenticated) {
             throw new IOException("Authentication failed.");
         }
     }
index 7beee64..50f4405 100644 (file)
@@ -58,8 +58,9 @@ public class SshClient {
     }
 
     public void close() {
-        for (SshSession session : openSessions.values())
+        for (SshSession session : openSessions.values()){
             closeSession(session);
+        }
 
         openSessions.clear();
 
index 6350dd1..244bcc0 100644 (file)
@@ -64,7 +64,7 @@ public class SshClientAdapter implements Runnable {
                 }
             }
 
-            while (stopRequested.get() == false) {
+            while (!stopRequested.get()) {
                 byte[] readBuff = new byte[BUFFER_SIZE];
                 int c = stdOut.read(readBuff);
                 if (c == -1) {
@@ -82,7 +82,7 @@ public class SshClientAdapter implements Runnable {
             // Netty closed connection prematurely.
             // Just pass and move on.
         } catch (Exception e) {
-            throw new RuntimeException(e);
+            throw new IllegalStateException(e);
         } finally {
             sshClient.close();
 
index 313ea93..b8f1369 100644 (file)
@@ -12,7 +12,6 @@ import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelInboundHandler;
-
 import java.io.IOException;
 import java.io.InputStream;
 
@@ -60,7 +59,7 @@ public class ChannelInputStream extends InputStream implements ChannelInboundHan
                     lock.wait();
                 } catch (InterruptedException e) {
                     Thread.currentThread().interrupt();
-                    throw new RuntimeException(e);
+                    throw new IllegalStateException(e);
                 }
             }
             return this.bb.readByte() & 0xFF;
index 8bd6b88..5c2770a 100644 (file)
@@ -10,7 +10,9 @@ package org.opendaylight.controller.netconf.util.messages;
 
 import com.google.common.base.Charsets;
 
-public class NetconfMessageConstants {
+public final class NetconfMessageConstants {
+
+    private NetconfMessageConstants(){}
     /**
      * The NETCONF 1.0 old-style message separator. This is framing mechanism
      * is used by default.
@@ -26,4 +28,5 @@ public class NetconfMessageConstants {
     public static final int MAX_HEADER_LENGTH = 13;
 
     public static final byte[] END_OF_CHUNK = "\n##\n".getBytes(Charsets.UTF_8);
+
 }
index de2d6d7..5b9707f 100644 (file)
@@ -112,7 +112,7 @@ public final class SendErrorExceptionUtil {
                 XPathConstants.NODE);
         errorSeverityNode.setTextContent(sendErrorException.getErrorSeverity().getTagValue());
 
-        if (sendErrorException.getErrorInfo() != null && sendErrorException.getErrorInfo().isEmpty() == false) {
+        if (sendErrorException.getErrorInfo() != null && !sendErrorException.getErrorInfo().isEmpty()) {
             /*
              * <error-info> <bad-attribute>message-id</bad-attribute>
              * <bad-element>rpc</bad-element> </error-info>
index 80eaa26..b23a2d6 100644 (file)
@@ -54,7 +54,7 @@ public final class NetconfConfigUtil {
 
         Optional<InetSocketAddress> inetSocketAddressOptional = extractSomeNetconfAddress(context, InfixProp.tcp, exceptionMessageIfNotFound, forClient);
 
-        if (inetSocketAddressOptional.isPresent() == false) {
+        if (!inetSocketAddressOptional.isPresent()) {
             throw new IllegalStateException("Netconf tcp address not found." + exceptionMessageIfNotFound);
         }
         InetSocketAddress inetSocketAddress = inetSocketAddressOptional.get();
index 17ea374..66603fb 100644 (file)
@@ -180,7 +180,7 @@ public final class XmlElement {
         final List<XmlElement> result = new ArrayList<>();
         for (int i = 0; i < childNodes.getLength(); i++) {
             Node item = childNodes.item(i);
-            if (item instanceof Element == false) {
+            if (!(item instanceof Element)) {
                 continue;
             }
             if (strat.accept((Element) item)) {
@@ -400,7 +400,7 @@ public final class XmlElement {
         } else {
             prefix = "";
         }
-        if (namespaces.containsKey(prefix) == false) {
+        if (!namespaces.containsKey(prefix)) {
             throw new IllegalArgumentException("Cannot find namespace for " + XmlUtil.toString(element) + ". Prefix from content is "
                     + prefix + ". Found namespaces " + namespaces);
         }
index d890742..1f81117 100644 (file)
@@ -8,12 +8,12 @@
 
 package org.opendaylight.controller.netconf.util.xml;
 
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringWriter;
+import com.google.common.base.Charsets;
+import com.google.common.base.Optional;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.xml.sax.SAXException;
 
 import javax.xml.XMLConstants;
 import javax.xml.namespace.QName;
@@ -23,7 +23,6 @@ import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.transform.OutputKeys;
 import javax.xml.transform.Source;
 import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
 import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.TransformerFactoryConfigurationError;
 import javax.xml.transform.dom.DOMSource;
@@ -33,14 +32,12 @@ import javax.xml.validation.Schema;
 import javax.xml.validation.SchemaFactory;
 import javax.xml.xpath.XPathExpression;
 import javax.xml.xpath.XPathExpressionException;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.xml.sax.SAXException;
-
-import com.google.common.base.Charsets;
-import com.google.common.base.Optional;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
 
 public final class XmlUtil {
 
@@ -81,7 +78,7 @@ public final class XmlUtil {
         try {
             dBuilder = BUILDERFACTORY.newDocumentBuilder();
         } catch (ParserConfigurationException e) {
-            throw new RuntimeException("Failed to parse XML document", e);
+            throw new IllegalStateException("Failed to parse XML document", e);
         }
         Document doc = dBuilder.parse(xmlContent);
 
@@ -96,10 +93,9 @@ public final class XmlUtil {
     public static Document newDocument() {
         try {
             DocumentBuilder builder = BUILDERFACTORY.newDocumentBuilder();
-            Document document = builder.newDocument();
-            return document;
+            return builder.newDocument();
         } catch (ParserConfigurationException e) {
-            throw new RuntimeException("Failed to create document", e);
+            throw new IllegalStateException("Failed to create document", e);
         }
     }
 
@@ -153,8 +149,8 @@ public final class XmlUtil {
             transformer.transform(source, result);
 
             return result.getWriter().toString();
-        } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
-            throw new RuntimeException("Unable to serialize xml element " + xml, e);
+        } catch (Exception |  TransformerFactoryConfigurationError e) {
+            throw new IllegalStateException("Unable to serialize xml element " + xml, e);
         }
     }
 

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.