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
8 package org.opendaylight.netconf.test.tool.customrpc;
11 import java.util.Optional;
12 import org.opendaylight.netconf.api.DocumentedException;
13 import org.opendaylight.netconf.api.xml.XmlElement;
14 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
15 import org.opendaylight.netconf.api.xml.XmlUtil;
16 import org.opendaylight.netconf.mapping.api.HandlingPriority;
17 import org.opendaylight.netconf.mapping.api.NetconfOperation;
18 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
19 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
20 import org.opendaylight.yangtools.yang.common.ErrorTag;
21 import org.opendaylight.yangtools.yang.common.ErrorType;
22 import org.w3c.dom.Document;
25 * {@link NetconfOperation} implementation. It can be configured to intercept rpcs with defined input
26 * and reply with defined output. If input isn't defined, rpc handling is delegated to the subsequent
27 * {@link NetconfOperation} which is able to handle it.
29 class SettableRpc implements NetconfOperation {
31 private final RpcMapping mapping;
33 SettableRpc(final File rpcConfig) {
34 mapping = new RpcMapping(rpcConfig);
38 public HandlingPriority canHandle(final Document message) {
39 return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1000);
43 public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation)
44 throws DocumentedException {
45 final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage);
46 final XmlElement rpcElement = requestElement.getOnlyChildElement();
47 final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID);
48 final Optional<Document> response = mapping.getResponse(rpcElement);
49 if (response.isPresent()) {
50 final Document document = response.get();
51 checkForError(document);
52 document.getDocumentElement().setAttribute(XmlNetconfConstants.MESSAGE_ID, msgId);
54 } else if (subsequentOperation.isExecutionTermination()) {
55 throw new DocumentedException("Mapping not found " + XmlUtil.toString(requestMessage),
56 ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED, ErrorSeverity.ERROR);
58 return subsequentOperation.execute(requestMessage);
62 private static void checkForError(final Document document) throws DocumentedException {
63 final XmlElement rpcReply = XmlElement.fromDomDocument(document);
64 if (rpcReply.getOnlyChildElementOptionally("rpc-error").isPresent()) {
65 throw DocumentedException.fromXMLDocument(document);