2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
6 * Modifications Copyright (c) 2021 AT&T
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.ccsdk.sli.plugins.restconfapicall;
24 import static com.google.common.base.Strings.repeat;
25 import static java.lang.String.format;
26 import static java.lang.String.valueOf;
27 import static org.apache.commons.lang3.StringUtils.join;
28 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.DELETE;
29 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.GET;
30 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.PATCH;
31 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.PUT;
32 import static org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode.parseParam;
33 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COLON;
34 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COMMA;
35 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HEADER;
36 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HTTP_REQ;
37 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HTTP_RES;
38 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.REQ_ERR;
39 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_CODE;
40 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_MSG;
41 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_PRE;
42 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getSchemaCtxFromDir;
43 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getUpdatedXmlReq;
44 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getYangParameters;
45 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.parseUrl;
46 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfListenerFactory.instance;
47 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.FORMAT_ERR;
48 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.UTF_HEADER;
49 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.XML_TREE_ERR;
50 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.getXmlWriter;
51 import static org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.MdsalPropertiesNodeUtils.getModuleNamespace;
52 import com.google.gson.Gson;
53 import com.google.gson.JsonElement;
54 import com.google.gson.JsonObject;
55 import com.google.gson.JsonParser;
56 import com.google.gson.stream.JsonWriter;
57 import java.io.StringWriter;
58 import java.io.Writer;
59 import java.net.SocketException;
61 import java.util.HashMap;
62 import java.util.Iterator;
63 import java.util.List;
65 import org.dom4j.Document;
66 import org.dom4j.DocumentException;
67 import org.dom4j.DocumentHelper;
68 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
69 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
70 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
71 import org.onap.ccsdk.sli.plugins.restapicall.Format;
72 import org.onap.ccsdk.sli.plugins.restapicall.HttpResponse;
73 import org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode;
74 import org.onap.ccsdk.sli.plugins.restapicall.XmlParser;
75 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DataFormatSerializer;
76 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DataFormatSerializerContext;
77 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerFactory;
78 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.Listener;
79 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.MdsalSerializerHelper;
80 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.SerializerHelper;
81 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.YangParameters;
82 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.MdsalPropertiesNodeSerializer;
83 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.Namespace;
84 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.PropertiesNodeSerializer;
85 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
86 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
87 import org.opendaylight.yangtools.yang.common.XMLNamespace;
88 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
89 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
90 import org.opendaylight.yangtools.yang.model.parser.api.YangParserException;
91 import org.opendaylight.yangtools.yang.model.parser.api.YangParserFactory;
92 import org.slf4j.Logger;
93 import org.slf4j.LoggerFactory;
96 * Representation of a plugin to enable RESTCONF based CRUD operations from DG.
98 public class RestconfApiCallNode implements SvcLogicJavaPlugin {
101 * Logger for the restconf api call node class.
103 private static final Logger log = LoggerFactory.getLogger(
104 RestconfApiCallNode.class);
107 * Rest api call node service instance
109 private RestapiCallNode restapiCallNode;
112 * Yang parser factory
114 private YangParserFactory parserFactory;
118 * Creates an instance of restconf api call node with restapi call node, within OSGi
120 * @param r restapi call node
121 * @param parserFactory Yang parser factory
123 public RestconfApiCallNode(RestapiCallNode r, YangParserFactory parserFactory) {
124 this.restapiCallNode = r;
125 this.parserFactory = parserFactory;
129 * Returns the restapi call node instance.
132 public RestapiCallNode getRestapiCallNode() {
133 return restapiCallNode;
138 * Returns the yang parser factory instance
141 public YangParserFactory getParserFactory() {
142 return parserFactory;
146 * set the yang parser factory instance
149 public void setParserFactory(YangParserFactory parserFactory) {
150 this.parserFactory = parserFactory;
156 * Sends the restconf request using the parameters map and the memory
157 * context. And this method allows the directed graphs to interact with
158 * the restconf api call node
160 * @param paramMap parameters map
161 * @param ctx service logic context
162 * @throws SvcLogicException when svc logic exception occurs
164 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx)
165 throws SvcLogicException {
166 sendRequest(paramMap, ctx, 0);
170 * Sends the restconf request using the parameters map and the memory
171 * context along with the retry count.
173 * @param paramMap parameters map
174 * @param ctx service logic context
175 * @param retryCount number of retry counts
176 * @throws SvcLogicException when svc logic exception occurs
178 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx,
179 Integer retryCount) throws SvcLogicException {
180 RestapiCallNode rest = getRestapiCallNode();
181 HttpResponse r = new HttpResponse();
183 YangParameters p = getYangParameters(paramMap);
185 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
186 Map<String, String> props = new HashMap<>((Map)ctx.toProperties());
187 String uri = parseUrl(p.restapiUrl, p.httpMethod);
188 InstanceIdentifierContext<?> insIdCtx = getInsIdCtx(p, uri);
191 if (p.httpMethod != GET && p.httpMethod != DELETE) {
192 req = serializeRequest(props, p, uri, insIdCtx);
193 if (p.httpMethod == PUT || p.httpMethod == PATCH) {
194 updateReq(req, p, insIdCtx);
197 if (req == null && p.requestBody != null) {
201 r = rest.sendHttpRequest(req, p);
202 if (p.returnRequestPayload && req != null) {
203 ctx.setAttribute(pp + HTTP_REQ, req);
206 String response = getResponse(ctx, p, pp, r);
207 if (response != null) {
209 Map<String, String> resProp = serializeResponse(
210 p, uri, response, insIdCtx);
211 for (Map.Entry<String, String> pro : resProp.entrySet()) {
212 ctx.setAttribute(pro.getKey(), pro.getValue());
214 } catch (SvcLogicException e) {
215 convertToNormalRes(ctx, p, pp, response);
218 } catch (SvcLogicException e) {
219 boolean shouldRetry = false;
220 if (e.getCause().getCause() instanceof SocketException) {
224 log.error(REQ_ERR + e.getMessage(), e);
225 String prefix = parseParam(paramMap, RES_PRE, false, null);
226 setFailureResponseStatus(ctx, prefix, e.getMessage());
229 if (r != null && r.code >= 300) {
230 throw new SvcLogicException(valueOf(r.code) +
231 COLON + " " + r.message);
235 private void convertToNormalRes(SvcLogicContext ctx ,
236 YangParameters p, String pp, String body)
237 throws SvcLogicException {
238 if (p.convertResponse) {
239 Map<String, String> mm = null;
240 if (p.format == Format.XML) {
241 mm = XmlParser.convertToProperties(body, p.listNameList);
242 } else if (p.format == Format.JSON) {
243 mm = org.onap.ccsdk.sli.plugins.restapicall.JsonParser
244 .convertToProperties(body);
248 for (Map.Entry<String, String> entry : mm.entrySet()) {
249 ctx.setAttribute(pp + entry.getKey(),
257 * Serializes the request message to JSON or XML from the properties.
259 * @param properties properties
260 * @param params YANG parameters
262 * @param insIdCtx instance identifier context
263 * @return JSON or XML message to be sent
264 * @throws SvcLogicException when serializing the request fails
266 public String serializeRequest(Map<String, String> properties,
267 YangParameters params, String uri,
268 InstanceIdentifierContext insIdCtx)
269 throws SvcLogicException {
270 PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
271 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
272 DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
273 null, uri, null, propSer);
274 DataFormatSerializer ser = DfSerializerFactory.instance()
275 .getSerializer(serCtx, params);
276 //TODO: Handling of XML annotations
277 return ser.encode(properties, null);
281 * Serializes the response message from JSON or XML to the properties.
283 * @param params YANG parameters
285 * @param response response message
286 * @param insIdCtx instance identifier context
287 * @return response message as properties
288 * @throws SvcLogicException when serializing the response fails
290 public Map<String, String> serializeResponse(YangParameters params,
291 String uri, String response,
292 InstanceIdentifierContext insIdCtx)
293 throws SvcLogicException {
294 PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
295 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
296 SerializerHelper helper = new MdsalSerializerHelper(
297 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
298 Listener listener = instance().getListener(helper, params);
299 DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
300 listener, uri, null, propSer);
301 DataFormatSerializer ser = DfSerializerFactory.instance()
302 .getSerializer(serCtx, params);
303 return ser.decode(response);
307 * Returns instance identifier context for a uri using the schema context.
309 * @param params YANG parameters
311 * @return instance identifier context
312 * @throws SvcLogicException when getting schema context fails
314 private InstanceIdentifierContext<?> getInsIdCtx(YangParameters params,
316 throws SvcLogicException {
317 EffectiveModelContext context = getSchemaContext(params);
318 return ParserIdentifier.toInstanceIdentifier(uri, context, null);
322 * Returns the global schema context or schema context of particular YANG
323 * files present in a directory path.
325 * @param params YANG parameters
326 * @return schema context
327 * @throws SvcLogicException when schema context fetching fails
329 private EffectiveModelContext getSchemaContext(YangParameters params) throws SvcLogicException {
332 if (params.dirPath != null) {
333 return getSchemaCtxFromDir(getParserFactory(), params.dirPath);
335 return (getParserFactory().createParser().buildEffectiveModel());
337 } catch (YangParserException e) {
338 throw new SvcLogicException("Caught exception creating yang model context", e);
343 * Returns the response message body of a http response message.
345 * @param ctx svc logic context
346 * @param params parameters
347 * @param pre prefix to be appended
348 * @param res http response
349 * @return response message body
351 public String getResponse(SvcLogicContext ctx, YangParameters params,
352 String pre, HttpResponse res) {
353 ctx.setAttribute(pre + RES_CODE, valueOf(res.code));
354 ctx.setAttribute(pre + RES_MSG, res.message);
356 if (params.dumpHeaders && res.headers != null) {
357 for (Map.Entry<String, List<String>> a : res.headers.entrySet()) {
358 ctx.setAttribute(pre + HEADER + a.getKey(),
359 join(a.getValue(), COMMA));
363 if (res.body != null && res.body.trim().length() > 0) {
364 ctx.setAttribute(pre + HTTP_RES, res.body);
371 * Sets the failure response status in the context memory.
373 * @param ctx service logic context
374 * @param prefix prefix to be added
375 * @param errMsg error message
377 private void setFailureResponseStatus(SvcLogicContext ctx, String prefix,
379 HttpResponse res = new HttpResponse();
381 res.message = errMsg;
382 ctx.setAttribute(prefix + RES_CODE, valueOf(res.code));
383 ctx.setAttribute(prefix + RES_MSG, res.message);
387 * Updates request message for JSON and XML data format, when the HTTP
388 * method points it as PUT or PATCH.
390 * @param req current request message
391 * @param p YANG parameters
392 * @param insIdCtx instance identifier context
393 * @return update request message
394 * @throws SvcLogicException when the data format type is wrong
396 public String updateReq(String req, YangParameters p,
397 InstanceIdentifierContext<?> insIdCtx)
398 throws SvcLogicException {
400 SchemaNode schemaNode = insIdCtx.getSchemaNode();
401 Namespace modNs = getModuleNamespace(schemaNode.getQName(),
402 insIdCtx.getSchemaContext());
403 String nodeName = schemaNode.getQName().getLocalName();
407 return getUpdatedJsonReq(req, nodeName, modNs.moduleName());
410 return getXmlReqForPutOp(req, nodeName, modNs.moduleNs());
413 throw new SvcLogicException(format(FORMAT_ERR, p.format));
418 * Returns the updated JSON request message, when the HTTP method
419 * points to PUT or PATCH.
421 * @param req current JSON request message
422 * @param nodeName root node name
423 * @param modName module name of the root node
424 * @return update JSON request message
426 private String getUpdatedJsonReq(String req, String nodeName,
428 Writer writer = new StringWriter();
429 JsonWriter jsonWriter = new JsonWriter(writer);
430 jsonWriter.setIndent(repeat(" ", 4));
432 JsonParser jsonParser = new JsonParser();
433 JsonObject oldJson = (JsonObject)jsonParser.parse(req);
434 oldJson = remChildModName(oldJson, modName);
435 JsonObject newJson = new JsonObject();
436 newJson.add(modName + COLON + nodeName, oldJson.deepCopy());
438 Gson gson= new Gson();
439 gson.toJson(newJson, jsonWriter);
440 return writer.toString();
444 * Removes module name from all the updated first level child node, if it
445 * is same as the root node added.
447 * @param oldJson JSON object for old request
448 * @param modName module name of root node
449 * @return JSON object for old request with updated child module name
451 private JsonObject remChildModName(JsonObject oldJson, String modName) {
452 Iterator<Map.Entry<String, JsonElement>> it = oldJson.entrySet().iterator();
453 Map<String, JsonElement> m = new HashMap<>();
454 while (it.hasNext()) {
455 Map.Entry<String, JsonElement> jNode = it.next();
456 if (jNode.getKey().contains(COLON)) {
457 String[] modArr = jNode.getKey().split(COLON);
458 if (modArr[0].equals(modName)) {
460 m.put(modArr[1], jNode.getValue());
465 for (Map.Entry<String, JsonElement> element : m.entrySet()) {
466 oldJson.add(element.getKey(), element.getValue());
473 * Returns the updated XML request message, when the HTTP method points
476 * @param req current JSON request message
477 * @param nodeName root node name
478 * @param modNs module namespace of the root node
479 * @return update JSON request message
480 * @throws SvcLogicException when XML parsing fails
482 private String getXmlReqForPutOp(String req, String nodeName,
483 XMLNamespace modNs) throws SvcLogicException {
484 req = getUpdatedXmlReq(req, nodeName, modNs.toString());
487 oldDoc = DocumentHelper.parseText(req);
488 } catch (DocumentException e) {
489 throw new SvcLogicException(XML_TREE_ERR, e);
491 Writer writer = getXmlWriter(
492 UTF_HEADER + oldDoc.getRootElement().asXML(), "4");
493 return writer.toString();