* @return prefix + key as used in getProperty method.
*/
String getFullKeyForReporting(String key);
+
+ String getPrefix();
+ String getPropertyWithoutPrefix(String fullKey);
}
public String getFullKeyForReporting(String key) {
return null;
}
+
+ @Override
+ public String getPrefix() {
+ return null;
+ }
+
+ @Override
+ public String getPropertyWithoutPrefix(String fullKey) {
+ return null;
+ }
}
*
* 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
*/
*
* 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
*/
*
* 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
*/
*
* 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
*/
public abstract class AttributeIfcSwitchStatement<T> {
- protected AttributeIfc lastAttribute;
+ private AttributeIfc lastAttribute;
public T switchAttribute(AttributeIfc attributeIfc) {
return caseJavaUnionAttribute(openType);
} else if(((JavaAttribute)attributeIfc).isIdentityRef()) {
return caseJavaIdentityRefAttribute(openType);
- } else
+ } else {
return caseJavaAttribute(openType);
+ }
} catch (UnknownOpenTypeException e) {
throw getIllegalArgumentException(attributeIfc);
}
throw getIllegalArgumentException(attributeIfc);
}
+ public AttributeIfc getLastAttribute() {
+ return lastAttribute;
+ }
+
protected T caseJavaIdentityRefAttribute(OpenType<?> openType) {
return caseJavaAttribute(openType);
}
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;
}
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;
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),
@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
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();
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);
}
}
revision = date;
}
}
- } else
+ } else {
revision = revisions.keySet().iterator().next();
-
+ }
return QName.create(URI.create(namespace), revision, localName).toString();
}
@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 ");
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);
@Override
public Optional<Map<String, Object>> mapAttribute(Object value) {
- if (value == null)
+ if (value == null){
return Optional.absent();
+ }
Util.checkType(value, CompositeDataSupport.class);
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);
AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = innerStrategies
.get(jmxName);
- Optional<?> mapAttribute = attributeMappingStrategy.mapAttribute(innerValue);
- return mapAttribute;
+ return attributeMappingStrategy.mapAttribute(innerValue);
}
}
@Override
protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseDependencyAttribute(
SimpleType<?> openType) {
- return new ObjectNameAttributeMappingStrategy(openType, dependencyTracker,
+ return new ObjectNameAttributeMappingStrategy(openType,
serviceNameOfDepAttr, namespaceOfDepAttr);
}
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()));
}
@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));
}
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();
@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();
@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);
}
}
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;
}
@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();
}
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++;
}
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);
}
}
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.
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;
}
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;
}
@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();
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);
}
@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();
@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);
}
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;
}
@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();
}
}
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;
}
}
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);
}
}
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);
}
}
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);
+ }
}
}
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;
}
--- /dev/null
+/*
+ * 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;
+ }
+}
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) {
}
parentElement.appendChild(innerNode);
}
+
+ public String getKey() {
+ return key;
+ }
+
+ public Document getDocument() {
+ return document;
+ }
+
+ public Map<String, AttributeWritingStrategy> getInnerStrats() {
+ return innerStrats;
+ }
}
@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);
@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);
@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);
}
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 {
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;
// 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);
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);
typeElement.appendChild(document.createTextNode(value));
return typeElement;
}
-
protected Object preprocess(Object value) {
return value;
}
super(document, key);
}
+ @Override
protected Object preprocess(Object value) {
Util.checkType(value, List.class);
BaseEncoding en = BaseEncoding.base64();
public class SimpleIdentityRefAttributeWritingStrategy extends SimpleAttributeWritingStrategy {
- private static final char QNAME_SEPARATOR = ':';
private static final String PREFIX = "prefix";
/**
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;
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;
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;
}
// 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);
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) {
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);
}
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;
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;
}
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;
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 {
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,
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,
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);
}
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);
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;
}
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)) {
}
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;
+ }
}
}
}
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";
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) {
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);
}
@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;
}
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());
}
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));
}
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;
+ }
}
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 {
* 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;
}
@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;
}
}));
public class ModuleRuntime {
- private final String moduleName;
private final InstanceRuntime instanceRuntime;
public ModuleRuntime(String moduleName, InstanceRuntime instanceRuntime) {
- this.moduleName = moduleName;
this.instanceRuntime = instanceRuntime;
}
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);
}
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);
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);
- }
-
}
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;
+ }
}
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;
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,
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);
void addIdSchemaNode(IdentitySchemaNode node) {
String name = node.getQName().getLocalName();
- Preconditions.checkState(identityNameToSchemaNode.containsKey(name) == false);
+ Preconditions.checkState(!identityNameToSchemaNode.containsKey(name));
identityNameToSchemaNode.put(name, node);
}
}
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);
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);
.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
case replace:
return new ReplaceEditConfigStrategy(providedServices);
case delete:
- return new DeleteEditConfigStrategy(providedServices);
+ return new DeleteEditConfigStrategy();
case remove:
return new RemoveEditConfigStrategy();
case none:
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));
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));
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);
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
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);
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;
public Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
Datastore source;
source = fromXml(xml);
- return getResponseInternal(document, configRegistryClient, source);
+ return getResponseInternal(document, getConfigRegistryClient(), source);
}
}
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);
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,
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
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);
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);
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(
}
@Override
- public void stop(BundleContext context) throws Exception {
+ public void stop(BundleContext context) {
if (configRegistryLookup != null) {
configRegistryLookup.interrupt();
}
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);
}
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);
}
}
}
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);
+ }
}
}
}
}
- private static class YangStoreCapability extends BasicCapability {
+ private static final class YangStoreCapability extends BasicCapability {
private final String content;
private final String revision;
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;
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;
}
private boolean isStillOpenTransaction(ObjectName transaction) {
- boolean isStillOpenTransaction = configRegistryClient.getOpenConfigs().contains(transaction);
- return isStillOpenTransaction;
+ return configRegistryClient.getOpenConfigs().contains(transaction);
}
public synchronized ObjectName getOrCreateTransaction() {
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();
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();
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);
}
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);
}
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);
}
}
@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
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.
}
}
- 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);
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());
}
- 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));
} 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;
}
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;
}
return inner.getPrefix() + "." + index + ".properties";
}
+ @Override
+ public String getPropertyWithoutPrefix(String fullKey) {
+ return inner.getPropertyWithoutPrefix(fullKey);
+ }
+
+
@Override
public String getFullKeyForReporting(String key) {
return getPrefix() + "." + key;
// 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 {
/**
**/
-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(
--- /dev/null
+/*
+ * 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;
+ }
+}
});
}
- private static class ClientChannelInitializer extends AbstractChannelInitializer<NetconfClientSession> {
+ private static final class ClientChannelInitializer extends AbstractChannelInitializer<NetconfClientSession> {
private final NetconfClientSessionNegotiatorFactory negotiatorFactory;
private final NetconfClientSessionListener sessionListener;
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);
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);
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);
}
}
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;
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);
// 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);
@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());
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) {
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 {
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);
}
@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();
@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);
}
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;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
+import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
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);
}
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);
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,
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);
}
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);
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;
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);
@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;
}
*/
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;
@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);
*/
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";
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();
*/
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() {
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;
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);
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;
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();
}
@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);
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);
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);
@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,
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)) {
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");
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 {
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 {
}
@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));
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);
}
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);
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 {
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;
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;
}
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:
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;
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;
}
// 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;
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();
}
}
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)");
}
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.");
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;
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
@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;
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;
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))));
public void authenticate(Connection connection) throws IOException {
boolean isAuthenticated = connection.authenticateWithPassword(username, password);
- if (isAuthenticated == false) {
+ if (!isAuthenticated) {
throw new IOException("Authentication failed.");
}
}
}
public void close() {
- for (SshSession session : openSessions.values())
+ for (SshSession session : openSessions.values()){
closeSession(session);
+ }
openSessions.clear();
}
}
- while (stopRequested.get() == false) {
+ while (!stopRequested.get()) {
byte[] readBuff = new byte[BUFFER_SIZE];
int c = stdOut.read(readBuff);
if (c == -1) {
// Netty closed connection prematurely.
// Just pass and move on.
} catch (Exception e) {
- throw new RuntimeException(e);
+ throw new IllegalStateException(e);
} finally {
sshClient.close();
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
-
import java.io.IOException;
import java.io.InputStream;
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
- throw new RuntimeException(e);
+ throw new IllegalStateException(e);
}
}
return this.bb.readByte() & 0xFF;
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.
public static final int MAX_HEADER_LENGTH = 13;
public static final byte[] END_OF_CHUNK = "\n##\n".getBytes(Charsets.UTF_8);
+
}
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>
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();
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)) {
} 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);
}
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;
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;
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 {
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);
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);
}
}
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);
}
}