2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.netconf.test.tool.customrpc;
12 import java.util.Optional;
13 import org.opendaylight.netconf.api.DocumentedException;
14 import org.opendaylight.netconf.api.xml.XmlElement;
15 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
16 import org.opendaylight.netconf.api.xml.XmlUtil;
17 import org.opendaylight.netconf.mapping.api.HandlingPriority;
18 import org.opendaylight.netconf.mapping.api.NetconfOperation;
19 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
20 import org.w3c.dom.Document;
23 * {@link NetconfOperation} implementation. It can be configured to intercept rpcs with defined input
24 * and reply with defined output. If input isn't defined, rpc handling is delegated to the subsequent
25 * {@link NetconfOperation} which is able to handle it.
27 class SettableRpc implements NetconfOperation {
29 private final RpcMapping mapping;
31 SettableRpc(final File rpcConfig) {
32 mapping = new RpcMapping(rpcConfig);
36 public HandlingPriority canHandle(final Document message) {
37 return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1000);
41 public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation)
42 throws DocumentedException {
43 final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage);
44 final XmlElement rpcElement = requestElement.getOnlyChildElement();
45 final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID);
46 final Optional<Document> response = mapping.getResponse(rpcElement);
47 if (response.isPresent()) {
48 final Document document = response.get();
49 checkForError(document);
50 document.getDocumentElement().setAttribute(XmlNetconfConstants.MESSAGE_ID, msgId);
52 } else if (subsequentOperation.isExecutionTermination()) {
53 throw new DocumentedException("Mapping not found " + XmlUtil.toString(requestMessage),
54 DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED,
55 DocumentedException.ErrorSeverity.ERROR);
57 return subsequentOperation.execute(requestMessage);
61 private static void checkForError(final Document document) throws DocumentedException {
62 final XmlElement rpcReply = XmlElement.fromDomDocument(document);
63 if (rpcReply.getOnlyChildElementOptionally("rpc-error").isPresent()) {
64 throw DocumentedException.fromXMLDocument(document);