Development of NETCONF RPCs for tr-069 adapter to
[oam/tr069-adapter.git] / netconf-server / src / main / java / org / commscope / tr069adapter / netconf / rpc / DownloadOperation.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 DownloadOperation implements NetconfOperation {
48   private static final Logger logger = LoggerFactory.getLogger(DownloadOperation.class);
49   public static final String OP_NAMESPACE = "urn:tr069rpc:1.0";
50   public static final String OP_NAME = "download";
51
52   private String deviceID;
53   private String swVersion;
54   private String hwVersion;
55
56   public DownloadOperation(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("download 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("download rpc requestXml= {}", requestXml);
86
87
88     NetConfServerProperties config =
89         NetConfServiceBooter.getApplicationContext().getBean(NetConfServerProperties.class);
90
91     final String baseUrl = config.getMapperPath() + "/download";
92     NetConfResponse restResponse =
93         XmlUtility.invokeMapperCall(baseUrl, requestXml, deviceID, swVersion, hwVersion);
94     Document document = null;
95
96     ErrorCodeDetails errorCode = restResponse.getErrorCode();
97     if (errorCode != null && errorCode.getFaultCode() != null
98         && !errorCode.getFaultCode().equalsIgnoreCase("0")) {
99       logger.error("Error recevied : {}", errorCode);
100       throw new DocumentedException(errorCode.getErrorMessage(),
101           ErrorType.from(errorCode.getErrorType()), ErrorTag.from(errorCode.getErrorTag()),
102           ErrorSeverity.from(errorCode.getErrorSeverity()));
103     } else if (restResponse.getNetconfResponseXml() != null) {
104       logger.debug("download rpc response received from mapper: {}",
105           restResponse.getNetconfResponseXml());
106       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
107       factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
108       factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
109       DocumentBuilder builder;
110       try {
111         Node child = requestMessage.createElement(XmlNetconfConstants.OK);
112         element.appendChild(child);
113         String xmlStr = XmlUtility.convertDocumentToString(element);
114         try {
115           builder = factory.newDocumentBuilder();
116           document = builder.parse(new InputSource(new StringReader(xmlStr)));
117         } catch (Exception e) {
118           logger.error("Error while converting String to element: {}", e.getMessage());
119           throw new DocumentedException("Operation Aborted", ErrorType.from("application"),
120               ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR"));
121         }
122       } catch (Exception e) {
123         logger.error("Error while contruscting the response: {}", e.getMessage());
124         throw new DocumentedException("Operation Aborted", ErrorType.from("application"),
125             ErrorTag.from("operation-failed"), ErrorSeverity.from("ERROR"));
126       }
127     }
128
129     return document;
130   }
131
132   protected HandlingPriority canHandle(final String operationName,
133       final String operationNamespace) {
134     return operationName.equals(getOperationName())
135         && operationNamespace.equals(getOperationNamespace())
136             ? HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1100)
137             : HandlingPriority.CANNOT_HANDLE;
138   }
139
140   public static final class OperationNameAndNamespace {
141     private final String operationName;
142     private final String namespace;
143
144     private final XmlElement operationElement;
145
146     public OperationNameAndNamespace(final Document message) throws DocumentedException {
147       XmlElement requestElement = null;
148       requestElement = getRequestElementWithCheck(message);
149       operationElement = requestElement.getOnlyChildElement();
150       operationName = operationElement.getName();
151       namespace = operationElement.getNamespace();
152     }
153
154     public String getOperationName() {
155       return operationName;
156     }
157
158     public String getNamespace() {
159       return namespace;
160     }
161
162     public XmlElement getOperationElement() {
163       return operationElement;
164     }
165
166   }
167
168   protected static XmlElement getRequestElementWithCheck(final Document message)
169       throws DocumentedException {
170     return XmlElement.fromDomElementWithExpected(message.getDocumentElement(),
171         XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
172   }
173
174   protected String getOperationNamespace() {
175     return OP_NAMESPACE;
176   }
177
178   protected String getOperationName() {
179     return OP_NAME;
180   }
181
182 }