Development of NETCONF RPCs for tr-069 adapter to
[oam/tr069-adapter.git] / netconf-server / src / main / java / org / commscope / tr069adapter / netconf / rpc / ResetOperation.java
1 /*
2  * ============LICENSE_START========================================================================
3  * ONAP : tr-069-adapter
4  * =================================================================================================
5  * Copyright (C) 2020 CommScope Inc Intellectual Property.
6  * =================================================================================================
7  * This tr-069-adapter software file is distributed by CommScope Inc under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You
9  * may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
14  * either express or implied. See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ===============LICENSE_END=======================================================================
17  */
18
19 package org.commscope.tr069adapter.netconf.rpc;
20
21 import java.io.StringReader;
22
23 import javax.xml.XMLConstants;
24 import javax.xml.parsers.DocumentBuilder;
25 import javax.xml.parsers.DocumentBuilderFactory;
26
27 import org.commscope.tr069adapter.mapper.model.ErrorCodeDetails;
28 import org.commscope.tr069adapter.mapper.model.NetConfResponse;
29 import org.commscope.tr069adapter.netconf.boot.NetConfServiceBooter;
30 import org.commscope.tr069adapter.netconf.config.NetConfServerProperties;
31 import org.opendaylight.netconf.api.DocumentedException;
32 import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
33 import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
34 import org.opendaylight.netconf.api.DocumentedException.ErrorType;
35 import org.opendaylight.netconf.api.xml.XmlElement;
36 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
37 import org.opendaylight.netconf.mapping.api.HandlingPriority;
38 import org.opendaylight.netconf.mapping.api.NetconfOperation;
39 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.w3c.dom.Document;
43 import org.w3c.dom.Element;
44 import org.w3c.dom.Node;
45 import org.xml.sax.InputSource;
46
47 public class ResetOperation implements NetconfOperation {
48   private static final Logger logger = LoggerFactory.getLogger(ResetOperation.class);
49   public static final String OP_NAMESPACE = "urn:tr069rpc:1.0";
50   public static final String OP_NAME = "reset";
51
52   private String deviceID;
53   private String swVersion;
54   private String hwVersion;
55
56   public ResetOperation(String deviceID, String swVersion, String hwVersion) {
57     this.deviceID = deviceID;
58     this.swVersion = swVersion;
59     this.hwVersion = hwVersion;
60   }
61
62   @Override
63   public HandlingPriority canHandle(final Document message) throws DocumentedException {
64     OperationNameAndNamespace operationNameAndNamespace = null;
65     operationNameAndNamespace = new OperationNameAndNamespace(message);
66     return canHandle(operationNameAndNamespace.getOperationName(),
67         operationNameAndNamespace.getNamespace());
68   }
69
70   @Override
71   public Document handle(Document requestMessage,
72       NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
73     logger.debug("Reset rpc is received in netconfserver");
74
75     final XmlElement requestElement = XmlElement.fromDomDocument(requestMessage);
76
77     final String msgId = requestElement.getAttribute(XmlNetconfConstants.MESSAGE_ID);
78     final Element element =
79         requestMessage.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
80             XmlNetconfConstants.RPC_REPLY_KEY);
81     element.setAttribute("xmlns:ns1", getOperationNamespace());
82     element.setAttribute("message-id", msgId);
83
84     String requestXml = XmlUtility.convertDocumentToString(requestElement);
85     logger.debug("reset rpc requestXml= {}", requestXml);
86
87     NetConfServerProperties config =
88         NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class);
89
90     final String baseUrl = config.getMapperPath() + "/reset";
91     NetConfResponse restResponse =
92         XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion);
93     Document respDoc = null;
94
95     ErrorCodeDetails errorCode = restResponse.getErrorCode();
96     if (errorCode != null && errorCode.getFaultCode() != null
97         && !errorCode.getFaultCode().equalsIgnoreCase("0")) {
98       logger.error("Error recevied : {}", errorCode);
99       throw new DocumentedException(errorCode.getErrorMessage(),
100           ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()),
101           ErrorSeverity.from(errorCode.getErrorSeverity()));
102     } else {
103       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
104       factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
105       factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
106       DocumentBuilder builder;
107       try {
108         Node child = requestMessage.createElement(XmlNetconfConstants.OK);
109         element.appendChild(child);
110         String xmlStr = XmlUtility.convertDocumentToString(element);
111         try {
112           builder = factory.newDocumentBuilder();
113           respDoc = builder.parse(new InputSource(new StringReader(xmlStr)));
114         } catch (Exception e) {
115           logger.error("Error while converting String to element: {}", e.getMessage());
116           throw new DocumentedException("Operation Aborted", ErrorType.from("application"),
117               ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR"));
118         }
119       } catch (Exception e) {
120         logger.error("Error while contruscting the response: {}", e.getMessage());
121         throw new DocumentedException("Operation Aborted", ErrorType.from("application"),
122             ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR"));
123       }
124     }
125
126     return respDoc;
127   }
128
129   protected HandlingPriority canHandle(final String operationName,
130       final String operationNamespace) {
131     return operationName.equals(getOperationName())
132         && operationNamespace.equals(getOperationNamespace())
133             ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100)
134             : HandlingPriority.CANNOT_HANDLE;
135   }
136
137   public static final class OperationNameAndNamespace {
138     private final String operationName;
139     private final String namespace;
140
141     private final XmlElement operationElement;
142
143     public OperationNameAndNamespace(final Document message) throws DocumentedException {
144       XmlElement requestElement = null;
145       requestElement = getRequestElementWithCheck(message);
146       operationElement = requestElement.getOnlyChildElement();
147       operationName = operationElement.getName();
148       namespace = operationElement.getNamespace();
149     }
150
151     public String getOperationName() {
152       return operationName;
153     }
154
155     public String getNamespace() {
156       return namespace;
157     }
158
159     public XmlElement getOperationElement() {
160       return operationElement;
161     }
162
163   }
164
165   protected static XmlElement getRequestElementWithCheck(final Document message)
166       throws DocumentedException {
167     return XmlElement.fromDomElementWithExpected(message.getDocumentElement(),
168         XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
169   }
170
171   protected String getOperationNamespace() {
172     return OP_NAMESPACE;
173   }
174
175   protected String getOperationName() {
176     return OP_NAME;
177   }
178
179 }