private final CurrentSchemaContext schemaContext;
private final TransactionProvider transactionProvider;
- public EditConfig(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext, final TransactionProvider transactionProvider) {
+ public EditConfig(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
+ final TransactionProvider transactionProvider) {
super(netconfSessionIdForReporting);
this.schemaContext = schemaContext;
this.transactionProvider = transactionProvider;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
+ throws DocumentedException {
final Datastore targetDatastore = extractTargetParameter(operationElement);
if (targetDatastore == Datastore.running) {
throw new DocumentedException("edit-config on running datastore is not supported",
final DataSchemaNode schemaNode = getSchemaNodeFromNamespace(ns, element).get();
final DataTreeChangeTracker changeTracker = new DataTreeChangeTracker(defaultAction);
- final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider = new EditOperationStrategyProvider(changeTracker);
+ final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider =
+ new EditOperationStrategyProvider(changeTracker);
parseIntoNormalizedNode(schemaNode, element, editOperationStrategyProvider);
executeOperations(changeTracker);
}
}
- private void executeChange(final DOMDataReadWriteTransaction rwtx, final DataTreeChange change) throws DocumentedException {
+ private static void executeChange(final DOMDataReadWriteTransaction rwtx, final DataTreeChange change)
+ throws DocumentedException {
final YangInstanceIdentifier path = YangInstanceIdentifier.create(change.getPath());
final NormalizedNode<?, ?> changeData = change.getChangeRoot();
switch (change.getAction()) {
try {
final Optional<NormalizedNode<?, ?>> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
if (readResult.isPresent()) {
- throw new DocumentedException("Data already exists, cannot execute CREATE operation", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, ErrorSeverity.ERROR);
+ throw new DocumentedException("Data already exists, cannot execute CREATE operation",
+ ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, ErrorSeverity.ERROR);
}
mergeParentMap(rwtx, path, changeData);
rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
try {
final Optional<NormalizedNode<?, ?>> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
if (!readResult.isPresent()) {
- throw new DocumentedException("Data is missing, cannot execute DELETE operation", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
+ throw new DocumentedException("Data is missing, cannot execute DELETE operation",
+ ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
}
rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
} catch (final ReadFailedException e) {
}
}
- private void mergeParentMap(final DOMDataReadWriteTransaction rwtx, final YangInstanceIdentifier path,
- final NormalizedNode change) {
+ private static void mergeParentMap(final DOMDataReadWriteTransaction rwtx, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> change) {
if (change instanceof MapEntryNode) {
final YangInstanceIdentifier mapNodeYid = path.getParent();
//merge empty map
}
}
- private NormalizedNode parseIntoNormalizedNode(final DataSchemaNode schemaNode, final XmlElement element,
- final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider) {
-
-
+ private NormalizedNode<?, ?> parseIntoNormalizedNode(final DataSchemaNode schemaNode, final XmlElement element,
+ final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider) {
if (schemaNode instanceof ContainerSchemaNode) {
return DomToNormalizedNodeParserFactory
.getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext(), editOperationStrategyProvider)
throw new UnsupportedOperationException("implement exception if parse fails");
}
- private Optional<DataSchemaNode> getSchemaNodeFromNamespace(final String namespace, final XmlElement element) throws DocumentedException{
+ private Optional<DataSchemaNode> getSchemaNodeFromNamespace(final String namespace, final XmlElement element)
+ throws DocumentedException {
Optional<DataSchemaNode> dataSchemaNode = Optional.absent();
try {
- //returns module with newest revision since findModuleByNamespace returns a set of modules and we only need the newest one
+ // returns module with newest revision since findModuleByNamespace returns a set of modules and we only
+ // need the newest one
final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(new URI(namespace), null);
if (module == null) {
// no module is present with this namespace
return dataSchemaNode;
}
- private Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException {
+ private static Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException {
final NodeList elementsByTagName = operationElement.getDomElement().getElementsByTagName(TARGET_KEY);
// Direct lookup instead of using XmlElement class due to performance
if (elementsByTagName.getLength() == 0) {
- final Map<String, String> errorInfo = ImmutableMap.of("bad-attribute", TARGET_KEY, "bad-element", OPERATION_NAME);
- throw new DocumentedException("Missing target element",
- ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE, ErrorSeverity.ERROR, errorInfo);
+ final Map<String, String> errorInfo = ImmutableMap.of("bad-attribute", TARGET_KEY, "bad-element",
+ OPERATION_NAME);
+ throw new DocumentedException("Missing target element", ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE,
+ ErrorSeverity.ERROR, errorInfo);
} else if (elementsByTagName.getLength() > 1) {
- throw new DocumentedException("Multiple target elements", ErrorType.RPC, ErrorTag.UNKNOWN_ATTRIBUTE, ErrorSeverity.ERROR);
+ throw new DocumentedException("Multiple target elements", ErrorType.RPC, ErrorTag.UNKNOWN_ATTRIBUTE,
+ ErrorSeverity.ERROR);
} else {
final XmlElement targetChildNode = XmlElement.fromDomElement((Element) elementsByTagName.item(0)).getOnlyChildElement();
return Datastore.valueOf(targetChildNode.getName());
}
}
- private ModifyAction getDefaultOperation(final XmlElement operationElement) throws DocumentedException {
+ private static ModifyAction getDefaultOperation(final XmlElement operationElement) throws DocumentedException {
final NodeList elementsByTagName = operationElement.getDomElement().getElementsByTagName(DEFAULT_OPERATION_KEY);
- if(elementsByTagName.getLength() == 0) {
+ if (elementsByTagName.getLength() == 0) {
return ModifyAction.MERGE;
- } else if(elementsByTagName.getLength() > 1) {
- throw new DocumentedException("Multiple " + DEFAULT_OPERATION_KEY + " elements",
- ErrorType.RPC, ErrorTag.UNKNOWN_ATTRIBUTE, ErrorSeverity.ERROR);
+ } else if (elementsByTagName.getLength() > 1) {
+ throw new DocumentedException("Multiple " + DEFAULT_OPERATION_KEY + " elements", ErrorType.RPC,
+ ErrorTag.UNKNOWN_ATTRIBUTE, ErrorSeverity.ERROR);
} else {
return ModifyAction.fromXmlValue(elementsByTagName.item(0).getTextContent());
}
}
- private XmlElement getElement(final XmlElement operationElement, final String elementName) throws DocumentedException {
+ private static XmlElement getElement(final XmlElement operationElement, final String elementName)
+ throws DocumentedException {
final Optional<XmlElement> childNode = operationElement.getOnlyChildElementOptionally(elementName);
if (!childNode.isPresent()) {
throw new DocumentedException(elementName + " element is missing",
<version>${project.version}</version>
<classifier>features</classifier>
<type>xml</type>
- <scope>runtime</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>features-netconf</artifactId>
<version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+
+ <!-- netconf features -->
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>features4-netconf</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-aaa-netconf-plugin</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-aaa-netconf-plugin-no-cluster</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-config-netconf-connector</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-all</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-api</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-client</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-impl</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-mapping-api</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-mdsal</artifactId>
+ <version>1.6.0-SNAPSHOT</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-monitoring</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-netty-util</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-notifications-api</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-notifications-impl</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
<classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-ssh</artifactId>
+ <version>${project.version}</version>
<type>xml</type>
- <scope>runtime</scope>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-tcp</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-util</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+
+ <!-- netconf-connector features -->
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>features4-netconf-connector</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-message-bus</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>odl-netconf-clustered-topology</artifactId>
<version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-connector</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-connector-all</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-connector-ssh</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
<classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-callhome-ssh</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-console</artifactId>
+ <version>${project.version}</version>
<type>xml</type>
- <scope>runtime</scope>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-netconf-topology</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+
+ <!-- yanglib features -->
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>features4-yanglib</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-yanglib</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
</dependency>
</dependencies>
</dependencyManagement>
import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup.NetconfTopologySetupBuilder;
import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopologyBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
final ClusterSingletonServiceProvider clusterSingletonServiceProvider,
final BindingAwareBroker bindingAwareBroker,
final ScheduledThreadPool keepaliveExecutor, final ThreadPool processingExecutor,
- final Broker domBroker, final ActorSystemProvider actorSystemProvider, final EventExecutor eventExecutor,
- final NetconfClientDispatcher clientDispatcher, final String topologyId,
- final int writeTxIdleTimeout) {
+ final Broker domBroker, final ActorSystemProvider actorSystemProvider,
+ final EventExecutor eventExecutor, final NetconfClientDispatcher clientDispatcher,
+ final String topologyId, final Config config) {
this.dataBroker = Preconditions.checkNotNull(dataBroker);
this.rpcProviderRegistry = Preconditions.checkNotNull(rpcProviderRegistry);
this.clusterSingletonServiceProvider = Preconditions.checkNotNull(clusterSingletonServiceProvider);
this.eventExecutor = Preconditions.checkNotNull(eventExecutor);
this.clientDispatcher = Preconditions.checkNotNull(clientDispatcher);
this.topologyId = Preconditions.checkNotNull(topologyId);
- this.writeTxIdleTimeout = Duration.apply(writeTxIdleTimeout, TimeUnit.SECONDS);
+ this.writeTxIdleTimeout = Duration.apply(config.getWriteTransactionIdleTimeout(), TimeUnit.SECONDS);
}
// Blueprint init method
<reference id="clientDispatcherDependency"
interface="org.opendaylight.netconf.client.NetconfClientDispatcher"
odl:type="netconf-client-dispatcher"/>
+ <odl:clustered-app-config
+ id="singletonConfig"
+ binding-class="org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config"
+ />
<bean id="netconfTopologyManager"
class="org.opendaylight.netconf.topology.singleton.impl.NetconfTopologyManager"
<argument ref="eventExecutor"/>
<argument ref="clientDispatcherDependency"/>
<argument value="topology-netconf"/>
- <argument value="0"/>
+ <argument ref="singletonConfig"/>
</bean>
<service ref="netconfTopologyManager"
interface="org.opendaylight.netconf.topology.singleton.api.NetconfTopologySingletonService"/>
--- /dev/null
+module netconf-clustered-topology-config {
+ yang-version 1;
+ namespace "urn:opendaylight:netconf:topology:singleton:config";
+ prefix nctc;
+
+ description
+ "Configuration for Netconf Clustered Topology";
+
+ revision "2017-04-19" {
+ description
+ "Initial revision.";
+ }
+
+ container config {
+ leaf write-transaction-idle-timeout {
+ type uint16;
+ default 0;
+ description "Idle time in seconds after which write transaction is cancelled
+ automatically. If 0, automatic cancellation is turned off.";
+ }
+ }
+}
\ No newline at end of file
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.ConfigBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
final EventExecutor eventExecutor = mock(EventExecutor.class);
final NetconfClientDispatcher clientDispatcher = mock(NetconfClientDispatcher.class);
+ final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(0).build();
netconfTopologyManager = new NetconfTopologyManager(dataBroker, rpcProviderRegistry,
clusterSingletonServiceProvider, bindingAwareBroker, keepaliveExecutor, processingExecutor, domBroker,
- actorSystemProvider, eventExecutor, clientDispatcher, topologyId, 0);
+ actorSystemProvider, eventExecutor, clientDispatcher, topologyId, config);
}
@Test
</execution>
</executions>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
</plugins>
</build>
public class CloseableUtil {
+ @SuppressWarnings("checkstyle:IllegalCatch")
public static void closeAll(Iterable<? extends AutoCloseable> autoCloseables) throws Exception {
Exception lastException = null;
for (AutoCloseable autoCloseable : autoCloseables) {
+ XmlUtil.toString(response));
}
- public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized, final DOMResult result, final SchemaPath schemaPath, final SchemaContext context)
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized, final DOMResult result,
+ final SchemaPath schemaPath, final SchemaContext context)
throws IOException, XMLStreamException {
final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
try (
- final NormalizedNodeStreamWriter normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
- final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter)
+ NormalizedNodeStreamWriter normalizedNodeStreamWriter =
+ XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
+ NormalizedNodeWriter normalizedNodeWriter =
+ NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter)
) {
normalizedNodeWriter.write(normalized);
normalizedNodeWriter.flush();
} finally {
try {
- if(writer != null) {
+ if (writer != null) {
writer.close();
}
} catch (final Exception e) {
@Override
protected Element handle(final Document document, final XmlElement operationElement,
final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
- if (!subsequentOperation.isExecutionTermination()){
- throw new DocumentedException(String.format("No netconf operation expected to be subsequent to %s, but is %s", this, subsequentOperation),
+ if (!subsequentOperation.isExecutionTermination()) {
+ throw new DocumentedException(String.format(
+ "No netconf operation expected to be subsequent to %s, but is %s", this, subsequentOperation),
DocumentedException.ErrorType.APPLICATION,
DocumentedException.ErrorTag.MALFORMED_MESSAGE,
DocumentedException.ErrorSeverity.ERROR);
return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
}
- protected abstract Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException;
+ protected abstract Element handleWithNoSubsequentOperations(Document document,
+ XmlElement operationElement) throws DocumentedException;
}
return canHandle(operationNameAndNamespace.getOperationName(), operationNameAndNamespace.getNamespace());
}
+ protected HandlingPriority canHandle(final String operationName, final String operationNamespace) {
+ return operationName.equals(getOperationName()) && operationNamespace.equals(getOperationNamespace())
+ ? getHandlingPriority()
+ : HandlingPriority.CANNOT_HANDLE;
+ }
+
public static final class OperationNameAndNamespace {
- private final String operationName, namespace;
+ private final String operationName;
+ private final String namespace;
+
private final XmlElement operationElement;
public OperationNameAndNamespace(final Document message) throws DocumentedException {
public XmlElement getOperationElement() {
return operationElement;
}
+
}
protected static XmlElement getRequestElementWithCheck(final Document message) throws DocumentedException {
XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
}
- protected HandlingPriority canHandle(final String operationName, final String operationNamespace) {
- return operationName.equals(getOperationName()) && operationNamespace.equals(getOperationNamespace())
- ? getHandlingPriority()
- : HandlingPriority.CANNOT_HANDLE;
- }
-
protected HandlingPriority getHandlingPriority() {
return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
}
Map<String, Attr> attributes = requestElement.getAttributes();
Element response = handle(document, operationElement, subsequentOperation);
- Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY, Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+ Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY,
+ Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
- if(XmlElement.fromDomElement(response).hasNamespace()) {
+ if (XmlElement.fromDomElement(response).hasNamespace()) {
rpcReply.appendChild(response);
} else {
- Element responseNS = XmlUtil.createElement(document, response.getNodeName(), Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+ Element responseNS = XmlUtil.createElement(document, response.getNodeName(),
+ Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
NodeList list = response.getChildNodes();
- while(list.getLength()!=0) {
+ while (list.getLength() != 0) {
responseNS.appendChild(list.item(0));
}
rpcReply.appendChild(responseNS);
return document;
}
- protected abstract Element handle(Document document, XmlElement message, NetconfOperationChainedExecution subsequentOperation)
+ protected abstract Element handle(Document document, XmlElement message,
+ NetconfOperationChainedExecution subsequentOperation)
throws DocumentedException;
@Override
final StringBuffer sb = new StringBuffer(getClass().getName());
try {
sb.append("{name=").append(getOperationName());
- } catch(UnsupportedOperationException e) {
+ } catch (UnsupportedOperationException e) {
// no problem
}
sb.append(", namespace=").append(getOperationNamespace());
*/
public enum FramingMechanism {
/**
+ * Chunked framing mechanism.
+ *
* @see <a href="http://tools.ietf.org/html/rfc6242#section-4.2">Chunked
* framing mechanism</a>
*/
CHUNK,
/**
+ * End-of-Message framing mechanism.
+ *
* @see <a
* href="http://tools.ietf.org/html/rfc6242#section-4.3">End-of-message
* framing mechanism</a>
}
public static boolean isOKMessage(XmlElement xmlElement) throws NetconfDocumentedException {
- if(xmlElement.getChildElements().size() != 1) {
+ if (xmlElement.getChildElements().size() != 1) {
return false;
}
try {
}
public static boolean isErrorMessage(XmlElement xmlElement) throws NetconfDocumentedException {
- if(xmlElement.getChildElements().size() != 1) {
+ if (xmlElement.getChildElements().size() != 1) {
return false;
}
try {
final DocumentedException sendErrorException) {
LOG.trace("Sending error {}", sendErrorException.getMessage(), sendErrorException);
final Document errorDocument = createDocument(sendErrorException);
- ChannelFuture f = session.sendMessage(new NetconfMessage(errorDocument));
- f.addListener(new SendErrorVerifyingListener(sendErrorException));
+ ChannelFuture channelFuture = session.sendMessage(new NetconfMessage(errorDocument));
+ channelFuture.addListener(new SendErrorVerifyingListener(sendErrorException));
}
public static void sendErrorMessage(final Channel channel, final DocumentedException sendErrorException) {
LOG.trace("Sending error {}", sendErrorException.getMessage(), sendErrorException);
final Document errorDocument = createDocument(sendErrorException);
- ChannelFuture f = channel.writeAndFlush(new NetconfMessage(errorDocument));
- f.addListener(new SendErrorVerifyingListener(sendErrorException));
+ ChannelFuture channelFuture = channel.writeAndFlush(new NetconfMessage(errorDocument));
+ channelFuture.addListener(new SendErrorVerifyingListener(sendErrorException));
}
public static void sendErrorMessage(final NetconfSession session, final DocumentedException sendErrorException,
}
tryToCopyAttributes(incommingMessage.getDocument(), errorDocument, sendErrorException);
- ChannelFuture f = session.sendMessage(new NetconfMessage(errorDocument));
- f.addListener(new SendErrorVerifyingListener(sendErrorException));
+ ChannelFuture channelFuture = session.sendMessage(new NetconfMessage(errorDocument));
+ channelFuture.addListener(new SendErrorVerifyingListener(sendErrorException));
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private static void tryToCopyAttributes(final Document incommingDocument, final Document errorDocument,
final DocumentedException sendErrorException) {
try {
final Element incommingRpc = incommingDocument.getDocumentElement();
- Preconditions.checkState(incommingRpc.getTagName().equals(XmlNetconfConstants.RPC_KEY), "Missing %s element",
- XmlNetconfConstants.RPC_KEY);
+ Preconditions.checkState(incommingRpc.getTagName().equals(XmlNetconfConstants.RPC_KEY),
+ "Missing %s element", XmlNetconfConstants.RPC_KEY);
final Element rpcReply = errorDocument.getDocumentElement();
- Preconditions.checkState(rpcReply.getTagName().equals(XmlMappingConstants.RPC_REPLY_KEY), "Missing %s element",
- XmlMappingConstants.RPC_REPLY_KEY);
+ Preconditions.checkState(rpcReply.getTagName().equals(XmlMappingConstants.RPC_REPLY_KEY),
+ "Missing %s element", XmlMappingConstants.RPC_REPLY_KEY);
final NamedNodeMap incomingAttributes = incommingRpc.getAttributes();
for (int i = 0; i < incomingAttributes.getLength(); i++) {
private static final class SendErrorVerifyingListener implements ChannelFutureListener {
private final DocumentedException sendErrorException;
- public SendErrorVerifyingListener(final DocumentedException sendErrorException) {
+ SendErrorVerifyingListener(final DocumentedException sendErrorException) {
this.sendErrorException = sendErrorException;
}
public class SubtreeFilter {
private static final Logger LOG = LoggerFactory.getLogger(SubtreeFilter.class);
- public static Document applyRpcSubtreeFilter(Document requestDocument, Document rpcReply) throws DocumentedException {
+ public static Document applyRpcSubtreeFilter(Document requestDocument,
+ Document rpcReply) throws DocumentedException {
OperationNameAndNamespace operationNameAndNamespace = new OperationNameAndNamespace(requestDocument);
- if (XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0.equals(operationNameAndNamespace.getNamespace()) &&
- XmlNetconfConstants.GET.equals(operationNameAndNamespace.getOperationName()) ||
- XmlNetconfConstants.GET_CONFIG.equals(operationNameAndNamespace.getOperationName())) {
+ if (XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0.equals(operationNameAndNamespace.getNamespace())
+ && XmlNetconfConstants.GET.equals(operationNameAndNamespace.getOperationName())
+ || XmlNetconfConstants.GET_CONFIG.equals(operationNameAndNamespace.getOperationName())) {
// process subtree filtering here, in case registered netconf operations do
// not implement filtering.
- Optional<XmlElement> maybeFilter = operationNameAndNamespace.getOperationElement().getOnlyChildElementOptionally(
- XmlNetconfConstants.FILTER, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ Optional<XmlElement> maybeFilter = operationNameAndNamespace.getOperationElement()
+ .getOnlyChildElementOptionally(XmlNetconfConstants.FILTER,
+ XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
if (!maybeFilter.isPresent()) {
return rpcReply;
}
* @param filter filter
* @param notification notification
* @return document containing filtered notification content
- * @throws DocumentedException
+ * @throws DocumentedException if operation fails
*/
- public static Optional<Document> applySubtreeNotificationFilter(XmlElement filter, Document notification) throws DocumentedException {
+ public static Optional<Document> applySubtreeNotificationFilter(XmlElement filter,
+ Document notification) throws DocumentedException {
removeEventTimeNode(notification);
if (isSupported(filter)) {
return Optional.fromNullable(filteredNotification(filter, notification));
}
private static void removeEventTimeNode(Document document) {
- final Node eventTimeNode = document.getDocumentElement().getElementsByTagNameNS(
- XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0, XmlNetconfConstants.EVENT_TIME).item(0);
+ final Node eventTimeNode = document.getDocumentElement().getElementsByTagNameNS(XmlNetconfConstants
+ .URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0, XmlNetconfConstants.EVENT_TIME).item(0);
document.getDocumentElement().removeChild(eventTimeNode);
}
private static boolean isSupported(XmlElement filter) {
- return "subtree".equals(filter.getAttribute("type"))||
- "subtree".equals(filter.getAttribute("type", XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+ return "subtree".equals(filter.getAttribute("type"))
+ || "subtree".equals(filter.getAttribute("type",
+ XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
}
private static Document extractNotificationContent(Document notification) throws DocumentedException {
return notification;
}
- private static Document filteredNotification(XmlElement filter, Document originalNotification) throws DocumentedException {
+ private static Document filteredNotification(XmlElement filter,
+ Document originalNotification) throws DocumentedException {
Document result = XmlUtil.newDocument();
XmlElement dataSrc = XmlElement.fromDomDocument(originalNotification);
Element dataDst = (Element) result.importNode(dataSrc.getDomElement(), false);
for (XmlElement filterChild : filter.getChildElements()) {
addSubtree2(filterChild, dataSrc.getOnlyChildElement(), XmlElement.fromDomElement(dataDst));
}
- if(dataDst.getFirstChild() != null) {
+ if (dataDst.getFirstChild() != null) {
result.appendChild(dataDst.getFirstChild());
return result;
} else {
Element rpcReply = originalReplyDocument.getDocumentElement();
Node rpcReplyDst = result.importNode(rpcReply, false);
result.appendChild(rpcReplyDst);
- XmlElement dataSrc = XmlElement.fromDomElement(rpcReply).getOnlyChildElement("data", XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ XmlElement dataSrc = XmlElement.fromDomElement(rpcReply).getOnlyChildElement("data",
+ XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
Element dataDst = (Element) result.importNode(dataSrc.getDomElement(), false);
rpcReplyDst.appendChild(dataDst);
addSubtree(filter, dataSrc, XmlElement.fromDomElement(dataDst));
}
}
- private static MatchingResult addSubtree2(XmlElement filter, XmlElement src, XmlElement dstParent) throws DocumentedException {
+ private static MatchingResult addSubtree2(XmlElement filter, XmlElement src,
+ XmlElement dstParent) throws DocumentedException {
Document document = dstParent.getDomElement().getOwnerDocument();
MatchingResult matches = matches(src, filter);
if (matches != MatchingResult.NO_MATCH && matches != MatchingResult.CONTENT_MISMATCH) {
int numberOfTextMatchingChildren = 0;
for (XmlElement srcChild : src.getChildElements()) {
for (XmlElement filterChild : filter.getChildElements()) {
- MatchingResult childMatch = addSubtree2(filterChild, srcChild, XmlElement.fromDomElement(copied));
+ MatchingResult childMatch =
+ addSubtree2(filterChild, srcChild, XmlElement.fromDomElement(copied));
if (childMatch == MatchingResult.CONTENT_MISMATCH) {
return MatchingResult.NO_MATCH;
}
* If filter node has no children and has text content, it also must match.
*/
private static MatchingResult matches(XmlElement src, XmlElement filter) throws DocumentedException {
- boolean tagMatch = src.getName().equals(filter.getName()) &&
- src.getNamespaceOptionally().equals(filter.getNamespaceOptionally());
+ boolean tagMatch = src.getName().equals(filter.getName())
+ && src.getNamespaceOptionally().equals(filter.getNamespaceOptionally());
MatchingResult result = null;
if (tagMatch) {
// match text content
if (result == null) {
for (Attr attr : filter.getAttributes().values()) {
// ignore namespace declarations
- if (XmlUtil.XMLNS_URI.equals(attr.getNamespaceURI()) == false ) {
+ if (XmlUtil.XMLNS_URI.equals(attr.getNamespaceURI()) == false) {
// find attr with matching localName(), namespaceURI(), == value() in src
String found = src.getAttribute(attr.getLocalName(), attr.getNamespaceURI());
if (attr.getValue().equals(found) && result != MatchingResult.NO_MATCH) {
return result;
}
- private static boolean prefixedContentMatches(final XmlElement filter, final XmlElement src) throws DocumentedException {
+ private static boolean prefixedContentMatches(final XmlElement filter,
+ final XmlElement src) throws DocumentedException {
final Map.Entry<String, String> prefixToNamespaceOfFilter;
final Map.Entry<String, String> prefixToNamespaceOfSrc;
try {
return false;
}
- final String unprefixedFilterContent = filter.getTextContent().substring(prefixToNamespaceOfFilter.getKey().length() + 1);
- final String unprefixedSrcContnet = src.getTextContent().substring(prefixToNamespaceOfSrc.getKey().length() + 1);
+ final String unprefixedFilterContent =
+ filter.getTextContent().substring(prefixToNamespaceOfFilter.getKey().length() + 1);
+ final String unprefixedSrcContnet =
+ src.getTextContent().substring(prefixToNamespaceOfSrc.getKey().length() + 1);
// Finally compare unprefixed content
return unprefixedFilterContent.equals(unprefixedSrcContnet);
}
package org.opendaylight.netconf.util.osgi;
import java.util.Collection;
-import java.util.Optional;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
final Collection<ServiceReference<ManagedService>> serviceReferences
= bundleContext.getServiceReferences(ManagedService.class, null);
for (final ServiceReference<ManagedService> serviceReference : serviceReferences) {
- ManagedService service = bundleContext.getService(serviceReference);
- if (service instanceof NetconfConfiguration){
- LOG.debug("Netconf configuration service found");
- return (NetconfConfiguration) service;
- }
+ ManagedService service = bundleContext.getService(serviceReference);
+ if (service instanceof NetconfConfiguration) {
+ LOG.debug("Netconf configuration service found");
+ return (NetconfConfiguration) service;
+ }
}
throw new IllegalStateException("Netconf configuration service not found");
LOG.debug("CSS netconf server configuration cannot be updated as passed dictionary is null");
return;
}
- final InetSocketAddress sshServerAddress = new InetSocketAddress((String) dictionaryConfig.get(SSH_ADDRESS_PROP),
- Integer.parseInt((String) dictionaryConfig.get(SSH_PORT_PROP)));
- final InetSocketAddress tcpServerAddress = new InetSocketAddress((String) dictionaryConfig.get(TCP_ADDRESS_PROP),
+ final InetSocketAddress sshServerAddress =
+ new InetSocketAddress((String) dictionaryConfig.get(SSH_ADDRESS_PROP),
+ Integer.parseInt((String) dictionaryConfig.get(SSH_PORT_PROP)));
+ final InetSocketAddress tcpServerAddress =
+ new InetSocketAddress((String) dictionaryConfig.get(TCP_ADDRESS_PROP),
Integer.parseInt((String) dictionaryConfig.get(TCP_PORT_PROP)));
netconfConfiguration = new NetconfConfigurationHolder(tcpServerAddress,
LOG.debug("CSS netconf server configuration was updated: {}", dictionaryConfig.toString());
}
- public InetSocketAddress getSshServerAddress(){
+ public InetSocketAddress getSshServerAddress() {
return netconfConfiguration.getSshServerAddress();
}
- public InetSocketAddress getTcpServerAddress(){
+ public InetSocketAddress getTcpServerAddress() {
return netconfConfiguration.getTcpServerAddress();
}
}
/**
- * This method returns the uri for all prefixes needed. Wherever possible it
- * uses XMLConstants.
+ * Returns the URI for all prefixes needed. Wherever possible it
+ * uses {@code XMLConstants}.
*
- * @param prefix
- * @return uri
+ * @param prefix prefix
+ * @return uri uniform resource identifier
*/
@Override
public String getNamespaceURI(String prefix) {
throw new UnsupportedOperationException("Utility class");
}
- public static XPathExpression compileXPath(final String xPath) {
- final XPath xpath = FACTORY.newXPath();
- xpath.setNamespaceContext(NS_CONTEXT);
+ public static XPathExpression compileXPath(final String xpath) {
+ final XPath newXPath = FACTORY.newXPath();
+ newXPath.setNamespaceContext(NS_CONTEXT);
try {
- return xpath.compile(xPath);
+ return newXPath.compile(xpath);
} catch (final XPathExpressionException e) {
- throw new IllegalStateException("Error while compiling xpath expression " + xPath, e);
+ throw new IllegalStateException("Error while compiling xpath expression " + xpath, e);
}
}
public class CloseableUtilTest {
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Test
public void testCloseAllFail() throws Exception {
final AutoCloseable failingCloseable = new AutoCloseable() {
@Test
public void testConflictingVersionDetection() throws Exception {
- final Document document = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/netconfMessages/conflictingversion/conflictingVersionResponse.xml"));
- try{
+ final Document document = XmlUtil.readXmlToDocument(getClass()
+ .getResourceAsStream("/netconfMessages/conflictingversion/conflictingVersionResponse.xml"));
+ try {
NetconfUtil.checkIsMessageOk(document);
fail();
} catch (final IllegalStateException e) {
.withValue("admin")
.build();
final MapEntryNode session1 = Builders.mapEntryBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifierWithPredicates(Session.QNAME, QName.create(Session.QNAME, "session-id"), 1L))
+ .withNodeIdentifier(new YangInstanceIdentifier
+ .NodeIdentifierWithPredicates(Session.QNAME, QName.create(Session.QNAME, "session-id"), 1L))
.withChild(username)
.build();
final MapNode sessionList = Builders.mapBuilder()
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException{
+ protected Element handleWithNoSubsequentOperations(Document document,
+ XmlElement operationElement) throws DocumentedException {
handleWithNoSubsequentOperationsRun = true;
return null;
}
}
@Override
- protected Element handle(Document document, XmlElement message, NetconfOperationChainedExecution subsequentOperation) throws DocumentedException{
+ protected Element handle(Document document, XmlElement message,
+ NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
this.handleRun = true;
try {
return XmlUtil.readXmlToElement("<element/>");
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException{
+ protected Element handleWithNoSubsequentOperations(Document document,
+ XmlElement operationElement) throws DocumentedException {
return null;
}
assertTrue(NetconfMessageUtil.isOKMessage(new NetconfMessage(okMessage)));
assertFalse(NetconfMessageUtil.isErrorMessage(new NetconfMessage(okMessage)));
- Document errorMessage = XmlFileLoader.xmlFileToDocument("netconfMessages/communicationError/testClientSendsRpcReply_expectedResponse.xml");
+ Document errorMessage = XmlFileLoader
+ .xmlFileToDocument("netconfMessages/communicationError/testClientSendsRpcReply_expectedResponse.xml");
assertTrue(NetconfMessageUtil.isErrorMessage(new NetconfMessage(errorMessage)));
assertFalse(NetconfMessageUtil.isOKMessage(new NetconfMessage(errorMessage)));
Document helloMessage = XmlFileLoader.xmlFileToDocument("netconfMessages/client_hello.xml");
- Collection<String> caps = NetconfMessageUtil.extractCapabilitiesFromHello(new NetconfMessage(helloMessage).getDocument());
+ Collection<String> caps =
+ NetconfMessageUtil.extractCapabilitiesFromHello(new NetconfMessage(helloMessage).getDocument());
assertTrue(caps.contains("urn:ietf:params:netconf:base:1.0"));
assertTrue(caps.contains("urn:ietf:params:netconf:base:1.1"));
}
}
@Before
- public void setUp(){
+ public void setUp() {
XMLUnit.setIgnoreWhitespace(true);
}
XmlElement filter = XmlElement.fromDomDocument(getDocument("filter.xml"));
Document preFilterDocument = getDocument("pre-filter.xml");
Document postFilterDocument = getDocument("post-filter.xml");
- Optional<Document> actualPostFilterDocumentOpt = SubtreeFilter.applySubtreeNotificationFilter(filter, preFilterDocument);
- if(actualPostFilterDocumentOpt.isPresent()) {
+ Optional<Document> actualPostFilterDocumentOpt =
+ SubtreeFilter.applySubtreeNotificationFilter(filter, preFilterDocument);
+ if (actualPostFilterDocumentOpt.isPresent()) {
Document actualPostFilterDocument = actualPostFilterDocumentOpt.get();
LOG.info("Actual document: {}", XmlUtil.toString(actualPostFilterDocument));
Diff diff = XMLUnit.compareXML(postFilterDocument, actualPostFilterDocument);
}
public Document getDocument(String fileName) throws SAXException, IOException {
- return XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/subtree/notification/" + directoryIndex + "/" +
- fileName));
+ return XmlUtil.readXmlToDocument(getClass().getResourceAsStream(
+ "/subtree/notification/" + directoryIndex + "/" + fileName));
}
}
}
@Before
- public void setUp(){
+ public void setUp() {
XMLUnit.setIgnoreWhitespace(true);
}
}
public Document getDocument(String fileName) throws SAXException, IOException {
- return XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/subtree/rpc/" + directoryIndex + "/" +
- fileName));
+ return XmlUtil.readXmlToDocument(
+ getClass().getResourceAsStream("/subtree/rpc/" + directoryIndex + "/" + fileName));
}
}
package org.opendaylight.netconf.util.osgi;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
NetconfConfigUtil.getNetconfConfigurationService(context);
Assert.fail(IllegalStateException.class + "exception expected");
} catch (IllegalStateException e) {
-
+ assertTrue(e.getMessage().startsWith("Netconf configuration service not found"));
}
}
/**
* Custom xmlunit qualifier that doesn't care about order when deeper in the recursion
- * defaults to comparing element name and text content
+ * defaults to comparing element name and text content.
*/
public class NetconfXmlUnitRecursiveQualifier implements ElementQualifier {
return compareNodes(currentControl, currentTest);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private boolean compareNodes(Node currentControl, Node currentTest) {
try {
return !(currentControl.hasChildNodes() || currentTest.hasChildNodes());
}
- return (countNodesWithoutConsecutiveTextNodes(controlNodes) == countNodesWithoutConsecutiveTextNodes(testNodes))
- && checkChildren(controlNodes, testNodes);
+ return (countNodesWithoutConsecutiveTextNodes(controlNodes)
+ == countNodesWithoutConsecutiveTextNodes(testNodes)) && checkChildren(controlNodes, testNodes);
} catch (Exception e) {
return false;
return builder.toString();
}
- private static int countNodesWithoutConsecutiveTextNodes(NodeList l) {
+ private static int countNodesWithoutConsecutiveTextNodes(NodeList nodeList) {
int count = 0;
boolean lastNodeWasText = false;
- final int length = l.getLength();
+ final int length = nodeList.getLength();
for (int i = 0; i < length; i++) {
- Node n = l.item(i);
- if (!lastNodeWasText || n.getNodeType() != Node.TEXT_NODE) {
+ Node node = nodeList.item(i);
+ if (!lastNodeWasText || node.getNodeType() != Node.TEXT_NODE) {
count++;
}
- lastNodeWasText = n.getNodeType() == Node.TEXT_NODE;
+ lastNodeWasText = node.getNodeType() == Node.TEXT_NODE;
}
return count;
}
private XmlUnitUtil() {}
- public static void assertContainsElementWithText(final Document doc, final String textToFind) throws NodeTestException {
+ public static void assertContainsElementWithText(final Document doc,
+ final String textToFind) throws NodeTestException {
NodeTest nt = new NodeTest(doc);
NodeTester tester = new AbstractNodeTester() {
@Override
public void testText(Text text) throws NodeTestException {
- if(!textFound) {
+ if (!textFound) {
if (text.getData().equalsIgnoreCase(textToFind)) {
textFound = true;
}
@Override
public void testElement(Element element) throws NodeTestException {
if (!elementFound) {
- if(element.isEqualNode(testElement)) {
+ if (element.isEqualNode(testElement)) {
elementFound = true;
}
}
assertNodeTestPasses(nt, tester, new short[]{Node.ELEMENT_NODE}, true);
}
- public static void assertContainsElementWithName(final Document doc, final String elementName) throws NodeTestException {
+ public static void assertContainsElementWithName(final Document doc,
+ final String elementName) throws NodeTestException {
NodeTest nt = new NodeTest(doc);
NodeTester tester = new AbstractNodeTester() {
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
@Test
public void testResolver() throws Exception {
- final HardcodedNamespaceResolver hardcodedNamespaceResolver = new HardcodedNamespaceResolver("prefix", "namespace");
+ final HardcodedNamespaceResolver hardcodedNamespaceResolver =
+ new HardcodedNamespaceResolver("prefix", "namespace");
assertEquals("namespace", hardcodedNamespaceResolver.getNamespaceURI("prefix"));
- try{
+ try {
hardcodedNamespaceResolver.getNamespaceURI("unknown");
fail("Unknown namespace lookup should fail");
- } catch(IllegalStateException e) {}
+ } catch (IllegalStateException e) {
+ assertTrue(e.getMessage().startsWith("Prefix mapping not found for "));
+ }
assertNull(hardcodedNamespaceResolver.getPrefix("any"));
assertNull(hardcodedNamespaceResolver.getPrefixes("any"));
package org.opendaylight.netconf.util.xml;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import javax.xml.xpath.XPathConstants;
try {
XMLNetconfUtil.compileXPath("!@(*&$!");
fail("Incorrect xpath should fail");
- } catch (IllegalStateException e) {}
- final Object value = XmlUtil.evaluateXPath(correctXPath, XmlUtil.readXmlToDocument("<top><innerText>value</innerText></top>"), XPathConstants.NODE);
+ } catch (IllegalStateException e) {
+ assertTrue(e.getMessage().startsWith("Error while compiling xpath expression "));
+ }
+ final Object value = XmlUtil.evaluateXPath(correctXPath,
+ XmlUtil.readXmlToDocument("<top><innerText>value</innerText></top>"), XPathConstants.NODE);
assertEquals("value", ((Element) value).getTextContent());
}
<groupId>${project.groupId}</groupId>
<artifactId>features-restconf</artifactId>
<version>${project.version}</version>
+ <type>xml</type>
<classifier>features</classifier>
+ </dependency>
+
+ <!-- restconf features -->
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>features4-restconf</artifactId>
+ <version>${project.version}</version>
<type>xml</type>
- <scope>runtime</scope>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-mdsal-apidocs</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>odl-restconf</artifactId>
<version>${project.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-restconf-all</artifactId>
+ <version>${project.version}</version>
+ <type>xml</type>
<classifier>features</classifier>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>odl-restconf-noauth</artifactId>
+ <version>${project.version}</version>
<type>xml</type>
- <scope>runtime</scope>
+ <classifier>features</classifier>
</dependency>
</dependencies>
</dependencyManagement>
final String insert, final String point) {
if (insert == null) {
makePut(rWTransaction, datastore, path, payload, schemaContext);
- } else {
- final DataSchemaNode schemaNode = checkListAndOrderedType(schemaContext, path);
- checkItemDoesNotExists(rWTransaction, datastore, path);
- switch (insert) {
- case "first":
- if (schemaNode instanceof ListSchemaNode) {
- final OrderedMapNode readList =
- (OrderedMapNode) this.readConfigurationData(path.getParent());
- if (readList == null || readList.getValue().isEmpty()) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
- } else {
- rWTransaction.delete(datastore, path.getParent());
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
- makePut(rWTransaction, datastore, path.getParent(), readList, schemaContext);
- }
+ return;
+ }
+
+ final DataSchemaNode schemaNode = checkListAndOrderedType(schemaContext, path);
+ checkItemDoesNotExists(rWTransaction, datastore, path);
+ switch (insert) {
+ case "first":
+ if (schemaNode instanceof ListSchemaNode) {
+ final OrderedMapNode readList =
+ (OrderedMapNode) this.readConfigurationData(path.getParent());
+ if (readList == null || readList.getValue().isEmpty()) {
+ simplePut(datastore, path, rWTransaction, schemaContext, payload);
} else {
- final OrderedLeafSetNode<?> readLeafList =
- (OrderedLeafSetNode<?>) readConfigurationData(path.getParent());
- if (readLeafList == null || readLeafList.getValue().isEmpty()) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
- } else {
- rWTransaction.delete(datastore, path.getParent());
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
- makePut(rWTransaction, datastore, path.getParent(), readLeafList,
- schemaContext);
- }
+ rWTransaction.delete(datastore, path.getParent());
+ simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ makePut(rWTransaction, datastore, path.getParent(), readList, schemaContext);
}
- break;
- case "last":
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
- break;
- case "before":
- if (schemaNode instanceof ListSchemaNode) {
- final OrderedMapNode readList =
- (OrderedMapNode) this.readConfigurationData(path.getParent());
- if (readList == null || readList.getValue().isEmpty()) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
- } else {
- insertWithPointListPut(rWTransaction, datastore, path, payload, schemaContext, point,
- readList, true);
- }
+ } else {
+ final OrderedLeafSetNode<?> readLeafList =
+ (OrderedLeafSetNode<?>) readConfigurationData(path.getParent());
+ if (readLeafList == null || readLeafList.getValue().isEmpty()) {
+ simplePut(datastore, path, rWTransaction, schemaContext, payload);
} else {
- final OrderedLeafSetNode<?> readLeafList =
- (OrderedLeafSetNode<?>) readConfigurationData(path.getParent());
- if (readLeafList == null || readLeafList.getValue().isEmpty()) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
- } else {
- insertWithPointLeafListPut(rWTransaction, datastore, path, payload, schemaContext, point,
- readLeafList, true);
- }
+ rWTransaction.delete(datastore, path.getParent());
+ simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ makePut(rWTransaction, datastore, path.getParent(), readLeafList,
+ schemaContext);
}
- break;
- case "after":
- if (schemaNode instanceof ListSchemaNode) {
- final OrderedMapNode readList =
- (OrderedMapNode) this.readConfigurationData(path.getParent());
- if (readList == null || readList.getValue().isEmpty()) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
- } else {
- insertWithPointListPut(rWTransaction, datastore, path, payload, schemaContext, point,
- readList, false);
- }
+ }
+ break;
+ case "last":
+ simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ break;
+ case "before":
+ if (schemaNode instanceof ListSchemaNode) {
+ final OrderedMapNode readList =
+ (OrderedMapNode) this.readConfigurationData(path.getParent());
+ if (readList == null || readList.getValue().isEmpty()) {
+ simplePut(datastore, path, rWTransaction, schemaContext, payload);
} else {
- final OrderedLeafSetNode<?> readLeafList =
- (OrderedLeafSetNode<?>) readConfigurationData(path.getParent());
- if (readLeafList == null || readLeafList.getValue().isEmpty()) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
- } else {
- insertWithPointLeafListPut(rWTransaction, datastore, path, payload, schemaContext, point,
- readLeafList, false);
- }
+ insertWithPointListPut(rWTransaction, datastore, path, payload, schemaContext, point,
+ readList, true);
}
- break;
- default:
- throw new RestconfDocumentedException(
- "Used bad value of insert parameter. Possible values are first, last, before or after, "
- + "but was: " + insert);
- }
+ } else {
+ final OrderedLeafSetNode<?> readLeafList =
+ (OrderedLeafSetNode<?>) readConfigurationData(path.getParent());
+ if (readLeafList == null || readLeafList.getValue().isEmpty()) {
+ simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ } else {
+ insertWithPointLeafListPut(rWTransaction, datastore, path, payload, schemaContext, point,
+ readLeafList, true);
+ }
+ }
+ break;
+ case "after":
+ if (schemaNode instanceof ListSchemaNode) {
+ final OrderedMapNode readList =
+ (OrderedMapNode) this.readConfigurationData(path.getParent());
+ if (readList == null || readList.getValue().isEmpty()) {
+ simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ } else {
+ insertWithPointListPut(rWTransaction, datastore, path, payload, schemaContext, point,
+ readList, false);
+ }
+ } else {
+ final OrderedLeafSetNode<?> readLeafList =
+ (OrderedLeafSetNode<?>) readConfigurationData(path.getParent());
+ if (readLeafList == null || readLeafList.getValue().isEmpty()) {
+ simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ } else {
+ insertWithPointLeafListPut(rWTransaction, datastore, path, payload, schemaContext, point,
+ readLeafList, false);
+ }
+ }
+ break;
+ default:
+ throw new RestconfDocumentedException(
+ "Used bad value of insert parameter. Possible values are first, last, before or after, but was: "
+ + insert);
}
}
- private static void insertWithPointLeafListPut(final DOMDataReadWriteTransaction rWTransaction,
+ private static void insertWithPointLeafListPut(final DOMDataWriteTransaction tx,
final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
final SchemaContext schemaContext, final String point, final OrderedLeafSetNode<?> readLeafList,
final boolean before) {
- rWTransaction.delete(datastore, path.getParent());
+ tx.delete(datastore, path.getParent());
final InstanceIdentifierContext<?> instanceIdentifier =
ControllerContext.getInstance().toInstanceIdentifier(point);
int p = 0;
int h = 0;
final NormalizedNode<?, ?> emptySubtree =
ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
- rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
+ tx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
if (h == p) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ simplePut(datastore, path, tx, schemaContext, payload);
}
final YangInstanceIdentifier childPath = path.getParent().node(nodeChild.getIdentifier());
- rWTransaction.put(datastore, childPath, nodeChild);
+ tx.put(datastore, childPath, nodeChild);
h++;
}
}
- private static void insertWithPointListPut(final DOMDataReadWriteTransaction rWTransaction,
- final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
- final SchemaContext schemaContext, final String point, final OrderedMapNode readList,
- final boolean before) {
- rWTransaction.delete(datastore, path.getParent());
+ private static void insertWithPointListPut(final DOMDataWriteTransaction tx, final LogicalDatastoreType datastore,
+ final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext,
+ final String point, final OrderedMapNode readList, final boolean before) {
+ tx.delete(datastore, path.getParent());
final InstanceIdentifierContext<?> instanceIdentifier =
ControllerContext.getInstance().toInstanceIdentifier(point);
int p = 0;
int h = 0;
final NormalizedNode<?, ?> emptySubtree =
ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
- rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
+ tx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
for (final MapEntryNode mapEntryNode : readList.getValue()) {
if (h == p) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ simplePut(datastore, path, tx, schemaContext, payload);
}
final YangInstanceIdentifier childPath = path.getParent().node(mapEntryNode.getIdentifier());
- rWTransaction.put(datastore, childPath, mapEntryNode);
+ tx.put(datastore, childPath, mapEntryNode);
h++;
}
}
- private static void makePut(final DOMDataReadWriteTransaction writeTransaction,
- final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
- final SchemaContext schemaContext) {
+ private static void makePut(final DOMDataWriteTransaction tx, final LogicalDatastoreType datastore,
+ final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext) {
if (payload instanceof MapNode) {
final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
- writeTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
- ensureParentsByMerge(datastore, path, writeTransaction, schemaContext);
+ tx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
+ ensureParentsByMerge(datastore, path, tx, schemaContext);
for (final MapEntryNode child : ((MapNode) payload).getValue()) {
final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
- writeTransaction.put(datastore, childPath, child);
+ tx.put(datastore, childPath, child);
}
} else {
- simplePut(datastore, path, writeTransaction, schemaContext, payload);
+ simplePut(datastore, path, tx, schemaContext, payload);
}
}
private static void simplePut(final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
- final DOMDataReadWriteTransaction writeTransaction, final SchemaContext schemaContext,
- final NormalizedNode<?, ?> payload) {
- ensureParentsByMerge(datastore, path, writeTransaction, schemaContext);
- writeTransaction.put(datastore, path, payload);
+ final DOMDataWriteTransaction tx, final SchemaContext schemaContext, final NormalizedNode<?, ?> payload) {
+ ensureParentsByMerge(datastore, path, tx, schemaContext);
+ tx.put(datastore, path, payload);
}
private static CheckedFuture<Void, TransactionCommitFailedException> deleteDataViaTransaction(
return readWriteTransaction.submit();
}
- private static void deleteDataWithinTransaction(final DOMDataWriteTransaction writeTransaction,
+ private static void deleteDataWithinTransaction(final DOMDataWriteTransaction tx,
final LogicalDatastoreType datastore, final YangInstanceIdentifier path) {
LOG.trace("Delete {} within Restconf PATCH: {}", datastore.name(), path);
- writeTransaction.delete(datastore, path);
+ tx.delete(datastore, path);
}
- private static void mergeDataWithinTransaction(
- final DOMDataReadWriteTransaction writeTransaction, final LogicalDatastoreType datastore,
- final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext) {
+ private static void mergeDataWithinTransaction(final DOMDataWriteTransaction tx,
+ final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
+ final SchemaContext schemaContext) {
LOG.trace("Merge {} within Restconf PATCH: {} with payload {}", datastore.name(), path, payload);
- ensureParentsByMerge(datastore, path, writeTransaction, schemaContext);
+ ensureParentsByMerge(datastore, path, tx, schemaContext);
// Since YANG Patch provides the option to specify what kind of operation for each edit,
// OpenDaylight should not change it.
- writeTransaction.merge(datastore, path, payload);
+ tx.merge(datastore, path, payload);
}
public void setDomDataBroker(final DOMDataBroker domDataBroker) {
}
private static void ensureParentsByMerge(final LogicalDatastoreType store,
- final YangInstanceIdentifier normalizedPath, final DOMDataReadWriteTransaction rwTx,
+ final YangInstanceIdentifier normalizedPath, final DOMDataWriteTransaction tx,
final SchemaContext schemaContext) {
final List<PathArgument> normalizedPathWithoutChildArgs = new ArrayList<>();
YangInstanceIdentifier rootNormalizedPath = null;
final NormalizedNode<?, ?> parentStructure = ImmutableNodes.fromInstanceId(schemaContext,
YangInstanceIdentifier.create(normalizedPathWithoutChildArgs));
- rwTx.merge(store, rootNormalizedPath, parentStructure);
+ tx.merge(store, rootNormalizedPath, parentStructure);
}
private static final class PATCHStatusContextHelper {