--- /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
+*/
+/*
+* Generated file
+*
+* 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
+*
+* Do not modify this file unless it is present under src/main directory
+*/
+package org.opendaylight.controller.config.yang.test.impl;
+public class DepTestImplModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractDepTestImplModuleFactory {
+
+}
--- /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
+*/
+/*
+* Generated file
+*
+* 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
+*
+* Do not modify this file unless it is present under src/main directory
+*/
+package org.opendaylight.controller.config.yang.test.impl;
+public class IdentityTestModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractIdentityTestModuleFactory {
+
+}
--- /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
+*/
+/*
+* Generated file
+*
+* 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
+*
+* Do not modify this file unless it is present under src/main directory
+*/
+package org.opendaylight.controller.config.yang.test.impl;
+public class NetconfTestImplModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractNetconfTestImplModuleFactory {
+
+}
--- /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
+*/
+/*
+* Generated file
+*
+* 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
+*
+* Do not modify this file unless it is present under src/main directory
+*/
+package org.opendaylight.controller.config.yang.test.impl;
+public class TestImplModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractTestImplModuleFactory {
+
+}
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ 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
+-->
<snapshot>
<required-capabilities>
<capability>urn:opendaylight:params:xml:ns:yang:controller:netty?module=netty&revision=2013-11-19</capability>
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ 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
+-->
<snapshot>
<configuration>
<data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ 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
+-->
<snapshot>
<configuration>
<data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ 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
+-->
+<snapshot>
+ <configuration>
+ <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
+ <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
+ <module>
+ <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf">prefix:sal-netconf-connector</type>
+ <name>controller-config</name>
+ <port xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf">1830</port>
+ <username xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf">admin</username>
+ <worker-thread-group xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf">
+ <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:netty">prefix:netty-threadgroup</type>
+ <name>global-worker-group</name>
+ </worker-thread-group>
+ <address xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf">127.0.0.1</address>
+ <tcp-only xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf">false</tcp-only>
+ <event-executor xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf">
+ <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:netty">prefix:netty-event-executor</type>
+ <name>global-event-executor</name>
+ </event-executor>
+ <password xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf">admin</password>
+ <boss-thread-group xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf">
+ <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:netty">prefix:netty-threadgroup</type>
+ <name>global-boss-group</name>
+ </boss-thread-group>
+ <dom-registry xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf">
+ <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">prefix:dom-broker-osgi-registry</type>
+ <name>dom-broker</name>
+ </dom-registry>
+ </module>
+ </modules>
+ </data>
+ </configuration>
+ <required-capabilities>
+ <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf?module=odl-sal-netconf-connector-cfg&revision=2013-10-28</capability>
+ </required-capabilities>
+</snapshot>
import java.util.Queue;
import java.util.Set;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
import org.opendaylight.controller.netconf.client.NetconfClientSession;
try {
NetconfMapping.checkSuccessReply(message);
- } catch (IllegalStateException e) {
+ } catch (NetconfDocumentedException | IllegalStateException e) {
LOG.warn("Error reply from remote device", e);
r.future.setException(e);
return;
*/
package org.opendaylight.controller.sal.connect.netconf;
+import com.google.common.base.Optional;
+import com.google.common.base.Predicate;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
-
import javax.activation.UnsupportedDataTypeException;
import javax.annotation.Nullable;
-
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
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.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
public class NetconfMapping {
public static URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
}
}
- public static void checkSuccessReply(NetconfMessage output) {
+ public static void checkSuccessReply(NetconfMessage output) throws NetconfDocumentedException {
if(NetconfMessageUtil.isErrorMessage(output)) {
throw new IllegalStateException(String.format("Response contains error: %s", XmlUtil.toString(output.getDocument())));
}
org.opendaylight.controller.netconf.confignetconfconnector.transactions,
org.opendaylight.controller.netconf.confignetconfconnector.util,
org.opendaylight.controller.netconf.confignetconfconnector.osgi,
- org.opendaylight.controller.config.util,</Private-Package>
+ org.opendaylight.controller.config.util,
+ org.opendaylight.controller.netconf.confignetconfconnector.exception,</Private-Package>
<Import-Package>com.google.common.base,
com.google.common.collect,
javax.annotation,
org.opendaylight.controller.netconf.mapping.api,
org.opendaylight.controller.netconf.util.mapping,
org.opendaylight.controller.netconf.util.xml,
+ org.opendaylight.controller.netconf.util.exception,
org.opendaylight.yangtools.yang.common,
org.opendaylight.yangtools.yang.model.api,
org.osgi.framework,
com.google.common.io,
org.opendaylight.yangtools.yang.model.api.type,
org.opendaylight.yangtools.sal.binding.generator.spi,
- org.opendaylight.yangtools.sal.binding.yang.types</Import-Package>
+ org.opendaylight.yangtools.sal.binding.yang.types,</Import-Package>
<Export-Package></Export-Package>
</instructions>
</configuration>
--- /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.exception;
+
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+
+import java.util.Collections;
+import java.util.Map;
+
+public class NetconfConfigHandlingException extends NetconfDocumentedException {
+
+ public NetconfConfigHandlingException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
+ }
+
+ public NetconfConfigHandlingException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
+ super(message,errorType,errorTag,errorSeverity,errorInfo);
+ }
+}
--- /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.exception;
+
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+
+import java.util.Collections;
+import java.util.Map;
+
+public class NoTransactionFoundException extends NetconfDocumentedException {
+
+ public NoTransactionFoundException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
+ }
+
+ public NoTransactionFoundException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
+ super(message,errorType,errorTag,errorSeverity,errorInfo);
+ }
+
+}
--- /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.exception;
+
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+
+import java.util.Collections;
+import java.util.Map;
+
+public class OperationNotPermittedException extends NetconfDocumentedException {
+
+ public OperationNotPermittedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
+ }
+
+ public OperationNotPermittedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
+ super(message,errorType,errorTag,errorSeverity,errorInfo);
+ }
+}
package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import java.util.List;
}
@Override
- public AttributeConfigElement readElement(List<XmlElement> configNodes) {
- if (configNodes.size() == 0)
+ public AttributeConfigElement readElement(List<XmlElement> configNodes) throws NetconfDocumentedException {
+ if (configNodes.size() == 0){
return AttributeConfigElement.createNullValue(postprocessNullableDefault(nullableDefault));
-
+ }
return readElementHook(configNodes);
}
- abstract AttributeConfigElement readElementHook(List<XmlElement> configNodes);
+ abstract AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws NetconfDocumentedException;
protected Object postprocessNullableDefault(String nullableDefault) {
return nullableDefault;
package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
import com.google.common.collect.Lists;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import java.util.List;
}
@Override
- AttributeConfigElement readElementHook(List<XmlElement> configNodes) {
+ AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws NetconfDocumentedException {
List<Object> innerList = Lists.newArrayList();
for (int i = 0; i < configNodes.size(); i++) {
innerList.add(innerStrategy.readElement(Lists.newArrayList(configNodes.get(i))).getValue());
import java.util.List;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
public interface AttributeReadingStrategy {
- public abstract AttributeConfigElement readElement(List<XmlElement> element);
+ public abstract AttributeConfigElement readElement(List<XmlElement> element) throws NetconfDocumentedException;
}
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import java.util.List;
}
@Override
- AttributeConfigElement readElementHook(List<XmlElement> configNodes) {
+ AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws NetconfDocumentedException {
Preconditions.checkState(configNodes.size() == 1, "This element should be present only once %s", configNodes);
List<XmlElement> recognisedChildren = Lists.newArrayList();
for (Entry<String, AttributeReadingStrategy> innerAttrEntry : innerStrategies.entrySet()) {
- List<XmlElement> childItem = complexElement.getChildElementsWithSameNamespace(innerAttrEntry.getKey());
+ List<XmlElement> childItem = null;
+ childItem = complexElement.getChildElementsWithSameNamespace(innerAttrEntry.getKey());
recognisedChildren.addAll(childItem);
AttributeConfigElement resolvedInner = innerAttrEntry.getValue().readElement(childItem);
package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
import com.google.common.base.Preconditions;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.ObjectNameAttributeMappingStrategy;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
public class ObjectNameAttributeReadingStrategy extends AbstractAttributeReadingStrategy {
private static final Object PREFIX_SEPARATOR = ":";
+ private static final Logger logger = LoggerFactory.getLogger(ObjectNameAttributeReadingStrategy.class);
public ObjectNameAttributeReadingStrategy(String nullableDefault) {
super(nullableDefault);
}
@Override
- AttributeConfigElement readElementHook(List<XmlElement> configNodes) {
+ AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws NetconfDocumentedException {
XmlElement firstChild = configNodes.get(0);
Preconditions.checkState(configNodes.size() == 1, "This element should be present only once " + firstChild
return AttributeConfigElement.create(getNullableDefault(), resolve(firstChild));
}
- private ObjectNameAttributeMappingStrategy.MappedDependency resolve(XmlElement firstChild) {
- XmlElement typeElement = firstChild.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
+ private ObjectNameAttributeMappingStrategy.MappedDependency resolve(XmlElement firstChild) throws NetconfDocumentedException{
+ XmlElement typeElement = null;
+ typeElement = firstChild.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
Map.Entry<String, String> prefixNamespace = typeElement.findNamespaceOfTextContent();
String serviceName = checkPrefixAndExtractServiceName(typeElement, prefixNamespace);
dependencyName);
}
- public static String checkPrefixAndExtractServiceName(XmlElement typeElement, Map.Entry<String, String> prefixNamespace) {
+ 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",
package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
import com.google.common.base.Preconditions;
+import java.util.List;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.List;
-
public class SimpleAttributeReadingStrategy extends AbstractAttributeReadingStrategy {
private static final Logger logger = LoggerFactory.getLogger(SimpleAttributeReadingStrategy.class);
}
@Override
- AttributeConfigElement readElementHook(List<XmlElement> configNodes) {
+ AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws NetconfDocumentedException {
XmlElement xmlElement = configNodes.get(0);
Preconditions.checkState(configNodes.size() == 1, "This element should be present only once " + xmlElement
+ " but was " + configNodes.size());
logger.warn("Ignoring exception caused by failure to read text element", e);
}
- Preconditions.checkNotNull(textContent, "This element should contain text %s", xmlElement);
+ if (null == textContent){
+ throw new NetconfDocumentedException(String.format("This element should contain text %s", xmlElement),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.invalid_value,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
return AttributeConfigElement.create(postprocessNullableDefault(getNullableDefault()),
postprocessParsedValue(textContent));
}
- protected String readElementContent(XmlElement xmlElement) {
+ protected String readElementContent(XmlElement xmlElement) throws NetconfDocumentedException {
return xmlElement.getTextContent();
}
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.operations.editconfig.EditConfig;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.yangtools.yang.common.QName;
}
@Override
- protected String readElementContent(XmlElement xmlElement) {
+ protected String readElementContent(XmlElement xmlElement) throws NetconfDocumentedException {
// TODO test
Map.Entry<String, String> namespaceOfTextContent = xmlElement.findNamespaceOfTextContent();
String content = xmlElement.getTextContent();
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.confignetconfconnector.operations.editconfig.EditStrategyType;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
// TODO refactor, replace Map->Multimap with e.g. ConfigElementResolved
// class
- public Map<String, Multimap<String, ModuleElementResolved>> fromXmlModulesResolved(XmlElement xml, EditStrategyType defaultEditStrategyType, ServiceRegistryWrapper serviceTracker) {
+ public Map<String, Multimap<String, ModuleElementResolved>> fromXmlModulesResolved(XmlElement xml, EditStrategyType defaultEditStrategyType, ServiceRegistryWrapper serviceTracker) throws NetconfDocumentedException {
Optional<XmlElement> modulesElement = getModulesElement(xml);
List<XmlElement> moduleElements = getModulesElementList(modulesElement);
for (XmlElement moduleElement : moduleElements) {
ResolvingStrategy<ModuleElementResolved> resolvingStrategy = new ResolvingStrategy<ModuleElementResolved>() {
@Override
- public ModuleElementResolved resolveElement(ModuleConfig moduleMapping, XmlElement moduleElement, ServiceRegistryWrapper serviceTracker, String instanceName, String moduleNamespace, EditStrategyType defaultStrategy) {
+ public ModuleElementResolved resolveElement(ModuleConfig moduleMapping, XmlElement moduleElement, ServiceRegistryWrapper serviceTracker, String instanceName, String moduleNamespace, EditStrategyType defaultStrategy) throws NetconfDocumentedException {
return moduleMapping.fromXml(moduleElement, serviceTracker,
instanceName, moduleNamespace, defaultStrategy, identityMap);
}
* return a map containing namespace -> moduleName -> instanceName map. Attribute parsing is omitted.
*/
public Map<String, Multimap<String, ModuleElementDefinition>> fromXmlModulesMap(XmlElement xml,
- EditStrategyType defaultEditStrategyType, ServiceRegistryWrapper serviceTracker) {
+ EditStrategyType defaultEditStrategyType, ServiceRegistryWrapper serviceTracker) throws NetconfDocumentedException {
Optional<XmlElement> modulesElement = getModulesElement(xml);
List<XmlElement> moduleElements = getModulesElementList(modulesElement);
XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
}
- private List<XmlElement> getModulesElementList(Optional<XmlElement> modulesElement) {
+ private List<XmlElement> getModulesElementList(Optional<XmlElement> modulesElement) throws NetconfDocumentedException {
List<XmlElement> moduleElements;
if (modulesElement.isPresent()) {
}
private <T> void resolveModule(Map<String, Multimap<String, T>> retVal, ServiceRegistryWrapper serviceTracker,
- XmlElement moduleElement, EditStrategyType defaultStrategy, ResolvingStrategy<T> resolvingStrategy) {
- XmlElement typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
+ XmlElement moduleElement, EditStrategyType defaultStrategy, ResolvingStrategy<T> resolvingStrategy) throws NetconfDocumentedException {
+ XmlElement typeElement = null;
+ typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
Entry<String, String> prefixToNamespace = typeElement.findNamespaceOfTextContent();
String moduleNamespace = prefixToNamespace.getValue();
- XmlElement nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.NAME_KEY);
+ XmlElement nameElement = null;
+ nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.NAME_KEY);
String instanceName = nameElement.getTextContent();
String factoryNameWithPrefix = typeElement.getTextContent();
String prefixOrEmptyString = prefixToNamespace.getKey();
innerMap.put(factoryName, resolvedElement);
}
- public Services fromXmlServices(XmlElement xml) {
+ public Services fromXmlServices(XmlElement xml) throws NetconfDocumentedException {
Optional<XmlElement> servicesElement = getServicesElement(xml);
Services services;
XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
}
- public static void checkUnrecognisedChildren(XmlElement parent) {
+ public static void checkUnrecognisedChildren(XmlElement parent) throws NetconfDocumentedException {
Optional<XmlElement> servicesOpt = getServicesElement(parent);
Optional<XmlElement> modulesOpt = getModulesElement(parent);
private interface ResolvingStrategy<T> {
public T resolveElement(ModuleConfig moduleMapping, XmlElement moduleElement, ServiceRegistryWrapper serviceTracker,
- String instanceName, String moduleNamespace, EditStrategyType defaultStrategy);
+ String instanceName, String moduleNamespace, EditStrategyType defaultStrategy) throws NetconfDocumentedException;
}
}
package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeReadingStrategy;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.ObjectXmlReader;
}
public InstanceConfigElementResolved fromXml(XmlElement moduleElement, ServiceRegistryWrapper services, String moduleNamespace,
- EditStrategyType defaultStrategy, Multimap<String, String> providedServices, Map<String, Map<Date,EditConfig.IdentityMapping>> identityMap) {
+ EditStrategyType defaultStrategy, Multimap<String, String> providedServices, Map<String, Map<Date,EditConfig.IdentityMapping>> identityMap) throws NetconfDocumentedException {
Map<String, AttributeConfigElement> retVal = Maps.newHashMap();
Map<String, AttributeReadingStrategy> strats = new ObjectXmlReader().prepareReading(yangToAttrConfig, identityMap);
List<XmlElement> recognisedChildren = Lists.newArrayList();
- XmlElement type = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
- XmlElement name = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.NAME_KEY);
+ XmlElement type = null;
+ XmlElement name = null;
+ type = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
+ name = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.NAME_KEY);
List<XmlElement> typeAndName = Lists.newArrayList(type, name);
for (Entry<String, AttributeReadingStrategy> readStratEntry : strats.entrySet()) {
}
private List<XmlElement> getConfigNodes(XmlElement moduleElement, String moduleNamespace, String name,
- List<XmlElement> recognisedChildren, List<XmlElement> typeAndName) {
+ List<XmlElement> recognisedChildren, List<XmlElement> typeAndName) throws NetconfDocumentedException {
List<XmlElement> foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name, moduleNamespace);
if (foundConfigNodes.isEmpty()) {
logger.debug("No config nodes {}:{} found in {}", moduleNamespace, name, moduleElement);
List<XmlElement> foundWithoutNamespaceNodes = moduleElement.getChildElementsWithinNamespace(name,
XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
foundWithoutNamespaceNodes.removeAll(typeAndName);
- Preconditions.checkState(foundWithoutNamespaceNodes.isEmpty(),
- "Element %s present multiple times with different namespaces: %s, %s", name, foundConfigNodes,
- foundWithoutNamespaceNodes);
+ if (!foundWithoutNamespaceNodes.isEmpty()){
+ throw new NetconfDocumentedException(String.format("Element %s present multiple times with different namespaces: %s, %s", name, foundConfigNodes,
+ foundWithoutNamespaceNodes),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.invalid_value,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
}
recognisedChildren.addAll(foundConfigNodes);
package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
-import com.google.common.base.Preconditions;
import com.google.common.collect.Multimap;
+import java.util.Map;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.confignetconfconnector.exception.OperationNotPermittedException;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfigStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfigXmlParser;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
-import java.util.Map;
-
/**
* Parsed xml element containing whole configuration for an instance of some
* module. Contains preferred edit strategy type.
private final Map<String, AttributeConfigElement> configuration;
private final Multimap<String, String> providedServices;
- public InstanceConfigElementResolved(String currentStrategy, Map<String, AttributeConfigElement> configuration, EditStrategyType defaultStrategy, Multimap<String, String> providedServices) {
- EditStrategyType valueOf = parseStrategy(currentStrategy, defaultStrategy);
+ public InstanceConfigElementResolved(String currentStrategy, Map<String, AttributeConfigElement> configuration, EditStrategyType defaultStrategy, Multimap<String, String> providedServices) throws NetconfDocumentedException {
+ EditStrategyType valueOf = null;
+ valueOf = parseStrategy(currentStrategy, defaultStrategy);
this.editStrategy = valueOf;
this.configuration = configuration;
this.providedServices = providedServices;
}
- static EditStrategyType parseStrategy(String currentStrategy, EditStrategyType defaultStrategy) {
+ static EditStrategyType parseStrategy(String currentStrategy, EditStrategyType defaultStrategy) throws OperationNotPermittedException {
EditStrategyType parsedStrategy = EditStrategyType.valueOf(currentStrategy);
- if (defaultStrategy.isEnforcing()) {
- Preconditions
- .checkArgument(
- parsedStrategy == defaultStrategy,
- "With "
- + defaultStrategy
- + " as "
- + EditConfigXmlParser.DEFAULT_OPERATION_KEY
- + " operations on module elements are not permitted since the default option is restrictive");
- }
+ EditStrategyType.compareParsedStrategyToDefaultEnforcing(parsedStrategy,defaultStrategy);
return parsedStrategy;
}
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.confignetconfconnector.operations.editconfig.EditStrategyType;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
}
public ModuleElementResolved fromXml(XmlElement moduleElement, ServiceRegistryWrapper depTracker, String instanceName,
- String moduleNamespace, EditStrategyType defaultStrategy, Map<String, Map<Date,EditConfig.IdentityMapping>> identityMap) {
+ String moduleNamespace, EditStrategyType defaultStrategy, Map<String, Map<Date,EditConfig.IdentityMapping>> identityMap) throws NetconfDocumentedException {
InstanceConfigElementResolved ice = instanceConfig.fromXml(moduleElement, depTracker, moduleNamespace, defaultStrategy, providedServices, identityMap);
return new ModuleElementResolved(instanceName, ice);
package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
+import org.opendaylight.controller.netconf.confignetconfconnector.exception.OperationNotPermittedException;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfigStrategy;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.MissingInstanceHandlingStrategy;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.NoneEditConfigStrategy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ModuleElementDefinition {
private final String instanceName;
private final EditStrategyType editStrategy;
+ private static final Logger logger = LoggerFactory.getLogger(ModuleElementDefinition.class);
public ModuleElementDefinition(String instanceName, String currentStrategy, EditStrategyType defaultStrategy) {
this.instanceName = instanceName;
- if (currentStrategy == null || currentStrategy.isEmpty())
+ if (currentStrategy == null || currentStrategy.isEmpty()) {
this.editStrategy = defaultStrategy;
- else
- this.editStrategy = InstanceConfigElementResolved.parseStrategy(currentStrategy, defaultStrategy);
+ } else {
+ EditStrategyType _edStrategy = null;
+ try {
+ _edStrategy = InstanceConfigElementResolved.parseStrategy(currentStrategy, defaultStrategy);
+ } catch (OperationNotPermittedException e) {
+ _edStrategy = defaultStrategy;
+ logger.warn("Operation not permitted on current strategy {} while default strategy is {}. Element definition strategy set to default.",
+ currentStrategy,
+ defaultStrategy,
+ e);
+ }
+ this.editStrategy = _edStrategy;
+ }
+
}
public String getInstanceName() {
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.mapping.attributes.fromxml.ObjectNameAttributeReadingStrategy;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
// TODO support edit strategies on services
- public static Services fromXml(XmlElement xml) {
+ public static Services fromXml(XmlElement xml) throws NetconfDocumentedException {
Map<String, Map<String, Map<String, String>>> retVal = Maps.newHashMap();
List<XmlElement> services = xml.getChildElements(SERVICE_KEY);
import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry.Rpc;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeReadingStrategy;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.ObjectXmlReader;
}
}
- public Map<String, AttributeConfigElement> fromXml(XmlElement configRootNode) {
+ public Map<String, AttributeConfigElement> fromXml(XmlElement configRootNode) throws NetconfDocumentedException {
Map<String, AttributeConfigElement> retVal = Maps.newHashMap();
// FIXME add identity map to runtime data
package org.opendaylight.controller.netconf.confignetconfconnector.operations;
-import java.util.HashMap;
-import java.util.Map;
-
import org.opendaylight.controller.config.api.ConflictingVersionException;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.api.jmx.CommitStatus;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
this.transactionProvider = transactionProvider;
}
- private static void checkXml(XmlElement xml) {
+ private static void checkXml(XmlElement xml) throws NetconfDocumentedException {
xml.checkName(XmlNetconfConstants.COMMIT);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
}
@Override
protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
- checkXml(xml);
+ checkXml(xml);
CommitStatus status;
try {
status = this.transactionProvider.commitTransaction();
- } catch (final IllegalStateException e) {
- // TODO Illegal state thrown when no transaction yet for user
- // Throw other exception type, or create transaction automatically
- logger.warn("Commit failed: ", e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.operation_failed.name(),
- "Operation failed. Use 'get-config' or 'edit-config' before triggering 'commit' operation");
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.application, ErrorTag.operation_failed,
- ErrorSeverity.error, errorInfo);
- } catch (ValidationException e) {
+ logger.trace("Datastore {} committed successfully: {}", Datastore.candidate, status);
+ } catch (ConflictingVersionException | ValidationException e) {
throw NetconfDocumentedException.wrap(e);
- } catch (ConflictingVersionException e) {
- throw NetconfDocumentedException.wrap(e);
-
}
logger.trace("Datastore {} committed successfully: {}", Datastore.candidate, status);
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations;
-
-import java.util.HashMap;
-import java.util.Map;
+ package org.opendaylight.controller.netconf.confignetconfconnector.operations;
+import com.google.common.base.Optional;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.base.Optional;
+import java.util.HashMap;
+import java.util.Map;
+
public class DiscardChanges extends AbstractConfigNetconfOperation {
this.transactionProvider = transactionProvider;
}
- private static void fromXml(XmlElement xml) {
+ private static void fromXml(XmlElement xml) throws NetconfDocumentedException {
xml.checkName(DISCARD);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
}
@Override
protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
- try {
- fromXml(xml);
- } catch (final IllegalArgumentException e) {
- //FIXME where can IllegalStateException be thrown?
- logger.warn("Rpc error: {}", ErrorTag.bad_attribute, e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.bad_attribute.name(), e.getMessage());
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.rpc, ErrorTag.bad_attribute,
- ErrorSeverity.error, errorInfo);
- }
-
+ fromXml(xml);
try {
this.transactionProvider.abortTransaction();
} catch (final IllegalStateException e) {
- //FIXME where can IllegalStateException be thrown?
logger.warn("Abort failed: ", e);
final Map<String, String> errorInfo = new HashMap<>();
errorInfo
}
logger.trace("Changes discarded successfully from datastore {}", Datastore.candidate);
+
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
}
package org.opendaylight.controller.netconf.confignetconfconnector.operations;
-import java.util.HashMap;
-import java.util.Map;
-
+import com.google.common.base.Optional;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
+import java.util.HashMap;
+import java.util.Map;
public class Validate extends AbstractConfigNetconfOperation {
this.transactionProvider = transactionProvider;
}
- private void checkXml(XmlElement xml) {
+ private void checkXml(XmlElement xml) throws NetconfDocumentedException {
xml.checkName(VALIDATE);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
String datastoreValue = sourceChildNode.getName();
Datastore sourceDatastore = Datastore.valueOf(datastoreValue);
- Preconditions.checkState(sourceDatastore == Datastore.candidate, "Only " + Datastore.candidate
- + " is supported as source for " + VALIDATE + " but was " + datastoreValue);
+ if (sourceDatastore != Datastore.candidate){
+ throw new NetconfDocumentedException( "Only " + Datastore.candidate
+ + " is supported as source for " + VALIDATE + " but was " + datastoreValue,ErrorType.application,ErrorTag.data_missing,ErrorSeverity.error);
+ }
}
@Override
@Override
protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
- try {
- checkXml(xml);
- } catch (IllegalStateException e) {
- //FIXME where can IllegalStateException be thrown? I see precondition that guards for programming bugs..
- logger.warn("Rpc error: {}", ErrorTag.missing_attribute, e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.missing_attribute.name(), "Missing value of datastore attribute");
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.rpc, ErrorTag.missing_attribute,
- ErrorSeverity.error, errorInfo);
- } catch (final IllegalArgumentException e) {
- // FIXME use checked exception if it has domain meaning
- logger.warn("Rpc error: {}", ErrorTag.bad_attribute, e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.bad_attribute.name(), e.getMessage());
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.rpc, ErrorTag.bad_attribute,
- ErrorSeverity.error, errorInfo);
- }
-
+ checkXml(xml);
try {
transactionProvider.validateTransaction();
} catch (ValidationException e) {
package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
+import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
import org.slf4j.Logger;
@Override
public void executeConfiguration(String module, String instance, Map<String, AttributeConfigElement> configuration,
- ConfigTransactionClient ta, ServiceRegistryWrapper services) {
+ ConfigTransactionClient ta, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
try {
ObjectName on = ta.lookupConfigBean(module, instance);
// edit configs should not handle missing
abstract void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services);
+ String module, String instance, ServiceRegistryWrapper services) throws NetconfConfigHandlingException;
abstract void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- ObjectName objectName, ServiceRegistryWrapper services);
+ ObjectName objectName, ServiceRegistryWrapper services) throws NetconfConfigHandlingException;
}
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
import org.slf4j.Logger;
@Override
void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) {
- throw new IllegalStateException("Unable to delete " + module + ":" + instance + " , ServiceInstance not found");
+ String module, String instance, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
+ throw new NetconfConfigHandlingException(String.format("Unable to delete %s : %s , ServiceInstance not found", module ,instance),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
}
@Override
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) {
+ void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
try {
ta.destroyModule(on);
logger.debug("ServiceInstance {} deleted successfully", on);
} catch (InstanceNotFoundException e) {
- throw new IllegalStateException("Unable to delete " + on, e);
+ throw new NetconfConfigHandlingException(
+ String.format("Unable to delete %s because of exception %s" + on, e.getMessage()),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
}
}
}
package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Multimap;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
+import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Config;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.InstanceConfig;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.InstanceConfigElementResolved;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Multimap;
+import javax.management.InstanceNotFoundException;
+import javax.management.ObjectName;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
public class EditConfig extends AbstractConfigNetconfOperation {
@VisibleForTesting
Element getResponseInternal(final Document document,
- final EditConfigXmlParser.EditConfigExecution editConfigExecution) throws NetconfDocumentedException {
+ final EditConfigXmlParser.EditConfigExecution editConfigExecution) throws NetconfDocumentedException, NetconfConfigHandlingException {
if (editConfigExecution.shouldTest()) {
executeTests(configRegistryClient, editConfigExecution);
private void executeSet(ConfigRegistryClient configRegistryClient,
EditConfigXmlParser.EditConfigExecution editConfigExecution) throws NetconfDocumentedException {
- try {
- set(configRegistryClient, editConfigExecution);
-
- } catch (IllegalStateException e) {
- //FIXME: when can IllegalStateException be thrown?
- // JmxAttributeValidationException is wrapped in DynamicWritableWrapper with ValidationException
- // ValidationException is not thrown until validate or commit is issued
- logger.warn("Set phase for {} failed", EditConfigXmlParser.EDIT_CONFIG, e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.operation_failed.name(), e.getMessage());
- throw new NetconfDocumentedException("Test phase: " + e.getMessage(), e, ErrorType.application,
- ErrorTag.operation_failed, ErrorSeverity.error, errorInfo);
- }
+ set(configRegistryClient, editConfigExecution);
logger.debug("Set phase for {} operation successful", EditConfigXmlParser.EDIT_CONFIG);
}
EditConfigExecution editConfigExecution) throws NetconfDocumentedException {
try {
test(configRegistryClient, editConfigExecution, editConfigExecution.getDefaultStrategy());
- } catch (IllegalStateException | ValidationException e) {
- //FIXME: when can IllegalStateException be thrown?
+ } catch (final ValidationException e) {
logger.warn("Test phase for {} failed", EditConfigXmlParser.EDIT_CONFIG, e);
final Map<String, String> errorInfo = new HashMap<>();
errorInfo.put(ErrorTag.operation_failed.name(), e.getMessage());
}
private void test(ConfigRegistryClient configRegistryClient, EditConfigExecution execution,
- EditStrategyType editStrategyType) throws ValidationException {
+ EditStrategyType editStrategyType) throws ValidationException, NetconfDocumentedException {
ObjectName taON = transactionProvider.getTestTransaction();
try {
-
// default strategy = replace wipes config
if (editStrategyType == EditStrategyType.replace) {
transactionProvider.wipeTestTransaction(taON);
}
private void set(ConfigRegistryClient configRegistryClient,
- EditConfigXmlParser.EditConfigExecution editConfigExecution) {
+ EditConfigXmlParser.EditConfigExecution editConfigExecution) throws NetconfDocumentedException {
ObjectName taON = transactionProvider.getOrCreateTransaction();
// default strategy = replace wipes config
setOnTransaction(ta, editConfigExecution);
}
- private void setServicesOnTransaction(ConfigTransactionClient ta, EditConfigExecution execution) {
+ private void setServicesOnTransaction(ConfigTransactionClient ta, EditConfigExecution execution) throws NetconfDocumentedException {
Services services = execution.getServices();
logger.debug("Saving service {} with on {} under name {} with service on {}", qnameOfService,
on, refName, saved);
} catch (InstanceNotFoundException e) {
- throw new IllegalStateException("Unable to save ref name " + refName + " for instance " + on, e);
+ throw new NetconfDocumentedException(String.format("Unable to save ref name " + refName + " for instance " + on, e),
+ ErrorType.application,
+ ErrorTag.operation_failed,
+ ErrorSeverity.error);
}
}
}
return ta.getServiceInterfaceName(namespace, serviceName);
}
- private void setOnTransaction(ConfigTransactionClient ta, EditConfigExecution execution) {
+ private void setOnTransaction(ConfigTransactionClient ta, EditConfigExecution execution) throws NetconfDocumentedException {
for (Multimap<String, ModuleElementResolved> modulesToResolved : execution.getResolvedXmlElements(ta).values()) {
- for (Entry<String, ModuleElementResolved> moduleToResolved : modulesToResolved.entries()) {
+ for (Map.Entry<String, ModuleElementResolved> moduleToResolved : modulesToResolved.entries()) {
String moduleName = moduleToResolved.getKey();
ModuleElementResolved moduleElementResolved = moduleToResolved.getValue();
}
private void handleMisssingInstancesOnTransaction(ConfigTransactionClient ta,
- EditConfigExecution execution) {
+ EditConfigExecution execution) throws NetconfDocumentedException {
for (Multimap<String,ModuleElementDefinition> modulesToResolved : execution.getModulesDefinition(ta).values()) {
- for (Entry<String, ModuleElementDefinition> moduleToResolved : modulesToResolved.entries()) {
+ for (Map.Entry<String, ModuleElementDefinition> moduleToResolved : modulesToResolved.entries()) {
String moduleName = moduleToResolved.getKey();
ModuleElementDefinition moduleElementDefinition = moduleToResolved.getValue();
Map<String, Map<String, ModuleConfig>> namespaceToModuleNameToModuleConfig = Maps.newHashMap();
for (String namespace : mBeanEntries.keySet()) {
- for (Entry<String, ModuleMXBeanEntry> moduleNameToMbe : mBeanEntries.get(namespace).entrySet()) {
+ for (Map.Entry<String, ModuleMXBeanEntry> moduleNameToMbe : mBeanEntries.get(namespace).entrySet()) {
String moduleName = moduleNameToMbe.getKey();
ModuleMXBeanEntry moduleMXBeanEntry = moduleNameToMbe.getValue();
EditConfigXmlParser.EditConfigExecution editConfigExecution;
Config cfg = getConfigMapping(configRegistryClient, yangStoreSnapshot);
- try {
- editConfigExecution = editConfigXmlParser.fromXml(xml, cfg, transactionProvider, configRegistryClient);
- } catch (IllegalStateException e) {
- logger.warn("Error parsing xml", e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.missing_attribute.name(), "Error parsing xml: " + e.getMessage());
- throw new NetconfDocumentedException(e.getMessage(), ErrorType.rpc, ErrorTag.missing_attribute,
- ErrorSeverity.error, errorInfo);
- } catch (final IllegalArgumentException e) {
- logger.warn("Error parsing xml", e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.bad_attribute.name(), e.getMessage());
- throw new NetconfDocumentedException(e.getMessage(), ErrorType.rpc, ErrorTag.bad_attribute,
- ErrorSeverity.error, errorInfo);
- } catch (final UnsupportedOperationException e) {
- logger.warn("Unsupported", e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.operation_not_supported.name(), "Unsupported option for 'edit-config'");
- throw new NetconfDocumentedException(e.getMessage(), ErrorType.application,
- ErrorTag.operation_not_supported, ErrorSeverity.error, errorInfo);
- }
+ editConfigExecution = editConfigXmlParser.fromXml(xml, cfg, transactionProvider, configRegistryClient);
- return getResponseInternal(document, editConfigExecution);
+ Element responseInternal;
+ responseInternal = getResponseInternal(document, editConfigExecution);
+ return responseInternal;
}
}
package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
+import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
public interface EditConfigStrategy {
void executeConfiguration(String module, String instance, Map<String, AttributeConfigElement> configuration,
- ConfigTransactionClient ta, ServiceRegistryWrapper services);
+ ConfigTransactionClient ta, ServiceRegistryWrapper services) throws NetconfConfigHandlingException;
}
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
import com.google.common.collect.Multimap;
import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Services;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.Datastore;
import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
+import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
+import org.opendaylight.controller.netconf.util.exception.UnexpectedNamespaceException;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
import org.slf4j.Logger;
xml.checkName(EditConfigXmlParser.EDIT_CONFIG);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- XmlElement targetElement = xml.getOnlyChildElementWithSameNamespace(EditConfigXmlParser.TARGET_KEY);
- XmlElement targetChildNode = targetElement.getOnlyChildElementWithSameNamespace();
+
+ XmlElement targetElement = null;
+ XmlElement targetChildNode = null;
+ try {
+ targetElement = xml.getOnlyChildElementWithSameNamespace(EditConfigXmlParser.TARGET_KEY);
+ targetChildNode = targetElement.getOnlyChildElementWithSameNamespace();
+ } catch (final MissingNameSpaceException | UnexpectedNamespaceException e) {
+ logger.trace("Can't get only child element with same namespace due to {}",e);
+ throw NetconfDocumentedException.wrap(e);
+ }
String datastoreValue = targetChildNode.getName();
Datastore targetDatastore = Datastore.valueOf(datastoreValue);
logger.debug("Setting {} to '{}'", EditConfigXmlParser.TARGET_KEY, targetDatastore);
// check target
- Preconditions.checkArgument(targetDatastore == Datastore.candidate,
- "Only %s datastore supported for edit config but was: %s", Datastore.candidate, targetDatastore);
+ if (targetDatastore != Datastore.candidate){
+ throw new NetconfDocumentedException(String.format(
+ "Only %s datastore supported for edit config but was: %s",
+ Datastore.candidate,
+ targetDatastore),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.invalid_value,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
// Test option
TestOption testOption;
editStrategyType = EditStrategyType.valueOf(mergeStrategyString);
}
- XmlElement configElement = xml.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.CONFIG_KEY);
+ XmlElement configElement = null;
+ try {
+ configElement = xml.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.CONFIG_KEY);
+ } catch (MissingNameSpaceException e) {
+ logger.trace("Can't get only child element with same namespace due to {}",e);
+ throw NetconfDocumentedException.wrap(e);
+ }
return new EditConfigXmlParser.EditConfigExecution(cfgMapping, configElement, testOption, editStrategyType);
}
private final Config configResolver;
private final XmlElement configElement;
- EditConfigExecution(Config configResolver, XmlElement configElement, TestOption testOption, EditStrategyType defaultStrategy) {
+ EditConfigExecution(Config configResolver, XmlElement configElement, TestOption testOption, EditStrategyType defaultStrategy) throws NetconfDocumentedException {
Config.checkUnrecognisedChildren(configElement);
this.configResolver = configResolver;
this.configElement = configElement;
return testOption == TestOption.set || testOption == TestOption.testThenSet;
}
- Map<String, Multimap<String, ModuleElementResolved>> getResolvedXmlElements(ServiceReferenceReadableRegistry serviceRegistry) {
+ Map<String, Multimap<String, ModuleElementResolved>> getResolvedXmlElements(ServiceReferenceReadableRegistry serviceRegistry) throws NetconfDocumentedException {
return configResolver.fromXmlModulesResolved(configElement, defaultEditStrategyType, getServiceRegistryWrapper(serviceRegistry));
}
return new ServiceRegistryWrapper(serviceRegistry);
}
- Map<String, Multimap<String,ModuleElementDefinition>> getModulesDefinition(ServiceReferenceReadableRegistry serviceRegistry) {
+ Map<String, Multimap<String,ModuleElementDefinition>> getModulesDefinition(ServiceReferenceReadableRegistry serviceRegistry) throws NetconfDocumentedException {
return configResolver.fromXmlModulesMap(configElement, defaultEditStrategyType, getServiceRegistryWrapper(serviceRegistry));
}
package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
import com.google.common.collect.Multimap;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.confignetconfconnector.exception.OperationNotPermittedException;
import java.util.EnumSet;
import java.util.Set;
+ this);
}
}
+ public static void compareParsedStrategyToDefaultEnforcing(EditStrategyType parsedStrategy,
+ EditStrategyType defaultStrategy) throws OperationNotPermittedException {
+ if (defaultStrategy.isEnforcing()) {
+ if (parsedStrategy != defaultStrategy){
+ throw new OperationNotPermittedException(String.format("With "
+ + defaultStrategy
+ + " as "
+ + EditConfigXmlParser.DEFAULT_OPERATION_KEY
+ + " operations on module elements are not permitted since the default option is restrictive"),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
+ }
+ }
public EditConfigStrategy getFittingStrategy(Multimap<String, String> providedServices) {
switch (this) {
case merge:
import com.google.common.collect.Multimap;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
import org.slf4j.Logger;
@Override
void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) {
- throw new IllegalStateException(
- "Unable to handle missing instance, no missing instances should appear at this point, missing: "
- + module + ":" + instance);
+ String module, String instance, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
+ throw new NetconfConfigHandlingException(
+ String.format("Unable to handle missing instance, no missing instances should appear at this point, missing: %s : %s ",
+ module,
+ instance),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
}
private void addRefNames(ServiceRegistryWrapper services, Multimap<String, String> providedServices, ConfigTransactionClient ta, ObjectName on) throws InstanceNotFoundException {
}
@Override
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) {
+ void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
try {
addRefNames(services, providedServices, ta, on);
} catch (InstanceNotFoundException e) {
- throw new IllegalStateException("Unable to save default ref name for instance " + on, e);
+ throw new NetconfConfigHandlingException(String.format("Unable to save default ref name for instance %s. Instance was not found.",e),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
}
for (Entry<String, AttributeConfigElement> configAttributeEntry : configuration.entrySet()) {
ta.setAttribute(on, ace.getJmxName(), new Attribute(ace.getJmxName(), value));
logger.debug("Attribute {} set to {} for {}", configAttributeEntry.getKey(), value, on);
} catch (Exception e) {
- throw new IllegalStateException("Unable to set attributes for " + on + ", Error with attribute "
- + configAttributeEntry.getKey() + ":" + configAttributeEntry.getValue(), e);
+ throw new NetconfConfigHandlingException(String.format("Unable to set attributes for %s, Error with attribute %s : %s ",
+ on,
+ configAttributeEntry.getKey(),
+ configAttributeEntry.getValue()),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
}
}
}
package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
import org.slf4j.Logger;
@Override
void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) {
+ String module, String instance, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
ObjectName on = null;
try {
on = ta.createModule(module, instance);
logger.trace("New instance for {} {} created under name {}", module, instance, on);
} catch (InstanceAlreadyExistsException e1) {
- throw new IllegalStateException("Unable to create instance for " + module + " : " + instance);
+ throw new NetconfConfigHandlingException(String.format("Unable to create instance for %s : %s.", module, instance),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
}
}
import com.google.common.collect.Multimap;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
import org.slf4j.Logger;
@Override
void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) {
- throw new IllegalStateException(
- "Unable to handle missing instance, no missing instances should appear at this point, missing: "
- + module + ":" + instance);
+ String module, String instance, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
+ throw new NetconfConfigHandlingException(
+ String.format("Unable to handle missing instance, no missing instances should appear at this point, missing: %s : %s ",
+ module,
+ instance),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
}
private void addRefNames(ServiceRegistryWrapper services, Multimap<String, String> providedServices, ConfigTransactionClient ta, ObjectName on) throws InstanceNotFoundException {
}
@Override
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) {
+ void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
try {
addRefNames(services, providedServices, ta, on);
} catch (InstanceNotFoundException e) {
- throw new IllegalStateException("Unable to save default ref name for instance " + on, e);
+ throw new NetconfConfigHandlingException(String.format("Unable to save default ref name for instance %s. Instance not found. ",on),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
}
for (Entry<String, AttributeConfigElement> configAttributeEntry : configuration.entrySet()) {
package org.opendaylight.controller.netconf.confignetconfconnector.operations.get;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.management.ObjectName;
-
+import com.google.common.collect.Maps;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.InstanceConfig;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleConfig;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.Datastore;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
+import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
+import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
+import org.opendaylight.controller.netconf.util.exception.UnexpectedElementException;
+import org.opendaylight.controller.netconf.util.exception.UnexpectedNamespaceException;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
import org.slf4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.collect.Maps;
+import javax.management.ObjectName;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
public class Get extends AbstractConfigNetconfOperation {
return jmxToYangNamesForChildRbe;
}
- private static void checkXml(XmlElement xml) {
+ private static void checkXml(XmlElement xml) throws UnexpectedElementException, UnexpectedNamespaceException, MissingNameSpaceException {
xml.checkName(XmlNetconfConstants.GET);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
@Override
protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
- try {
- checkXml(xml);
- } catch (final IllegalArgumentException e) {
- logger.warn("Error parsing xml", e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.bad_attribute.name(), e.getMessage());
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.rpc, ErrorTag.bad_attribute,
- ErrorSeverity.error, errorInfo);
- } catch (final UnsupportedOperationException e) {
- logger.warn("Unsupported", e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.operation_not_supported.name(), "Unsupported option for 'get'");
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.application,
- ErrorTag.operation_not_supported, ErrorSeverity.error, errorInfo);
- }
+ checkXml(xml);
final Set<ObjectName> runtimeBeans = configRegistryClient.lookupRuntimeBeans();
package org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import javax.management.ObjectName;
-
+import com.google.common.base.Optional;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Config;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
+import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
+import org.opendaylight.controller.netconf.util.exception.UnexpectedElementException;
+import org.opendaylight.controller.netconf.util.exception.UnexpectedNamespaceException;
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.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.base.Optional;
+import javax.management.ObjectName;
+import java.util.Set;
public class GetConfig extends AbstractConfigNetconfOperation {
this.transactionProvider = transactionProvider;
}
- public static Datastore fromXml(XmlElement xml) {
+ public static Datastore fromXml(XmlElement xml) throws UnexpectedNamespaceException, UnexpectedElementException, MissingNameSpaceException, NetconfDocumentedException {
+
xml.checkName(GET_CONFIG);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
@Override
public Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
Datastore source;
- try {
- source = fromXml(xml);
- } catch (final IllegalArgumentException e) {
- logger.warn("Rpc error: {}", ErrorTag.bad_attribute, e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.bad_attribute.name(), e.getMessage());
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.rpc, ErrorTag.bad_attribute,
- ErrorSeverity.error, errorInfo);
- } catch (final IllegalStateException e) {
- logger.warn("Rpc error: {}", ErrorTag.missing_attribute, e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.missing_attribute.name(), "Missing datasource attribute value");
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.rpc, ErrorTag.missing_attribute,
- ErrorSeverity.error, errorInfo);
- } catch (final UnsupportedOperationException e) {
- logger.warn("Unsupported", e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.operation_not_supported.name(), "Unsupported option for get");
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.application,
- ErrorTag.operation_not_supported, ErrorSeverity.error, errorInfo);
- }
+ source = fromXml(xml);
return getResponseInternal(document, configRegistryClient, source);
}
}
package org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc;
-import java.util.Map;
-
-import javax.management.ObjectName;
-import javax.management.openmbean.OpenType;
-
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
+import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
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.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 javax.management.openmbean.OpenType;
+import java.util.Map;
public class RuntimeRpc extends AbstractConfigNetconfOperation {
this.yangStoreSnapshot = yangStoreSnapshot;
}
- private Element toXml(Document doc, Object result, AttributeIfc returnType, String namespace, String elementName) {
+ private Element toXml(Document doc, Object result, AttributeIfc returnType, String namespace, String elementName) throws NetconfDocumentedException {
AttributeMappingStrategy<?, ? extends OpenType<?>> mappingStrategy = new ObjectMapper(null).prepareStrategy(returnType);
Optional<?> mappedAttributeOpt = mappingStrategy.mapAttribute(result);
Preconditions.checkState(mappedAttributeOpt.isPresent(), "Unable to map return value %s as %s", result, returnType.getOpenType());
}
public NetconfOperationExecution fromXml(final XmlElement xml) throws NetconfDocumentedException {
- final String namespace = xml.getNamespace();
+ final String namespace;
+ try {
+ namespace = xml.getNamespace();
+ } catch (MissingNameSpaceException e) {
+ logger.trace("Can't get namespace from xml element due to {}",e);
+ throw NetconfDocumentedException.wrap(e);
+ }
final XmlElement contextInstanceElement = xml.getOnlyChildElement(CONTEXT_INSTANCE);
final String operationName = xml.getName();
}
@Override
- public HandlingPriority canHandle(Document message) {
- XmlElement requestElement = getRequestElementWithCheck(message);
+ public HandlingPriority canHandle(Document message) throws NetconfDocumentedException {
+ XmlElement requestElement = null;
+ requestElement = getRequestElementWithCheck(message);
XmlElement operationElement = requestElement.getOnlyChildElement();
final String netconfOperationName = operationElement.getName();
- final String netconfOperationNamespace = operationElement.getNamespace();
+ final String netconfOperationNamespace;
+ try {
+ netconfOperationNamespace = operationElement.getNamespace();
+ } catch (MissingNameSpaceException e) {
+ logger.debug("Cannot retrieve netconf operation namespace from message due to {}", e);
+ return HandlingPriority.CANNOT_HANDLE;
+ }
final Optional<XmlElement> contextInstanceElement = operationElement
.getOnlyChildElementOptionally(CONTEXT_INSTANCE);
@Override
protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
-
- // TODO exception handling
// TODO check for namespaces and unknown elements
-
final NetconfOperationExecution execution = fromXml(xml);
logger.debug("Invoking operation {} on {} with arguments {}", execution.operationName, execution.on,
import org.opendaylight.controller.config.api.jmx.CommitStatus;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.confignetconfconnector.exception.NoTransactionFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Commit and notification send must be atomic
*/
- public synchronized CommitStatus commitTransaction() throws ValidationException, ConflictingVersionException {
+ public synchronized CommitStatus commitTransaction() throws ValidationException, ConflictingVersionException, NoTransactionFoundException {
+ if (!getTransaction().isPresent()){
+ throw new NoTransactionFoundException("No transaction found for session " + netconfSessionIdForReporting,
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
final Optional<ObjectName> maybeTaON = getTransaction();
- Preconditions.checkState(maybeTaON.isPresent(), "No transaction found for session " + netconfSessionIdForReporting);
ObjectName taON = maybeTaON.get();
try {
CommitStatus status = configRegistryClient.commitConfig(taON);
package org.opendaylight.controller.netconf.confignetconfconnector;
-import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElement;
-import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithText;
-import static org.opendaylight.controller.netconf.util.xml.XmlUtil.readXmlToElement;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigInteger;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import javax.xml.parsers.ParserConfigurationException;
-
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
import org.custommonkey.xmlunit.AbstractNodeTester;
import org.custommonkey.xmlunit.NodeTest;
import org.custommonkey.xmlunit.NodeTestException;
import org.opendaylight.controller.config.yang.test.impl.Peers;
import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.DiscardChanges;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
+import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
import org.w3c.dom.traversal.DocumentTraversal;
import org.xml.sax.SAXException;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.InstanceNotFoundException;
+import javax.management.ObjectName;
+import javax.xml.parsers.ParserConfigurationException;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.math.BigInteger;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElement;
+import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithText;
+import static org.opendaylight.controller.netconf.util.xml.XmlUtil.readXmlToElement;
public class NetconfMappingTest extends AbstractConfigTest {
assertThat(string, JUnitMatchers.containsString(substring));
}
- private void checkEnum(final Document response) {
+ private void checkEnum(final Document response) throws NetconfDocumentedException {
XmlElement modulesElement = XmlElement.fromDomElement(response.getDocumentElement()).getOnlyChildElement("data")
.getOnlyChildElement("modules");
assertEquals(2, testingDepsSize);
}
- private void checkTypeConfigAttribute(Document response) {
+ private void checkTypeConfigAttribute(Document response) throws NetconfDocumentedException {
XmlElement modulesElement = XmlElement.fromDomElement(response.getDocumentElement()).getOnlyChildElement("data")
.getOnlyChildElement("modules");
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.InstanceConfigElementResolved;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Services;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.ValidateTest;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfigXmlParser.EditConfigExecution;
+import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
import org.opendaylight.controller.netconf.util.xml.XmlUtil;
any(ConfigTransactionClient.class), any(ServiceRegistryWrapper.class));
}
- private EditConfigExecution mockExecution(EditConfigStrategy editStrat) {
+ private EditConfigExecution mockExecution(EditConfigStrategy editStrat) throws NetconfDocumentedException {
EditConfigExecution mock = mock(EditConfigExecution.class);
doReturn(getMapping(editStrat)).when(mock).getResolvedXmlElements(any(ConfigTransactionClient.class));
doReturn(getMappingDefinition(editStrat)).when(mock).getModulesDefinition(any(ConfigTransactionClient.class));
this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis;
}
- public synchronized LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponse> pushConfigs(List<ConfigSnapshotHolder> configs) {
+ public synchronized LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponse> pushConfigs(List<ConfigSnapshotHolder> configs) throws NetconfDocumentedException {
logger.debug("Last config snapshots to be pushed to netconf: {}", configs);
LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponse> result = new LinkedHashMap<>();
// start pushing snapshots:
* is caught, whole process is retried - new service instance need to be obtained from the factory. Closes
* {@link NetconfOperationService} after each use.
*/
- private synchronized EditAndCommitResponse pushConfigWithConflictingVersionRetries(ConfigSnapshotHolder configSnapshotHolder) {
+ private synchronized EditAndCommitResponse pushConfigWithConflictingVersionRetries(ConfigSnapshotHolder configSnapshotHolder) throws NetconfDocumentedException {
ConflictingVersionException lastException;
Stopwatch stopwatch = new Stopwatch().start();
do {
} else {
serviceCandidate.close();
logger.trace("Netconf server did not provide required capabilities for {} " +
- "Expected but not found: {}, all expected {}, current {}",
+ "Expected but not found: {}, all expected {}, current {}",
idForReporting, notFoundDiff, expectedCapabilities, serviceCandidate.getCapabilities()
);
throw new NotEnoughCapabilitiesException("Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundDiff);
* @throws java.lang.RuntimeException if edit-config or commit fails otherwise
*/
private synchronized EditAndCommitResponse pushConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfOperationService operationService)
- throws ConflictingVersionException {
+ throws ConflictingVersionException, NetconfDocumentedException {
Element xmlToBePersisted;
try {
return new EditAndCommitResponse(editResponseMessage, commitResponseMessage);
}
- private NetconfOperation findOperation(NetconfMessage request, NetconfOperationService operationService) {
+ private NetconfOperation findOperation(NetconfMessage request, NetconfOperationService operationService) throws NetconfDocumentedException {
TreeMap<HandlingPriority, NetconfOperation> allOperations = new TreeMap<>();
Set<NetconfOperation> netconfOperations = operationService.getNetconfOperations();
if (netconfOperations.isEmpty()) {
private Document sendRequestGetResponseCheckIsOK(NetconfMessage request, NetconfOperationService operationService,
String operationNameForReporting, String configIdForReporting)
- throws ConflictingVersionException {
+ throws ConflictingVersionException, NetconfDocumentedException {
NetconfOperation operation = findOperation(request, operationService);
Document response;
}
// load editConfig.xml template, populate /rpc/edit-config/config with parameter
- private static NetconfMessage createEditConfigMessage(Element dataElement) {
+ private static NetconfMessage createEditConfigMessage(Element dataElement) throws NetconfDocumentedException {
String editConfigResourcePath = "/netconfOp/editConfig.xml";
try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcePath)) {
Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcePath);
import com.google.common.annotations.VisibleForTesting;
import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
final Thread pushingThread = new Thread(new Runnable() {
@Override
public void run() {
- configPusher.pushConfigs(configs);
+ try {
+ configPusher.pushConfigs(configs);
+ } catch (NetconfDocumentedException e) {
+ logger.error("Error pushing configs {}",configs);
+ throw new IllegalStateException(e);
+ }
logger.info("Configuration Persister initialization completed.");
ConfigPersisterNotificationHandler jmxNotificationHandler = new ConfigPersisterNotificationHandler(platformMBeanServer, persisterAggregator);
synchronized (ConfigPersisterActivator.this) {
this.errorInfo = errorInfo;
}
+ public static <E extends Exception> NetconfDocumentedException wrap(E exception) throws NetconfDocumentedException {
+ final Map<String, String> errorInfo = new HashMap<>();
+ errorInfo.put(ErrorTag.operation_failed.name(), "Exception thrown");
+ throw new NetconfDocumentedException(exception.getMessage(), exception, ErrorType.application, ErrorTag.operation_failed,
+ ErrorSeverity.error, errorInfo);
+ }
public static NetconfDocumentedException wrap(ValidationException e) throws NetconfDocumentedException {
final Map<String, String> errorInfo = new HashMap<>();
errorInfo.put(ErrorTag.operation_failed.name(), "Validation failed");
package org.opendaylight.controller.netconf.client;
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpression;
-
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.util.Timer;
+import io.netty.util.concurrent.Promise;
import org.opendaylight.controller.netconf.api.NetconfClientSessionPreferences;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.AbstractChannelInitializer;
import org.opendaylight.controller.netconf.util.AbstractNetconfSessionNegotiator;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
-import io.netty.channel.ChannelFutureListener;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-import io.netty.util.Timer;
-import io.netty.util.concurrent.Promise;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpression;
public class NetconfClientSessionNegotiator extends
AbstractNetconfSessionNegotiator<NetconfClientSessionPreferences, NetconfClientSession, NetconfClientSessionListener>
}
@Override
- protected void handleMessage(NetconfHelloMessage netconfMessage) {
+ protected void handleMessage(NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
NetconfClientSession session = super.getSessionForHelloMessage(netconfMessage);
if (shouldUseExi(netconfMessage.getDocument())){
- logger.info("Netconf session: {} should use exi.", session);
+ logger.debug("Netconf session: {} should use exi.", session);
tryToStartExi(session);
} else {
- logger.info("Netconf session {} isn't capable using exi.", session);
+ logger.debug("Netconf session {} isn't capable using exi.", session);
negotiationSuccessful(session);
}
}
}
@Override
- protected NetconfClientSession getSession(NetconfClientSessionListener sessionListener, Channel channel, NetconfHelloMessage message) {
+ protected NetconfClientSession getSession(NetconfClientSessionListener sessionListener, Channel channel, NetconfHelloMessage message) throws NetconfDocumentedException {
return new NetconfClientSession(sessionListener, channel, extractSessionId(message.getDocument()),
NetconfMessageUtil.extractCapabilitiesFromHello(message.getDocument()));
}
package org.opendaylight.controller.netconf.client;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Sets;
+import io.netty.channel.Channel;
+import io.netty.util.Timer;
+import io.netty.util.concurrent.Promise;
import org.opendaylight.controller.netconf.api.NetconfClientSessionPreferences;
+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 org.openexi.proc.common.AlignmentType;
import org.openexi.proc.common.EXIOptions;
import org.openexi.proc.common.EXIOptionsException;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Sets;
-
-import io.netty.channel.Channel;
-import io.netty.util.Timer;
-import io.netty.util.concurrent.Promise;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class NetconfClientSessionNegotiatorFactory implements SessionNegotiatorFactory<NetconfMessage, NetconfClientSession, NetconfClientSessionListener> {
private final long connectionTimeoutMillis;
private final Timer timer;
private final EXIOptions options;
+ private static final Logger logger = LoggerFactory.getLogger(NetconfClientSessionNegotiatorFactory.class);
public NetconfClientSessionNegotiatorFactory(Timer timer,
Optional<NetconfHelloMessageAdditionalHeader> additionalHeader,
Promise<NetconfClientSession> promise) {
NetconfMessage startExiMessage = NetconfStartExiMessage.create(options, START_EXI_MESSAGE_ID);
- NetconfHelloMessage helloMessage = NetconfHelloMessage.createClientHello(CLIENT_CAPABILITIES, additionalHeader);
+ NetconfHelloMessage helloMessage = null;
+ try {
+ helloMessage = NetconfHelloMessage.createClientHello(CLIENT_CAPABILITIES, additionalHeader);
+ } catch (NetconfDocumentedException e) {
+ logger.error("Unable to create client hello message with capabilities {} and additional handler {}",CLIENT_CAPABILITIES,additionalHeader);
+ throw new IllegalStateException(e);
+ }
NetconfClientSessionPreferences proposal = new NetconfClientSessionPreferences(helloMessage,startExiMessage);
return new NetconfClientSessionNegotiator(proposal, promise, channel, timer,
org.opendaylight.controller.netconf.util.mapping,
org.opendaylight.controller.netconf.util.osgi,
org.opendaylight.controller.netconf.util.xml,
+ org.opendaylight.controller.netconf.util.exception,
org.opendaylight.controller.netconf.util.handler,
org.opendaylight.protocol.framework,
org.osgi.framework,
package org.opendaylight.controller.netconf.impl;
-import static org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider.NetconfOperationProviderUtil.getNetconfSessionIdForReporting;
-
-import java.util.Set;
-
+import com.google.common.collect.Sets;
+import io.netty.channel.Channel;
+import io.netty.util.Timer;
+import io.netty.util.concurrent.Promise;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfServerSessionPreferences;
import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
import org.opendaylight.protocol.framework.SessionListenerFactory;
import org.opendaylight.protocol.framework.SessionNegotiator;
import org.opendaylight.protocol.framework.SessionNegotiatorFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import com.google.common.collect.Sets;
+import java.util.Set;
-import io.netty.channel.Channel;
-import io.netty.util.Timer;
-import io.netty.util.concurrent.Promise;
+import static org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider.NetconfOperationProviderUtil.getNetconfSessionIdForReporting;
public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorFactory<NetconfHelloMessage, NetconfServerSession, NetconfServerSessionListener> {
private final long connectionTimeoutMillis;
private final DefaultCommitNotificationProducer commitNotificationProducer;
private final SessionMonitoringService monitoringService;
+ private static final Logger logger = LoggerFactory.getLogger(NetconfServerSessionNegotiatorFactory.class);
public NetconfServerSessionNegotiatorFactory(Timer timer, NetconfOperationProvider netconfOperationProvider,
SessionIdProvider idProvider, long connectionTimeoutMillis,
getNetconfSessionIdForReporting(sessionId));
CapabilityProvider capabilityProvider = new CapabilityProviderImpl(netconfOperationServiceSnapshot);
- NetconfServerSessionPreferences proposal = new NetconfServerSessionPreferences(
- createHelloMessage(sessionId, capabilityProvider), sessionId);
+ NetconfServerSessionPreferences proposal = null;
+ try {
+ proposal = new NetconfServerSessionPreferences(
+ createHelloMessage(sessionId, capabilityProvider), sessionId);
+ } catch (NetconfDocumentedException e) {
+ logger.error("Unable to create hello mesage for session {} with capability provider {}", sessionId,capabilityProvider);
+ throw new IllegalStateException(e);
+ }
NetconfServerSessionListenerFactory sessionListenerFactory = new NetconfServerSessionListenerFactory(
commitNotificationProducer, monitoringService,
sessionListenerFactory.getSessionListener(), connectionTimeoutMillis);
}
- private NetconfHelloMessage createHelloMessage(long sessionId, CapabilityProvider capabilityProvider) {
+ private NetconfHelloMessage createHelloMessage(long sessionId, CapabilityProvider capabilityProvider) throws NetconfDocumentedException {
return NetconfHelloMessage.createServerHello(Sets.union(capabilityProvider.getCapabilities(), DEFAULT_CAPABILITIES), sessionId);
}
package org.opendaylight.controller.netconf.impl.mapping.operations;
-import java.io.InputStream;
-import java.util.Map;
-
+import com.google.common.base.Preconditions;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
+import java.io.InputStream;
public class DefaultCommit extends AbstractNetconfOperation {
}
private boolean isCommitWithoutNotification(Document message) {
- XmlElement xmlElement = XmlElement.fromDomElementWithExpected(message.getDocumentElement(),
- XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ XmlElement xmlElement = null;
+ try {
+ xmlElement = XmlElement.fromDomElementWithExpected(message.getDocumentElement(),
+ XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ } catch (NetconfDocumentedException e) {
+ logger.trace("Commit operation is not valid due to {}",e);
+ return false;
+ }
String attr = xmlElement.getAttribute(NOTIFY_ATTR);
getConfigMessage, null);
XmlElement dataElement;
- try {
- XmlElement xmlElement = XmlElement.fromDomElementWithExpected(responseDocument.getDocumentElement(),
- XmlNetconfConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- dataElement = xmlElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY);
- } catch (IllegalArgumentException e) {
- final String msg = "Unexpected response from get-config operation";
- logger.warn(msg, e);
- Map<String, String> info = Maps.newHashMap();
- info.put(NetconfDocumentedException.ErrorTag.operation_failed.toString(), e.getMessage());
- throw new NetconfDocumentedException(msg, e, NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error, info);
- }
-
+ XmlElement xmlElement = XmlElement.fromDomElementWithExpected(responseDocument.getDocumentElement(),
+ XmlNetconfConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ dataElement = xmlElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY);
return dataElement.getDomElement();
}
package org.opendaylight.controller.netconf.impl.mapping.operations;
-import java.util.HashMap;
-import java.util.Map;
-
+import com.google.common.base.Optional;
+import com.google.common.collect.Maps;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
+import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
import org.opendaylight.controller.netconf.util.mapping.AbstractLastNetconfOperation;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.base.Optional;
-import com.google.common.collect.Maps;
+import java.util.Map;
public final class DefaultGetSchema extends AbstractLastNetconfOperation {
public static final String GET_SCHEMA = "get-schema";
protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
GetSchemaEntry entry;
- try {
- entry = new GetSchemaEntry(xml);
- } catch (final IllegalArgumentException e) {
- logger.warn("Error parsing xml", e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(NetconfDocumentedException.ErrorTag.bad_attribute.name(), e.getMessage());
- throw new NetconfDocumentedException(e.getMessage(), e, NetconfDocumentedException.ErrorType.rpc,
- NetconfDocumentedException.ErrorTag.bad_attribute, NetconfDocumentedException.ErrorSeverity.error,
- errorInfo);
- } catch (final IllegalStateException e) {
- logger.warn("Error parsing xml", e);
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(NetconfDocumentedException.ErrorTag.bad_attribute.name(), e.getMessage());
- throw new NetconfDocumentedException(e.getMessage(), e, NetconfDocumentedException.ErrorType.rpc,
- NetconfDocumentedException.ErrorTag.bad_attribute, NetconfDocumentedException.ErrorSeverity.error,
- errorInfo);
- }
+ entry = new GetSchemaEntry(xml);
String schema;
try {
private final String identifier;
private final Optional<String> version;
- GetSchemaEntry(XmlElement getSchemaElement) {
+ GetSchemaEntry(XmlElement getSchemaElement) throws NetconfDocumentedException {
getSchemaElement.checkName(GET_SCHEMA);
getSchemaElement.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_YANG_IETF_NETCONF_MONITORING);
- XmlElement identifierElement = getSchemaElement.getOnlyChildElementWithSameNamespace(IDENTIFIER);
+ XmlElement identifierElement = null;
+ try {
+ identifierElement = getSchemaElement.getOnlyChildElementWithSameNamespace(IDENTIFIER);
+ } catch (MissingNameSpaceException e) {
+ logger.trace("Can't get identifier element as only child element with same namespace due to {}",e);
+ throw NetconfDocumentedException.wrap(e);
+ }
identifier = identifierElement.getTextContent();
Optional<XmlElement> versionElement = getSchemaElement
.getOnlyChildElementWithSameNamespaceOptionally(VERSION);
}
private NetconfOperationExecution getNetconfOperationWithHighestPriority(
- Document message, NetconfServerSession session) {
+ Document message, NetconfServerSession session) throws NetconfDocumentedException {
TreeMap<HandlingPriority, NetconfOperation> sortedByPriority = getSortedNetconfOperationsWithCanHandle(
message, session);
}
private TreeMap<HandlingPriority, NetconfOperation> getSortedNetconfOperationsWithCanHandle(Document message,
- NetconfServerSession session) {
+ NetconfServerSession session) throws NetconfDocumentedException {
TreeMap<HandlingPriority, NetconfOperation> sortedPriority = Maps.newTreeMap();
for (NetconfOperation netconfOperation : allNetconfOperations) {
return sortedPriority;
}
+ public static final NetconfOperationChainedExecution EXECUTION_TERMINATION_POINT = new NetconfOperationChainedExecution() {
+ @Override
+ public boolean isExecutionTermination() {
+ return true;
+ }
+
+ @Override
+ public Document execute(Document requestMessage) throws NetconfDocumentedException {
+ throw new NetconfDocumentedException("This execution represents the termination point in operation execution and cannot be executed itself",
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
+ };
+
private static class NetconfOperationExecution implements NetconfOperationChainedExecution {
private final NetconfOperation netconfOperation;
private NetconfOperationChainedExecution subsequentExecution;
import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import org.opendaylight.controller.netconf.client.test.TestingNetconfClient;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
import org.opendaylight.controller.netconf.StubUserManager;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
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;
}
}
- private void assertIsOK(final Document rpcReply) {
+ private void assertIsOK(final Document rpcReply) throws NetconfDocumentedException {
assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
}
- private Document assertGetConfigWorks(final TestingNetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException {
+ private Document assertGetConfigWorks(final TestingNetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException {
return assertGetConfigWorks(netconfClient, this.getConfig);
}
private Document assertGetConfigWorks(final TestingNetconfClient netconfClient, final NetconfMessage getConfigMessage)
- throws InterruptedException, ExecutionException, TimeoutException {
+ throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException {
final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
assertNotNull(rpcReply);
assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
* @param requestMessage
* @return
*/
- HandlingPriority canHandle(Document requestMessage);
+ HandlingPriority canHandle(Document message) throws NetconfDocumentedException;
/**
* Execute current netconf operation and trigger execution of subsequent
org.opendaylight.controller.netconf.api,
org.opendaylight.controller.netconf.mapping.api,
org.opendaylight.controller.netconf.util.mapping,
+ org.opendaylight.controller.netconf.util.exception,
org.osgi.framework,
org.slf4j,
org.w3c.dom,
*/
package org.opendaylight.controller.netconf.monitoring;
-import java.util.Map;
-
+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;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
+import java.util.Map;
public class Get extends AbstractNetconfOperation {
this.netconfMonitor = netconfMonitor;
}
- private Element getPlaceholder(Document innerResult) {
+ private Element getPlaceholder(Document innerResult) throws NetconfDocumentedException {
try {
- XmlElement rootElement = XmlElement.fromDomElementWithExpected(innerResult.getDocumentElement(),
- XmlNetconfConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ XmlElement rootElement = null;
+ rootElement = XmlElement.fromDomElementWithExpected(innerResult.getDocumentElement(),
+ XmlNetconfConstants.RPC_REPLY_KEY, XmlNetconfConstants.RFC4741_TARGET_NAMESPACE);
return rootElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY).getDomElement();
} catch (RuntimeException e) {
throw new IllegalArgumentException(String.format(
*/
package org.opendaylight.controller.netconf.ssh;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.util.concurrent.atomic.AtomicLong;
-import javax.annotation.concurrent.ThreadSafe;
import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
import org.opendaylight.controller.netconf.ssh.threads.SocketThread;
import org.opendaylight.controller.usermanager.IUserManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.annotation.concurrent.ThreadSafe;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.util.concurrent.atomic.AtomicLong;
+
@ThreadSafe
public class NetconfSSHServer implements Runnable {
try {
SocketThread.start(ss.accept(), clientAddress, sesssionId.incrementAndGet(),authProvider);
} catch (IOException e) {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
+ logger.error("Exception occurred during socket thread initialization {}",e);
}
}
}
org.opendaylight.controller.netconf.util.mapping,
org.opendaylight.controller.netconf.util.messages,
org.opendaylight.controller.netconf.util.handler,
- org.opendaylight.controller.netconf.util.handler.*,</Export-Package>
+ org.opendaylight.controller.netconf.util.handler.*,
+ org.opendaylight.controller.netconf.util.exception,</Export-Package>
<Import-Package>com.google.common.base,
com.google.common.collect,
ch.ethz.ssh2,
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.NetconfSessionListener;
import org.opendaylight.controller.netconf.api.NetconfSessionPreferences;
}
@Override
- protected void handleMessage(NetconfHelloMessage netconfMessage) {
- S session = getSessionForHelloMessage(netconfMessage);
+ protected void handleMessage(NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
+ S session = getSessionForHelloMessage(netconfMessage) ;
negotiationSuccessful(session);
}
- protected final S getSessionForHelloMessage(NetconfHelloMessage netconfMessage) {
+ protected final S getSessionForHelloMessage(NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
Preconditions.checkNotNull(netconfMessage, "netconfMessage");
final Document doc = netconfMessage.getDocument();
return channel.pipeline().replace(handlerKey, handlerKey, decoder);
}
- protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message);
+ protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message) throws NetconfDocumentedException;
protected synchronized void changeState(final State newState) {
logger.debug("Changing state from : {} to : {}", state, newState);
package org.opendaylight.controller.netconf.util;
import com.google.common.base.Preconditions;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
return (doc == null) ? null : new NetconfMessage(doc);
}
- public static Document checkIsMessageOk(NetconfMessage responseMessage) {
- return checkIsMessageOk(responseMessage.getDocument());
- }
-
- public static Document checkIsMessageOk(Document response) {
+ public static Document checkIsMessageOk(Document response) throws NetconfDocumentedException {
XmlElement element = XmlElement.fromDomDocument(response);
Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
element = element.getOnlyChildElement();
--- /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.util.exception;
+
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+
+import java.util.Collections;
+import java.util.Map;
+
+public class MissingNameSpaceException extends NetconfDocumentedException {
+
+ public MissingNameSpaceException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
+ }
+
+ public MissingNameSpaceException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
+ super(message,errorType,errorTag,errorSeverity,errorInfo);
+ }
+}
--- /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.util.exception;
+
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+
+import java.util.Collections;
+import java.util.Map;
+
+public class UnexpectedElementException extends NetconfDocumentedException {
+
+ public UnexpectedElementException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
+ }
+
+ public UnexpectedElementException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
+ super(message,errorType,errorTag,errorSeverity,errorInfo);
+ }
+}
--- /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.util.exception;
+
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+
+import java.util.Collections;
+import java.util.Map;
+
+public class UnexpectedNamespaceException extends NetconfDocumentedException {
+
+ public UnexpectedNamespaceException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
+ }
+
+ public UnexpectedNamespaceException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
+ super(message,errorType,errorTag,errorSeverity,errorInfo);
+ }
+}
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.base.Preconditions;
-
public abstract class AbstractLastNetconfOperation extends AbstractNetconfOperation {
protected AbstractLastNetconfOperation(String netconfSessionIdForReporting) {
@Override
protected Element handle(Document document, XmlElement operationElement,
NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
- Preconditions.checkArgument(subsequentOperation.isExecutionTermination(),
- "No netconf operation expected to be subsequent to %s, but is %s", this, subsequentOperation);
+ if (!subsequentOperation.isExecutionTermination()){
+ throw new NetconfDocumentedException(String.format("No netconf operation expected to be subsequent to %s, but is %s", this, subsequentOperation),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.malformed_message,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
return handleWithNoSubsequentOperations(document, operationElement);
}
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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public abstract class AbstractNetconfOperation implements NetconfOperation {
private final String netconfSessionIdForReporting;
+ private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfOperation.class);
protected AbstractNetconfOperation(String netconfSessionIdForReporting) {
this.netconfSessionIdForReporting = netconfSessionIdForReporting;
}
@Override
- public HandlingPriority canHandle(Document message) {
- OperationNameAndNamespace operationNameAndNamespace = new OperationNameAndNamespace(message);
+ public HandlingPriority canHandle(Document message) throws NetconfDocumentedException {
+ OperationNameAndNamespace operationNameAndNamespace = null;
+ operationNameAndNamespace = new OperationNameAndNamespace(message);
return canHandle(operationNameAndNamespace.getOperationName(), operationNameAndNamespace.getNamespace());
}
public static final class OperationNameAndNamespace {
private final String operationName, namespace;
- public OperationNameAndNamespace(Document message) {
- XmlElement requestElement = getRequestElementWithCheck(message);
+ public OperationNameAndNamespace(Document message) throws NetconfDocumentedException {
+ XmlElement requestElement = null;
+ requestElement = getRequestElementWithCheck(message);
XmlElement operationElement = requestElement.getOnlyChildElement();
operationName = operationElement.getName();
}
}
- protected static XmlElement getRequestElementWithCheck(Document message) {
+ protected static XmlElement getRequestElementWithCheck(Document message) throws NetconfDocumentedException {
return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), XmlNetconfConstants.RPC_KEY,
XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
}
package org.opendaylight.controller.netconf.util.messages;
-import java.util.Set;
-
+import com.google.common.base.Optional;
+import com.google.common.collect.Sets;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.base.Optional;
-import com.google.common.collect.Sets;
+import java.util.Set;
/**
* NetconfMessage that can carry additional header with session metadata. See {@link org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader}
private final NetconfHelloMessageAdditionalHeader additionalHeader;
- public NetconfHelloMessage(Document doc, NetconfHelloMessageAdditionalHeader additionalHeader) {
+ public NetconfHelloMessage(Document doc, NetconfHelloMessageAdditionalHeader additionalHeader) throws NetconfDocumentedException {
super(doc);
checkHelloMessage(doc);
this.additionalHeader = additionalHeader;
}
- public NetconfHelloMessage(Document doc) {
+ public NetconfHelloMessage(Document doc) throws NetconfDocumentedException {
this(doc, null);
}
return additionalHeader== null ? Optional.<NetconfHelloMessageAdditionalHeader>absent() : Optional.of(additionalHeader);
}
- private static void checkHelloMessage(Document doc) {
- try {
- XmlElement.fromDomElementWithExpected(doc.getDocumentElement(), HELLO_TAG,
- XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ private static void checkHelloMessage(Document doc) throws NetconfDocumentedException {
+ XmlElement.fromDomElementWithExpected(doc.getDocumentElement(), HELLO_TAG,
+ XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- } catch (IllegalArgumentException | IllegalStateException e) {
- throw new IllegalArgumentException(String.format(
- "Hello message invalid format, should contain %s tag from namespace %s, but is: %s", HELLO_TAG,
- XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlUtil.toString(doc)), e);
- }
}
public static NetconfHelloMessage createClientHello(Iterable<String> capabilities,
- Optional<NetconfHelloMessageAdditionalHeader> additionalHeaderOptional) {
+ Optional<NetconfHelloMessageAdditionalHeader> additionalHeaderOptional) throws NetconfDocumentedException {
Document doc = createHelloMessageDoc(capabilities);
return additionalHeaderOptional.isPresent() ? new NetconfHelloMessage(doc, additionalHeaderOptional.get())
: new NetconfHelloMessage(doc);
return doc;
}
- public static NetconfHelloMessage createServerHello(Set<String> capabilities, long sessionId) {
+ public static NetconfHelloMessage createServerHello(Set<String> capabilities, long sessionId) throws NetconfDocumentedException {
Document doc = createHelloMessageDoc(capabilities);
Element sessionIdElement = doc.createElement(XmlNetconfConstants.SESSION_ID);
sessionIdElement.setTextContent(Long.toString(sessionId));
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import javax.annotation.Nullable;
public final class NetconfMessageUtil {
+ private static final Logger logger = LoggerFactory.getLogger(NetconfMessageUtil.class);
+
private NetconfMessageUtil() {}
- public static boolean isOKMessage(NetconfMessage message) {
+ public static boolean isOKMessage(NetconfMessage message) throws NetconfDocumentedException {
return isOKMessage(message.getDocument());
}
- public static boolean isOKMessage(Document document) {
+ public static boolean isOKMessage(Document document) throws NetconfDocumentedException {
return isOKMessage(XmlElement.fromDomDocument(document));
}
- public static boolean isOKMessage(XmlElement xmlElement) {
+ public static boolean isOKMessage(XmlElement xmlElement) throws NetconfDocumentedException {
if(xmlElement.getChildElements().size() != 1) {
return false;
}
return xmlElement.getOnlyChildElement().getName().equals(XmlNetconfConstants.OK);
}
- public static boolean isErrorMessage(NetconfMessage message) {
+ public static boolean isErrorMessage(NetconfMessage message) throws NetconfDocumentedException {
return isErrorMessage(message.getDocument());
}
- public static boolean isErrorMessage(Document document) {
+ public static boolean isErrorMessage(Document document) throws NetconfDocumentedException {
return isErrorMessage(XmlElement.fromDomDocument(document));
}
- public static boolean isErrorMessage(XmlElement xmlElement) {
+ public static boolean isErrorMessage(XmlElement xmlElement) throws NetconfDocumentedException {
if(xmlElement.getChildElements().size() != 1) {
return false;
}
return xmlElement.getOnlyChildElement().getName().equals(XmlNetconfConstants.RPC_ERROR);
}
- public static Collection<String> extractCapabilitiesFromHello(Document doc) {
+ public static Collection<String> extractCapabilitiesFromHello(Document doc) throws NetconfDocumentedException {
XmlElement responseElement = XmlElement.fromDomDocument(doc);
XmlElement capabilitiesElement = responseElement
.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.CAPABILITIES);
@Override
public String apply(@Nullable XmlElement input) {
// Trim possible leading/tailing whitespace
- return input.getTextContent().trim();
+ try {
+ return input.getTextContent().trim();
+ } catch (NetconfDocumentedException e) {
+ logger.trace("Error fetching inpit text content becauese {}",e);
+ return null;
+ }
}
});
package org.opendaylight.controller.netconf.util.xml;
import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
+import org.opendaylight.controller.netconf.util.exception.UnexpectedElementException;
+import org.opendaylight.controller.netconf.util.exception.UnexpectedNamespaceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public final class XmlElement {
private final Element element;
+ private static final Logger logger = LoggerFactory.getLogger(XmlElement.class);
private XmlElement(Element element) {
this.element = element;
return new XmlElement(xml.getDocumentElement());
}
- public static XmlElement fromString(String s) {
+ public static XmlElement fromString(String s) throws NetconfDocumentedException {
try {
return new XmlElement(XmlUtil.readXmlToElement(s));
} catch (IOException | SAXException e) {
- throw new IllegalArgumentException("Unable to create from " + s, e);
+ throw NetconfDocumentedException.wrap(e);
}
}
- public static XmlElement fromDomElementWithExpected(Element element, String expectedName) {
+ public static XmlElement fromDomElementWithExpected(Element element, String expectedName) throws NetconfDocumentedException {
XmlElement xmlElement = XmlElement.fromDomElement(element);
xmlElement.checkName(expectedName);
return xmlElement;
}
- public static XmlElement fromDomElementWithExpected(Element element, String expectedName, String expectedNamespace) {
+ public static XmlElement fromDomElementWithExpected(Element element, String expectedName, String expectedNamespace) throws NetconfDocumentedException {
XmlElement xmlElement = XmlElement.fromDomElementWithExpected(element, expectedName);
xmlElement.checkNamespace(expectedNamespace);
return xmlElement;
}
- private static Map<String, String> extractNamespaces(Element typeElement) {
+ private static Map<String, String> extractNamespaces(Element typeElement) throws NetconfDocumentedException {
Map<String, String> namespaces = new HashMap<>();
NamedNodeMap attributes = typeElement.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
if (attribKey.equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
prefix = "";
} else {
- Preconditions.checkState(attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY + ":"));
+ if (!attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY + ":")){
+ throw new NetconfDocumentedException("Attribute doesn't start with :",
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.invalid_value,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
prefix = attribKey.substring(XmlUtil.XMLNS_ATTRIBUTE_KEY.length() + 1);
}
namespaces.put(prefix, attribute.getNodeValue());
return namespaces;
}
- public void checkName(String expectedName) {
- Preconditions.checkArgument(getName().equals(expectedName), "Expected %s xml element but was %s", expectedName,
- getName());
+ public void checkName(String expectedName) throws UnexpectedElementException {
+ if (!getName().equals(expectedName)){
+ throw new UnexpectedElementException(String.format("Expected %s xml element but was %s", expectedName,
+ getName()),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
}
- public void checkNamespaceAttribute(String expectedNamespace) {
- Preconditions.checkArgument(getNamespaceAttribute().equals(expectedNamespace),
- "Unexpected namespace %s for element %s, should be %s", getNamespaceAttribute(), expectedNamespace);
+ public void checkNamespaceAttribute(String expectedNamespace) throws UnexpectedNamespaceException, MissingNameSpaceException {
+ if (!getNamespaceAttribute().equals(expectedNamespace))
+ {
+ throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s for element %s, should be %s",
+ getNamespaceAttribute(),
+ expectedNamespace),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
}
- public void checkNamespace(String expectedNamespace) {
- Preconditions.checkArgument(getNamespace().equals(expectedNamespace),
- "Unexpected namespace %s for element %s, should be %s", getNamespace(), expectedNamespace);
+ public void checkNamespace(String expectedNamespace) throws UnexpectedNamespaceException, MissingNameSpaceException {
+ if (!getNamespace().equals(expectedNamespace))
+ {
+ throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s for element %s, should be %s",
+ getNamespace(),
+ expectedNamespace),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
}
public String getName() {
return getChildElementsInternal(new ElementFilteringStrategy() {
@Override
public boolean accept(Element e) {
- return XmlElement.fromDomElement(e).getNamespace().equals(namespace);
+ try {
+ return XmlElement.fromDomElement(e).getNamespace().equals(namespace);
+ } catch (MissingNameSpaceException e1) {
+ return false;
+ }
}
});
});
}
- public XmlElement getOnlyChildElement(String childName) {
+ public XmlElement getOnlyChildElement(String childName) throws NetconfDocumentedException {
List<XmlElement> nameElements = getChildElements(childName);
- Preconditions.checkState(nameElements.size() == 1, "One element " + childName + " expected in " + toString());
+ if (nameElements.size() != 1){
+ throw new NetconfDocumentedException("One element " + childName + " expected in " + toString(),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.invalid_value,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
return nameElements.get(0);
}
}
}
- public XmlElement getOnlyChildElementWithSameNamespace(String childName) {
+ public XmlElement getOnlyChildElementWithSameNamespace(String childName) throws NetconfDocumentedException {
return getOnlyChildElement(childName, getNamespace());
}
}
}
- public XmlElement getOnlyChildElementWithSameNamespace() {
+ public XmlElement getOnlyChildElementWithSameNamespace() throws NetconfDocumentedException {
XmlElement childElement = getOnlyChildElement();
childElement.checkNamespace(getNamespace());
return childElement;
}
}
- public XmlElement getOnlyChildElement(final String childName, String namespace) {
+ public XmlElement getOnlyChildElement(final String childName, String namespace) throws NetconfDocumentedException {
List<XmlElement> children = getChildElementsWithinNamespace(namespace);
children = Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
@Override
return xmlElement.getName().equals(childName);
}
}));
- Preconditions.checkState(children.size() == 1, "One element %s:%s expected in %s but was %s", namespace,
- childName, toString(), children.size());
+ if (children.size() != 1){
+ throw new NetconfDocumentedException(String.format("One element %s:%s expected in %s but was %s", namespace,
+ childName, toString(), children.size()),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.invalid_value,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
+
return children.get(0);
}
- public XmlElement getOnlyChildElement() {
+ public XmlElement getOnlyChildElement() throws NetconfDocumentedException {
List<XmlElement> children = getChildElements();
- Preconditions.checkState(children.size() == 1, "One element expected in %s but was %s", toString(),
- children.size());
+ if (children.size() != 1){
+ throw new NetconfDocumentedException(String.format( "One element expected in %s but was %s", toString(),
+ children.size()),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.invalid_value,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
return children.get(0);
}
- public String getTextContent() {
+ public String getTextContent() throws NetconfDocumentedException {
Node textChild = element.getFirstChild();
- Preconditions.checkNotNull(textChild, "Child node expected, got null for " + getName() + " : " + element);
- Preconditions.checkState(textChild instanceof Text, getName() + " should contain text." +
- Text.class.getName() + " expected, got " + textChild);
+ if (null == textChild){
+ throw new NetconfDocumentedException(String.format( "Child node expected, got null for " + getName() + " : " + element),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.invalid_value,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
+ if (!(textChild instanceof Text)){
+ throw new NetconfDocumentedException(String.format(getName() + " should contain text." +
+ Text.class.getName() + " expected, got " + textChild),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.invalid_value,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
String content = textChild.getTextContent();
// Trim needed
return content.trim();
}
- public String getNamespaceAttribute() {
+ public String getNamespaceAttribute() throws MissingNameSpaceException {
String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY);
- Preconditions.checkState(attribute != null && !attribute.equals(""), "Element %s must specify namespace",
- toString());
+ if (attribute == null || attribute.equals("")){
+ throw new MissingNameSpaceException(String.format("Element %s must specify namespace",
+ toString()),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
return attribute;
}
- public String getNamespace() {
+ public String getNamespace() throws MissingNameSpaceException {
String namespaceURI = element.getNamespaceURI();
- Preconditions.checkState(namespaceURI != null, "No namespace defined for %s", this);
+ if (namespaceURI == null || namespaceURI.equals("")){
+ throw new MissingNameSpaceException(String.format("No namespace defined for %s", this),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.operation_failed,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
return namespaceURI;
}
final StringBuilder sb = new StringBuilder("XmlElement{");
sb.append("name='").append(getName()).append('\'');
if (element.getNamespaceURI() != null) {
- sb.append(", namespace='").append(getNamespace()).append('\'');
+ try {
+ sb.append(", namespace='").append(getNamespace()).append('\'');
+ } catch (MissingNameSpaceException e) {
+ logger.trace("Missing namespace for element.");
+ }
}
sb.append('}');
return sb.toString();
* namespace is returned with empty string as key. If no default namespace
* is found value will be null.
*/
- public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() {
+ public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() throws NetconfDocumentedException {
Map<String, String> namespaces = extractNamespaces(element);
String textContent = getTextContent();
int indexOfColon = textContent.indexOf(':');
return Maps.immutableEntry(prefix, namespaces.get(prefix));
}
- public List<XmlElement> getChildElementsWithSameNamespace(final String childName) {
+ public List<XmlElement> getChildElementsWithSameNamespace(final String childName) throws MissingNameSpaceException {
List<XmlElement> children = getChildElementsWithinNamespace(getNamespace());
return Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
@Override
}
public void checkUnrecognisedElements(List<XmlElement> recognisedElements,
- XmlElement... additionalRecognisedElements) {
+ XmlElement... additionalRecognisedElements) throws NetconfDocumentedException {
List<XmlElement> childElements = getChildElements();
childElements.removeAll(recognisedElements);
for (XmlElement additionalRecognisedElement : additionalRecognisedElements) {
childElements.remove(additionalRecognisedElement);
}
- Preconditions.checkState(childElements.isEmpty(), "Unrecognised elements %s in %s", childElements, this);
+ if (!childElements.isEmpty()){
+ throw new NetconfDocumentedException(String.format("Unrecognised elements %s in %s", childElements, this),
+ NetconfDocumentedException.ErrorType.application,
+ NetconfDocumentedException.ErrorTag.invalid_value,
+ NetconfDocumentedException.ErrorSeverity.error);
+ }
}
- public void checkUnrecognisedElements(XmlElement... additionalRecognisedElements) {
- checkUnrecognisedElements(Collections.<XmlElement> emptyList(), additionalRecognisedElements);
+ public void checkUnrecognisedElements(XmlElement... additionalRecognisedElements) throws NetconfDocumentedException {
+ checkUnrecognisedElements(Collections.<XmlElement>emptyList(), additionalRecognisedElements);
}
@Override
public boolean hasNamespace() {
try {
getNamespaceAttribute();
- } catch (IllegalStateException e) {
+ } catch (MissingNameSpaceException e) {
try {
getNamespace();
- } catch (IllegalStateException e1) {
+ } catch (MissingNameSpaceException e1) {
return false;
}
return true;
public static final String SESSION_ID = "session-id";
//
+ // TODO duplicate
+ public static final String RFC4741_TARGET_NAMESPACE = "urn:ietf:params:xml:ns:netconf:base:1.0";
public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 = "urn:ietf:params:xml:ns:netconf:base:1.0";
public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_1 = "urn:ietf:params:xml:ns:netconf:base:1.1";
public static final String URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0 = "urn:ietf:params:xml:ns:netconf:exi:1.0";
package org.opendaylight.controller.netconf.util;
import org.junit.Test;
-import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
public void testConflictingVersionDetection() throws Exception {
Document document = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/netconfMessages/conflictingversion/conflictingVersionResponse.xml"));
try{
- NetconfUtil.checkIsMessageOk(new NetconfMessage(document));
+ NetconfUtil.checkIsMessageOk(document);
fail();
}catch(IllegalStateException e){
assertThat(e.getMessage(), containsString("Optimistic lock failed. Expected parent version 21, was 18"));