Bug 460 - Fix warning throughout netconf subsystem 99/5599/14
authorMartin Bobak <mbobak@cisco.com>
Mon, 10 Mar 2014 16:11:35 +0000 (17:11 +0100)
committerMartin Bobak <mbobak@cisco.com>
Mon, 28 Apr 2014 07:32:43 +0000 (09:32 +0200)
Change-Id: I461a7bab47ef67c13c6fd5864d8938cdd47c3c8b
Signed-off-by: Martin Bobak <mbobak@cisco.com>
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 1d4139f885152a0f9430ddf541f2c036bb6450ab..156fa580ce0c2403c78451d73702237f46f5ad79 100644 (file)
@@ -18,4 +18,7 @@ public interface PropertiesProvider {
      * @return prefix + key as used in getProperty method.
      */
     String getFullKeyForReporting(String key);
+
+    String getPrefix();
+    String getPropertyWithoutPrefix(String fullKey);
 }
index 2df07b114cf54ff327b10e5bdc7b40e859eb8410..3d4757b926f0fad6900d0c673ebd562c2afc9085 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 330f804e0eae6caa252ec5de740a87cffa2f5078..ae6ae675840dcd52c9379da9e502d4528a3cac52 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 b57d1dc1d4347b0ff4cf436a8c2149c3ca2e974d..07012263e17b8a34232d83c34e8813873cd07c11 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 74a05496df7e7f31c3c78cda03b3e813cfaefdfa..3baee6c132129d576b6df7958314dda14176ade8 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 9680bffd6b42d0391d637f52109f172206918aad..6f9118bf921d134547079a38f73cd55592e342de 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 54d24a4cec3823c0a07e1bfaf5e36b2c69815d0d..c08be06c9f619bfc48ff144f523f64535cb8a605 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 dbc1b48d4f9abebe5fc89c306f65b68fcee924d2..dcc2fa15439b01ecd15eca5144f15eaa3a77086b 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 5f44c16dcaefb754f7732143c41f59968cea9fda..bf9eee7f267fd5ded0f73f431443eecb9fa76183 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 61db74feb570bc1f0c20e3ee24a938cce0d849ea..61ea76bbfeb9504f456132ba7cfebd67bcc6e508 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 58f91a7deec8c9ce7522f426bb4428b2dee3d691..8e7ba708c6cea71ba46400f99fb765a2113bf762 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 30436bb42f077c72de371e45fc5453849a40f9bc..54ffe08cfbd455f19e2d8996588e19ce7e706cc0 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 368e1f12a642e54dc90ac8231818619a0de96815..594953e569e6c0c2c5531a8100e5e7f106f2d114 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 506d7d61c347016ef76a6601500ed773762dafb0..01844f27d4cb8609d8df9b4916f7fbe69a47eac2 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 83e8086eef2507b648d918cf4592d9d7c553c1b6..b827a5b03965d7f7471731a646b80e44ee835266 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 d92b7c432df344ae989f3fff8acbe94876ea512f..7dbf4f41bc6fc16eecf5b92bde33130b8261e910 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 81a1e535989192474d34fa49fa0f99d07c71b2f4..1754fc7e0945d4f43b69d5280ce9791ae7c16c0f 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 adee8bec58086a02a92835deea84c578a8c94cd6..f0d7960085f21bd5e4a220797d648521c93f51d8 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 0bb274ae413c2fbd4c4712cd31ec8b25e2442c5f..599d81396e6fea26dbe5c83778e90592f46e15e3 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 e8e97f990f44cd45608fb8df92e042437351e319..83ebf65d7fb71c1e5791dcfac416e4097a94f675 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 82c8c1ec6b537f2ca25cc585dfe4c795cd2b7350..4a4281a55e04489beb1a8ed9360a457ec9899dad 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 e1b8ecf17ee50c1a4895d73301025faabd5f88e6..26709dbe6b97e2b8fcb37cde22526053debe51df 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 bc99ecf09a90b480f71b6444776fefc354177559..cdebcfaa34620595134ce868f2ac743e9eabd606 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 051f365086624ce5acf8bf2cb3d52d268044f892..b17842b8e20f50e6aa468f10800dfe43f7d4f6ae 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 8d63bb05d8b8a275dc8984d4ebb2f438772d7ab4..4e07ec8c31e7beb81e369f9c7c68fcac5d65058f 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 b2555f712a0b2bd175d47fc19c482ef5713ddfab..a74afd08122ef026d235f90192207dc121a627d8 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 bb5a67cb9ce9051570b6ea736cc83d5e89cd1977..854f99c5c0522902f1c2f7288c353ba66dfe28aa 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 1da9fabdb38390dd0a153b37f4f30a3560fdd03d..0fe5fad29c1d4ad20e5cb67c3d8c21357e791f46 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 f3d75d07bef7ec9dc33ac1d0a189f9e37d30e50d..a5a625a2d6859a373511a1c22ffc9b98c9df6521 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 8d2d149822011ccc856e934e84271550846b1ed1..1f63555e83d93b57565ec44027114bd801eea0e1 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 f9df71700870d12e7f14e7121c14e088cd5ce474..eb5c018cf3db0af76ced902576543861b732a4f6 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 a081890d398c1c8fd2f349b8e5127b83e5a57cbf..28b14178937aeca68acc76dcebd3370a0f45aaf2 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 8c3b35122c2061af455222b70b464b3471ad6fc5..6a49275f260d7c0d047d3b3642d1886b35458b93 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 4936d1dbcda833b7fb5fdfe904d8b5e1493f6b34..59767fec6e79546595d9a6bf9207e80482b09a94 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 8fc3ee14233b31cf04c7703f2ba4ff65a1b28728..439dea2a80c352252228333cc19b9a66adc7775f 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 cd99ac4d8d672b039fffb3fcdbed0fa62fc4790e..c4217106cee221cc543b405eb6e4423a64437d8f 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 e88863c685ace15c486c9b5c263345a81ace9a44..c5fadb097f2d64f4d8b694e345f98dd71136d1c6 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 428ddb3b740dfbb5e34e62bff86035d0e9464b03..3ea26055f33c79212debc907caa259109f7101a2 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 de6979565e3fe225fc7150dbbe645d4042decdc0..547ffcda3db0941459d4c2163a7fdc9596bc5bb2 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 2f41defac8ff880a9733e21513f6a3dd96d914f5..6b81603dcd01cdffa0ce3d4b5c9486fc66db2b8d 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 0a72547d78454cc242756a5a683045ad2f034fa0..3e5707cf6ddbc29f842d50fe5cde929458604a91 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 b61fcbadc07cd3caaa6582538f734077c79839ba..bc3082ff50f51b4365280e6f37861c7c36cdaaf0 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 dd0e53b1bbb42f8fb2b91fb8b1eb1cc97671aa52..4665c2cc89cf23d9f5efbb876b532b377ef22896 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 11d3e32edf6748fe811a9a25174330afae5b1d28..82e07c1e7b29bd5b8eaffafc6e1a53cdeaa82828 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 5a30fc8352600f524f86224c88ff09a6c5365a68..7790e09ceeb245b926f9c1c4c71fe1f2dde16589 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 0f0b1227a625cd717840f2841dcb4706b270e47c..5cf7f30abcaa5cf356a2faf89635c0cb1ee06f63 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 421870ca3611bb6e35a8e7ddd9ec574d0e62e4ab..3ba92b092ed2f5ccb067a8ee25aae3efd08a4d82 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 09966b8c3bd6c74f29ed93f20cd12e6654ee9a04..7f4f8fccb50740c9a9c990e0f942c11b80a5fa64 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 b8b7fcb47f137f5d422c0239f9159cec3c5ad234..12469f66b7be00d2649f231f8e1471073eaa66bd 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 c6248df41bc133f7754f9c78f0ec2bb15fa69bcb..1069858b4777008a321b7021beb172ca951675df 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 756a38ed940be7e910dc82a90523bbf3cbf48b50..250af688eac0db0a796b2e4dd668f84684949b99 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 1616857949d91c0678e7740ae2b277bfc12b25a0..40a15be70616217d81529b003f899236865d8ac8 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 31a4f080368515c075872173e9ba066c830f5e0e..a0e7974b942951c521305ae4726baa4a5a74d74a 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 d9466ff00b6d6a0d1e9c034d43ad310600407dd3..238661f638afd870d55c7d441fb8bcffe1c1b392 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 b1bf23292875611d40c6875fd1a05bb8d81b328e..e02e27a745a032e1f36414c63e9e93dfd55e41c1 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 {
index 0a084b0ff6fd3989bf4e0e98b72e444ab5da5ce4..8e62a147d25276535b656a4ed606701163de6111 100644 (file)
@@ -13,7 +13,7 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.mon
 
 /**
 **/
-public class LocationBuilder {
+public final class LocationBuilder {
 
     public static Location getDefaultInstance(String defaultValue) {
         return defaultValue.equals("NETCONF") ? new Location(Location.Enumeration.NETCONF) : new Location(new Uri(
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 20da6aa86934a71eb91a4461988d8d1097babba8..c7c723cb27b552fa51b7a7a287f66306649f35ca 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 504e4c994915aeafc5d303fc2a56ab4bcf2722d8..524f0b52b7e22f4dc01317d5c7cf7dbcc1c045a0 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 6a86ecd21f4d81fdfa9db9de1a81d6e28e1d9488..91385bab33e5102659e72c7f42a435f509b5c1fa 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 4461054437ce61ef47fd2eea76a9b23ae15b5ef3..6c7f9d9b2a53cb1308dc83b6eaff6e0feaad2a72 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 b3245fff2b812775803acf59e1c2e53aa875d77e..75be1f8fe01647beeabbcb1101bd5265c7813578 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 d6940a1a453fcaaf14f4e6e30292f8dbc427256d..d4545430b47834ae8604737a50762056fd712526 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 bbd07e42bf515c46dec0a6900bd2105f3140596f..303047df12b6fae6c77e964b702cb23a9ed52b59 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 a7560fadb602cc450f84c71e2f9936cb131cd495..81fac5f12f9c7dc9d3bf40922c19723836c036ce 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 c2ab36f2c68ac8478d89fc14b02b6729e0ccf072..ff96ad779fbc974539ced455494129381bb09635 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 92caea17d5eaea998d5d62ab6682c765287c5329..8d9e839ee706d05ac2d6556f08503ee02fbb117a 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 05122be4d245a8f09b0c566aab90337c28c513af..c08db906df51a00b5dc39d53bb30be252381b3ca 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 6449c3e05fa39a6510e27d59ed69664e243e29b2..c277e20553fb3ed469c9f849d624f795f0acf635 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 200cd344a6617b995065b652efca10a6a2a35791..d14464d66734a3a890af70f8e49d068fbafc4c9a 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 de04484d1388f411577c7b1c2537996f2e625e7d..14c47352a8409d633dca64a01db06759ad79f8f6 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 a42bc09591ba0160d964ebe6f4b4900b91282ff8..731aad6d1a4d7103ca12fc99541482b81a82757b 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 c2d067915516b27efb44bd5a7644f942744a13d2..51054dd938ac8349447e694ea5c2698a7bc6d5c8 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 2d380482ba456afd4beef97c77d7a86d1bf79f14..6ddc8ebb55752dca439e63ee3e70dfa260e79783 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 8e40578a0e47c001676b8fb28809a9cf306364e2..fad0f79a4e7b9eb5d883b3d8086bd046343e4f6d 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 112bf67f69b48d869fede643308dca962c317819..5b8803001ca9a33f71d2cacab990f03891a6891e 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 ce26910b97dd449b10d395933e57cd6deccd52ea..d6566c8ffa69f3e0fd46d6775e8ced177cffd911 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 ccc80a7b71248758cc2ce9a3c00225a0dab3fc49..8f4590cbb112bb6315f0ba0059e8fea417d48c3f 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 a3efe8a16bd0c541971e7a4c0ca172b83144d3d5..8df62a67020c9b05dcac72bb0d589f42bb7a9076 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 1f7a32dc704ca2698112b0e5e9d90c9cdb503a87..bac83e49d3c463548589c48ae367d972ae818d6e 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 219e92c3f14053c805d1ac204132f92d62479948..9f9f4191f7641943fe768712b94c0ec2b3f409b7 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 9435e6ff732cad7904a8fc71caf6ed9ee194225a..8b1bb3601ddd3df4b2b033d4d3f697acab76d210 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 c4808e0868d0f59b1378f5900b5151933edf696e..b930b65b9742625071f6f0618be9461add72a2c7 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 06a4dc7207204d573f5abb2cc28c32318fee891d..89f76f39e5eafed6526388e9305a129d97bf7517 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 4aa274c6df34f2f2e9d4151454c4b84f53a41bdb..c482e77735348833a3eeda204d51698af1f50071 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 7beee649abfe0501e60850fda0db79dd96c7bb86..50f44054c16f9be42a300da8144ec3ce2866ea32 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 6350dd154415b510515f919d94c88d06ecac5314..244bcc0041c963988aa8fc78c712767fc7c643c2 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 313ea932413b63b36c5d20cc6cb1a9570205ab2a..b8f13699ba06d49876c6002fc27f297eceded04c 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 8bd6b8865933d7191a063055834ce3fb98b0bbe4..5c2770a8c1f2387211f4cdcf1a1ef762ef8f11d8 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 de2d6d7e0c354ada3bcf1fb4f1b630b186c34e3c..5b9707f2b52fff9875cd18e63d91ca257b815a0c 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 80eaa26de184ddc29993bd847d1c34b0e7becd09..b23a2d6697b2ab5623431741fb0ecb374cb22411 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 17ea3740fca77cd6124daad71050de6383970dc5..66603fb6c2d60b90cf2e17c277e65420d3c0b8b1 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 d8907424f804f6d93262a38ddf107364a392cca1..1f81117ca383922ff246c9e10af36b708f84b26a 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);
         }
     }