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 static com.google.common.base.Strings.repeat;
24 import static java.lang.String.format;
25 import static java.lang.String.valueOf;
26 import static org.apache.commons.lang3.StringUtils.join;
27 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.DELETE;
28 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.GET;
29 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.PATCH;
30 import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.PUT;
31 import static org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode.parseParam;
32 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COLON;
33 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COMMA;
34 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HEADER;
35 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HTTP_REQ;
36 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HTTP_RES;
37 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.REQ_ERR;
38 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_CODE;
39 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_MSG;
40 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_PRE;
41 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getSchemaCtxFromDir;
42 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getUpdatedXmlReq;
43 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getYangParameters;
44 import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.parseUrl;
45 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfListenerFactory.instance;
46 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.FORMAT_ERR;
47 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.UTF_HEADER;
48 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.XML_TREE_ERR;
49 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.getXmlWriter;
50 import static org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.MdsalPropertiesNodeUtils.getModuleNamespace;
51 import static org.osgi.framework.FrameworkUtil.getBundle;
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.model.api.EffectiveModelContext;
88 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
89 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
90 import org.osgi.framework.BundleContext;
91 import org.osgi.framework.ServiceReference;
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 * Creates an instance of restconf api call node with restapi call node.
114 * @param r restapi call node
116 public RestconfApiCallNode(RestapiCallNode r) {
117 this.restapiCallNode = r;
121 * Returns the restapi call node instance.
124 public RestapiCallNode getRestapiCallNode() {
125 return restapiCallNode;
129 * Sends the restconf request using the parameters map and the memory
130 * context. And this method allows the directed graphs to interact with
131 * the restconf api call node
133 * @param paramMap parameters map
134 * @param ctx service logic context
135 * @throws SvcLogicException when svc logic exception occurs
137 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx)
138 throws SvcLogicException {
139 sendRequest(paramMap, ctx, 0);
143 * Sends the restconf request using the parameters map and the memory
144 * context along with the retry count.
146 * @param paramMap parameters map
147 * @param ctx service logic context
148 * @param retryCount number of retry counts
149 * @throws SvcLogicException when svc logic exception occurs
151 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx,
152 Integer retryCount) throws SvcLogicException {
153 RestapiCallNode rest = getRestapiCallNode();
154 HttpResponse r = new HttpResponse();
156 YangParameters p = getYangParameters(paramMap);
158 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
159 Map<String, String> props = new HashMap<>((Map)ctx.toProperties());
160 String uri = parseUrl(p.restapiUrl, p.httpMethod);
161 InstanceIdentifierContext<?> insIdCtx = getInsIdCtx(p, uri);
164 if (p.httpMethod != GET && p.httpMethod != DELETE) {
165 req = serializeRequest(props, p, uri, insIdCtx);
166 if (p.httpMethod == PUT || p.httpMethod == PATCH) {
167 updateReq(req, p, insIdCtx);
170 if (req == null && p.requestBody != null) {
174 r = rest.sendHttpRequest(req, p);
175 if (p.returnRequestPayload && req != null) {
176 ctx.setAttribute(pp + HTTP_REQ, req);
179 String response = getResponse(ctx, p, pp, r);
180 if (response != null) {
182 Map<String, String> resProp = serializeResponse(
183 p, uri, response, insIdCtx);
184 for (Map.Entry<String, String> pro : resProp.entrySet()) {
185 ctx.setAttribute(pro.getKey(), pro.getValue());
187 } catch (SvcLogicException e) {
188 convertToNormalRes(ctx, p, pp, response);
191 } catch (SvcLogicException e) {
192 boolean shouldRetry = false;
193 if (e.getCause().getCause() instanceof SocketException) {
197 log.error(REQ_ERR + e.getMessage(), e);
198 String prefix = parseParam(paramMap, RES_PRE, false, null);
199 setFailureResponseStatus(ctx, prefix, e.getMessage());
202 if (r != null && r.code >= 300) {
203 throw new SvcLogicException(valueOf(r.code) +
204 COLON + " " + r.message);
208 private void convertToNormalRes(SvcLogicContext ctx ,
209 YangParameters p, String pp, String body)
210 throws SvcLogicException {
211 if (p.convertResponse) {
212 Map<String, String> mm = null;
213 if (p.format == Format.XML) {
214 mm = XmlParser.convertToProperties(body, p.listNameList);
215 } else if (p.format == Format.JSON) {
216 mm = org.onap.ccsdk.sli.plugins.restapicall.JsonParser
217 .convertToProperties(body);
221 for (Map.Entry<String, String> entry : mm.entrySet()) {
222 ctx.setAttribute(pp + entry.getKey(),
230 * Serializes the request message to JSON or XML from the properties.
232 * @param properties properties
233 * @param params YANG parameters
235 * @param insIdCtx instance identifier context
236 * @return JSON or XML message to be sent
237 * @throws SvcLogicException when serializing the request fails
239 public String serializeRequest(Map<String, String> properties,
240 YangParameters params, String uri,
241 InstanceIdentifierContext insIdCtx)
242 throws SvcLogicException {
243 PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
244 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
245 DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
246 null, uri, null, propSer);
247 DataFormatSerializer ser = DfSerializerFactory.instance()
248 .getSerializer(serCtx, params);
249 //TODO: Handling of XML annotations
250 return ser.encode(properties, null);
254 * Serializes the response message from JSON or XML to the properties.
256 * @param params YANG parameters
258 * @param response response message
259 * @param insIdCtx instance identifier context
260 * @return response message as properties
261 * @throws SvcLogicException when serializing the response fails
263 public Map<String, String> serializeResponse(YangParameters params,
264 String uri, String response,
265 InstanceIdentifierContext insIdCtx)
266 throws SvcLogicException {
267 PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
268 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
269 SerializerHelper helper = new MdsalSerializerHelper(
270 insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
271 Listener listener = instance().getListener(helper, params);
272 DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
273 listener, uri, null, propSer);
274 DataFormatSerializer ser = DfSerializerFactory.instance()
275 .getSerializer(serCtx, params);
276 return ser.decode(response);
280 * Returns instance identifier context for a uri using the schema context.
282 * @param params YANG parameters
284 * @return instance identifier context
285 * @throws SvcLogicException when getting schema context fails
287 private InstanceIdentifierContext<?> getInsIdCtx(YangParameters params,
289 throws SvcLogicException {
290 EffectiveModelContext context = getSchemaContext(params);
291 return ParserIdentifier.toInstanceIdentifier(uri, context, null);
295 * Returns the global schema context or schema context of particular YANG
296 * files present in a directory path.
298 * @param params YANG parameters
299 * @return schema context
300 * @throws SvcLogicException when schema context fetching fails
302 private EffectiveModelContext getSchemaContext(YangParameters params)
303 throws SvcLogicException {
304 if (params.dirPath != null) {
305 return getSchemaCtxFromDir(params.dirPath);
307 BundleContext bc = getBundle(SchemaContext.class).getBundleContext();
308 EffectiveModelContext schemaContext = null;
310 ServiceReference reference = bc.getServiceReference(
311 SchemaContext.class);
312 if (reference != null) {
313 schemaContext = (EffectiveModelContext) bc.getService(reference);
316 return schemaContext;
320 * Returns the response message body of a http response message.
322 * @param ctx svc logic context
323 * @param params parameters
324 * @param pre prefix to be appended
325 * @param res http response
326 * @return response message body
328 public String getResponse(SvcLogicContext ctx, YangParameters params,
329 String pre, HttpResponse res) {
330 ctx.setAttribute(pre + RES_CODE, valueOf(res.code));
331 ctx.setAttribute(pre + RES_MSG, res.message);
333 if (params.dumpHeaders && res.headers != null) {
334 for (Map.Entry<String, List<String>> a : res.headers.entrySet()) {
335 ctx.setAttribute(pre + HEADER + a.getKey(),
336 join(a.getValue(), COMMA));
340 if (res.body != null && res.body.trim().length() > 0) {
341 ctx.setAttribute(pre + HTTP_RES, res.body);
348 * Sets the failure response status in the context memory.
350 * @param ctx service logic context
351 * @param prefix prefix to be added
352 * @param errMsg error message
354 private void setFailureResponseStatus(SvcLogicContext ctx, String prefix,
356 HttpResponse res = new HttpResponse();
358 res.message = errMsg;
359 ctx.setAttribute(prefix + RES_CODE, valueOf(res.code));
360 ctx.setAttribute(prefix + RES_MSG, res.message);
364 * Updates request message for JSON and XML data format, when the HTTP
365 * method points it as PUT or PATCH.
367 * @param req current request message
368 * @param p YANG parameters
369 * @param insIdCtx instance identifier context
370 * @return update request message
371 * @throws SvcLogicException when the data format type is wrong
373 public String updateReq(String req, YangParameters p,
374 InstanceIdentifierContext<?> insIdCtx)
375 throws SvcLogicException {
377 SchemaNode schemaNode = insIdCtx.getSchemaNode();
378 Namespace modNs = getModuleNamespace(schemaNode.getQName(),
379 insIdCtx.getSchemaContext());
380 String nodeName = schemaNode.getQName().getLocalName();
384 return getUpdatedJsonReq(req, nodeName, modNs.moduleName());
387 return getXmlReqForPutOp(req, nodeName, modNs.moduleNs());
390 throw new SvcLogicException(format(FORMAT_ERR, p.format));
395 * Returns the updated JSON request message, when the HTTP method
396 * points to PUT or PATCH.
398 * @param req current JSON request message
399 * @param nodeName root node name
400 * @param modName module name of the root node
401 * @return update JSON request message
403 private String getUpdatedJsonReq(String req, String nodeName,
405 Writer writer = new StringWriter();
406 JsonWriter jsonWriter = new JsonWriter(writer);
407 jsonWriter.setIndent(repeat(" ", 4));
409 JsonParser jsonParser = new JsonParser();
410 JsonObject oldJson = (JsonObject)jsonParser.parse(req);
411 oldJson = remChildModName(oldJson, modName);
412 JsonObject newJson = new JsonObject();
413 newJson.add(modName + COLON + nodeName, oldJson.deepCopy());
415 Gson gson= new Gson();
416 gson.toJson(newJson, jsonWriter);
417 return writer.toString();
421 * Removes module name from all the updated first level child node, if it
422 * is same as the root node added.
424 * @param oldJson JSON object for old request
425 * @param modName module name of root node
426 * @return JSON object for old request with updated child module name
428 private JsonObject remChildModName(JsonObject oldJson, String modName) {
429 Iterator<Map.Entry<String, JsonElement>> it = oldJson.entrySet().iterator();
430 Map<String, JsonElement> m = new HashMap<>();
431 while (it.hasNext()) {
432 Map.Entry<String, JsonElement> jNode = it.next();
433 if (jNode.getKey().contains(COLON)) {
434 String[] modArr = jNode.getKey().split(COLON);
435 if (modArr[0].equals(modName)) {
437 m.put(modArr[1], jNode.getValue());
442 for (Map.Entry<String, JsonElement> element : m.entrySet()) {
443 oldJson.add(element.getKey(), element.getValue());
450 * Returns the updated XML request message, when the HTTP method points
453 * @param req current JSON request message
454 * @param nodeName root node name
455 * @param modNs module namespace of the root node
456 * @return update JSON request message
457 * @throws SvcLogicException when XML parsing fails
459 private String getXmlReqForPutOp(String req, String nodeName,
460 URI modNs) throws SvcLogicException {
461 req = getUpdatedXmlReq(req, nodeName, modNs.toString());
464 oldDoc = DocumentHelper.parseText(req);
465 } catch (DocumentException e) {
466 throw new SvcLogicException(XML_TREE_ERR, e);
468 Writer writer = getXmlWriter(
469 UTF_HEADER + oldDoc.getRootElement().asXML(), "4");
470 return writer.toString();