2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.ccsdk.sli.plugins.restconfapicall;
23 import com.google.gson.Gson;
24 import com.google.gson.JsonElement;
25 import com.google.gson.JsonObject;
26 import com.google.gson.JsonParser;
27 import com.google.gson.stream.JsonWriter;
29 import javax.ws.rs.core.UriBuilder;
30 import java.io.StringWriter;
31 import java.io.Writer;
32 import java.net.SocketException;
34 import java.net.URISyntaxException;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
40 import org.dom4j.Document;
41 import org.dom4j.DocumentException;
42 import org.dom4j.DocumentHelper;
43 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
44 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
45 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
46 import org.onap.ccsdk.sli.plugins.restapicall.Format;
47 import org.onap.ccsdk.sli.plugins.restapicall.HttpResponse;
48 import org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode;
49 import org.onap.ccsdk.sli.plugins.restapicall.XmlParser;
50 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DataFormatSerializer;
51 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DataFormatSerializerContext;
52 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerFactory;
53 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.Listener;
54 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.MdsalSerializerHelper;
55 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.SerializerHelper;
56 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.YangParameters;
57 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.MdsalPropertiesNodeSerializer;
58 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.Namespace;
59 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.PropertiesNodeSerializer;
60 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
61 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
64 import org.osgi.framework.BundleContext;
65 import org.osgi.framework.ServiceReference;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 import static com.google.common.base.Strings.repeat;
70 import static java.lang.String.format;
71 import static java.lang.String.valueOf;
72 import static org.apache.commons.lang3.StringUtils.join;
73 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.DELETE;
74 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.GET;
75 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.PATCH;
76 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.PUT;
77 import static org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode.parseParam;
78 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.ATTEMPTS_MSG;
79 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COLON;
80 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COMMA;
81 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COMM_FAIL;
82 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HEADER;
83 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HTTP_REQ;
84 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HTTP_RES;
85 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.MAX_RETRY_ERR;
86 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.NO_MORE_RETRY;
87 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.REQ_ERR;
88 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.REST_API_URL;
89 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_CODE;
90 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_MSG;
91 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_PRE;
92 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RETRY_COUNT;
93 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RETRY_FAIL;
94 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.UPDATED_URL;
95 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getSchemaCtxFromDir;
96 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getUpdatedXmlReq;
97 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getYangParameters;
98 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.parseUrl;
99 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfListenerFactory.instance;
100 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.FORMAT_ERR;
101 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.UTF_HEADER;
102 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.XML_TREE_ERR;
103 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.getXmlWriter;
104 import static org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.MdsalPropertiesNodeUtils.getModuleNamespace;
105 import static org.osgi.framework.FrameworkUtil.getBundle;
108 * Representation of a plugin to enable RESTCONF based CRUD operations from DG.
110 public class RestconfApiCallNode implements SvcLogicJavaPlugin {
113 * Logger for the restconf api call node class.
115 private static final Logger log = LoggerFactory.getLogger(
116 RestconfApiCallNode.class);
119 * Rest api call node service instance
121 private RestapiCallNode restapiCallNode;
124 * Creates an instance of restconf api call node with restapi call node.
126 * @param r restapi call node
128 public RestconfApiCallNode(RestapiCallNode r) {
129 this.restapiCallNode = r;
133 * Returns the restapi call node instance.
136 public RestapiCallNode getRestapiCallNode() {
137 return restapiCallNode;
141 * Sends the restconf request using the parameters map and the memory
142 * context. And this method allows the directed graphs to interact with
143 * the restconf api call node
145 * @param paramMap parameters map
146 * @param ctx service logic context
147 * @throws SvcLogicException when svc logic exception occurs
149 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx)
150 throws SvcLogicException {
151 sendRequest(paramMap, ctx, 0);
155 * Sends the restconf request using the parameters map and the memory
156 * context along with the retry count.
158 * @param paramMap parameters map
159 * @param ctx service logic context
160 * @param retryCount number of retry counts
161 * @throws SvcLogicException when svc logic exception occurs
163 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx,
164 Integer retryCount) throws SvcLogicException {
165 RestapiCallNode rest = getRestapiCallNode();
166 HttpResponse r = new HttpResponse();
168 YangParameters p = getYangParameters(paramMap);
170 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
171 Map<String, String> props = new HashMap<>((Map)ctx.toProperties());
172 String uri = parseUrl(p.restapiUrl, p.httpMethod);
173 InstanceIdentifierContext<?> insIdCtx = getInsIdCtx(p, uri);
176 if (p.httpMethod != GET && p.httpMethod != DELETE) {
177 req = serializeRequest(props, p, uri, insIdCtx);
178 if (p.httpMethod == PUT || p.httpMethod == PATCH) {
179 updateReq(req, p, insIdCtx);
182 if (req == null && p.requestBody != null) {
186 r = rest.sendHttpRequest(req, p);
187 if (p.returnRequestPayload && req != null) {
188 ctx.setAttribute(pp + HTTP_REQ, req);
191 String response = getResponse(ctx, p, pp, r);
192 if (response != null) {
194 Map<String, String> resProp = serializeResponse(
195 p, uri, response, insIdCtx);
196 for (Map.Entry<String, String> pro : resProp.entrySet()) {
197 ctx.setAttribute(pro.getKey(), pro.getValue());
199 } catch (SvcLogicException e) {
200 convertToNormalRes(ctx, p, pp, response);
203 } catch (SvcLogicException e) {
204 boolean shouldRetry = false;
205 if (e.getCause().getCause() instanceof SocketException) {
209 log.error(REQ_ERR + e.getMessage(), e);
210 String prefix = parseParam(paramMap, RES_PRE, false, null);
211 setFailureResponseStatus(ctx, prefix, e.getMessage());
214 if (r != null && r.code >= 300) {
215 throw new SvcLogicException(valueOf(r.code) +
216 COLON + " " + r.message);
220 private void convertToNormalRes(SvcLogicContext ctx ,
221 YangParameters p, String pp, String body)
222 throws SvcLogicException {
223 if (p.convertResponse) {
224 Map<String, String> mm = null;
225 if (p.format == Format.XML) {
226 mm = XmlParser.convertToProperties(body, p.listNameList);
227 } else if (p.format == Format.JSON) {
228 mm = org.onap.ccsdk.sli.plugins.restapicall.JsonParser
229 .convertToProperties(body);
233 for (Map.Entry<String, String> entry : mm.entrySet()) {
234 ctx.setAttribute(pp + entry.getKey(),
242 * Serializes the request message to JSON or XML from the properties.
244 * @param properties properties
245 * @param params YANG parameters
247 * @param insIdCtx instance identifier context
248 * @return JSON or XML message to be sent
249 * @throws SvcLogicException when serializing the request fails
251 public String serializeRequest(Map<String, String> properties,
252 YangParameters params, String uri,
253 InstanceIdentifierContext insIdCtx)
254 throws SvcLogicException {
255 PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
256 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
257 DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
258 null, uri, null, propSer);
259 DataFormatSerializer ser = DfSerializerFactory.instance()
260 .getSerializer(serCtx, params);
261 //TODO: Handling of XML annotations
262 return ser.encode(properties, null);
266 * Serializes the response message from JSON or XML to the properties.
268 * @param params YANG parameters
270 * @param response response message
271 * @param insIdCtx instance identifier context
272 * @return response message as properties
273 * @throws SvcLogicException when serializing the response fails
275 public Map<String, String> serializeResponse(YangParameters params,
276 String uri, String response,
277 InstanceIdentifierContext insIdCtx)
278 throws SvcLogicException {
279 PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
280 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
281 SerializerHelper helper = new MdsalSerializerHelper(
282 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
283 Listener listener = instance().getListener(helper, params);
284 DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
285 listener, uri, null, propSer);
286 DataFormatSerializer ser = DfSerializerFactory.instance()
287 .getSerializer(serCtx, params);
288 return ser.decode(response);
292 * Returns instance identifier context for a uri using the schema context.
294 * @param params YANG parameters
296 * @return instance identifier context
297 * @throws SvcLogicException when getting schema context fails
299 private InstanceIdentifierContext<?> getInsIdCtx(YangParameters params,
301 throws SvcLogicException {
302 SchemaContext context = getSchemaContext(params);
303 return ParserIdentifier.toInstanceIdentifier(uri, context, null);
307 * Returns the global schema context or schema context of particular YANG
308 * files present in a directory path.
310 * @param params YANG parameters
311 * @return schema context
312 * @throws SvcLogicException when schema context fetching fails
314 private SchemaContext getSchemaContext(YangParameters params)
315 throws SvcLogicException {
316 if (params.dirPath != null) {
317 return getSchemaCtxFromDir(params.dirPath);
319 BundleContext bc = getBundle(SchemaContext.class).getBundleContext();
320 SchemaContext schemaContext = null;
322 ServiceReference reference = bc.getServiceReference(
323 SchemaContext.class);
324 if (reference != null) {
325 schemaContext = (SchemaContext) bc.getService(reference);
328 return schemaContext;
332 * Returns the response message body of a http response message.
334 * @param ctx svc logic context
335 * @param params parameters
336 * @param pre prefix to be appended
337 * @param res http response
338 * @return response message body
340 public String getResponse(SvcLogicContext ctx, YangParameters params,
341 String pre, HttpResponse res) {
342 ctx.setAttribute(pre + RES_CODE, valueOf(res.code));
343 ctx.setAttribute(pre + RES_MSG, res.message);
345 if (params.dumpHeaders && res.headers != null) {
346 for (Map.Entry<String, List<String>> a : res.headers.entrySet()) {
347 ctx.setAttribute(pre + HEADER + a.getKey(),
348 join(a.getValue(), COMMA));
352 if (res.body != null && res.body.trim().length() > 0) {
353 ctx.setAttribute(pre + HTTP_RES, res.body);
360 * Sets the failure response status in the context memory.
362 * @param ctx service logic context
363 * @param prefix prefix to be added
364 * @param errMsg error message
366 private void setFailureResponseStatus(SvcLogicContext ctx, String prefix,
368 HttpResponse res = new HttpResponse();
370 res.message = errMsg;
371 ctx.setAttribute(prefix + RES_CODE, valueOf(res.code));
372 ctx.setAttribute(prefix + RES_MSG, res.message);
376 * Updates request message for JSON and XML data format, when the HTTP
377 * method points it as PUT or PATCH.
379 * @param req current request message
380 * @param p YANG parameters
381 * @param insIdCtx instance identifier context
382 * @return update request message
383 * @throws SvcLogicException when the data format type is wrong
385 public String updateReq(String req, YangParameters p,
386 InstanceIdentifierContext<?> insIdCtx)
387 throws SvcLogicException {
389 SchemaNode schemaNode = insIdCtx.getSchemaNode();
390 Namespace modNs = getModuleNamespace(schemaNode.getQName(),
391 insIdCtx.getSchemaContext());
392 String nodeName = schemaNode.getQName().getLocalName();
396 return getUpdatedJsonReq(req, nodeName, modNs.moduleName());
399 return getXmlReqForPutOp(req, nodeName, modNs.moduleNs());
402 throw new SvcLogicException(format(FORMAT_ERR, p.format));
407 * Returns the updated JSON request message, when the HTTP method
408 * points to PUT or PATCH.
410 * @param req current JSON request message
411 * @param nodeName root node name
412 * @param modName module name of the root node
413 * @return update JSON request message
415 private String getUpdatedJsonReq(String req, String nodeName,
417 Writer writer = new StringWriter();
418 JsonWriter jsonWriter = new JsonWriter(writer);
419 jsonWriter.setIndent(repeat(" ", 4));
421 JsonParser jsonParser = new JsonParser();
422 JsonObject oldJson = (JsonObject)jsonParser.parse(req);
423 oldJson = remChildModName(oldJson, modName);
424 JsonObject newJson = new JsonObject();
425 newJson.add(modName + COLON + nodeName, oldJson.deepCopy());
427 Gson gson= new Gson();
428 gson.toJson(newJson, jsonWriter);
429 return writer.toString();
433 * Removes module name from all the updated first level child node, if it
434 * is same as the root node added.
436 * @param oldJson JSON object for old request
437 * @param modName module name of root node
438 * @return JSON object for old request with updated child module name
440 private JsonObject remChildModName(JsonObject oldJson, String modName) {
441 Iterator<Map.Entry<String, JsonElement>> it = oldJson.entrySet().iterator();
442 Map<String, JsonElement> m = new HashMap<>();
443 while (it.hasNext()) {
444 Map.Entry<String, JsonElement> jNode = it.next();
445 if (jNode.getKey().contains(COLON)) {
446 String[] modArr = jNode.getKey().split(COLON);
447 if (modArr[0].equals(modName)) {
449 m.put(modArr[1], jNode.getValue());
454 for (Map.Entry<String, JsonElement> element : m.entrySet()) {
455 oldJson.add(element.getKey(), element.getValue());
462 * Returns the updated XML request message, when the HTTP method points
465 * @param req current JSON request message
466 * @param nodeName root node name
467 * @param modNs module namespace of the root node
468 * @return update JSON request message
469 * @throws SvcLogicException when XML parsing fails
471 private String getXmlReqForPutOp(String req, String nodeName,
472 URI modNs) throws SvcLogicException {
473 req = getUpdatedXmlReq(req, nodeName, modNs.toString());
476 oldDoc = DocumentHelper.parseText(req);
477 } catch (DocumentException e) {
478 throw new SvcLogicException(XML_TREE_ERR, e);
480 Writer writer = getXmlWriter(
481 UTF_HEADER + oldDoc.getRootElement().asXML(), "4");
482 return writer.toString();