summaryrefslogtreecommitdiffstats
path: root/plugins/restconf-client/provider/src/main/java/org/onap/ccsdk/sli/plugins/restconfapicall/RestconfApiCallNode.java
blob: b5a9df706fa06fde4ed6e8e91046a2c21ed1c81d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*-
 * ============LICENSE_START=======================================================
 * ONAP - CCSDK
 * ================================================================================
 * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
 * Modifications Copyright (c) 2021 AT&T
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.ccsdk.sli.plugins.restconfapicall;

import static com.google.common.base.Strings.repeat;
import static java.lang.String.format;
import static java.lang.String.valueOf;
import static org.apache.commons.lang3.StringUtils.join;
import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.DELETE;
import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.GET;
import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.PATCH;
import static org.onap.ccsdk.sli.plugins.restapicall.HttpMethod.PUT;
import static org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode.parseParam;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COLON;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.COMMA;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HEADER;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HTTP_REQ;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.HTTP_RES;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.REQ_ERR;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_CODE;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_MSG;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.RES_PRE;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getSchemaCtxFromDir;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getUpdatedXmlReq;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.getYangParameters;
import static org.onap.ccsdk.sli.plugins.restconfapicall.RestconfApiUtils.parseUrl;
import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfListenerFactory.instance;
import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.FORMAT_ERR;
import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.UTF_HEADER;
import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.XML_TREE_ERR;
import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerUtil.getXmlWriter;
import static org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.MdsalPropertiesNodeUtils.getModuleNamespace;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.SocketException;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
import org.onap.ccsdk.sli.core.sli.SvcLogicException;
import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
import org.onap.ccsdk.sli.plugins.restapicall.Format;
import org.onap.ccsdk.sli.plugins.restapicall.HttpResponse;
import org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode;
import org.onap.ccsdk.sli.plugins.restapicall.XmlParser;
import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DataFormatSerializer;
import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DataFormatSerializerContext;
import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.DfSerializerFactory;
import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.Listener;
import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.MdsalSerializerHelper;
import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.SerializerHelper;
import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.YangParameters;
import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.MdsalPropertiesNodeSerializer;
import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.Namespace;
import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.PropertiesNodeSerializer;
import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.parser.api.YangParserException;
import org.opendaylight.yangtools.yang.model.parser.api.YangParserFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Representation of a plugin to enable RESTCONF based CRUD operations from DG.
 */
public class RestconfApiCallNode implements SvcLogicJavaPlugin {

    /**
     * Logger for the restconf api call node class.
     */
    private static final Logger log = LoggerFactory.getLogger(
            RestconfApiCallNode.class);

    /**
     * Rest api call node service instance
     */
    private RestapiCallNode restapiCallNode;

    /**
     * Yang parser factory
     */
    private YangParserFactory parserFactory;


    /**
     * Creates an instance of restconf api call node with restapi call node, within OSGi
     *
     * @param r restapi call node
     * @param parserFactory Yang parser factory
     */
    public RestconfApiCallNode(RestapiCallNode r, YangParserFactory parserFactory) {
        this.restapiCallNode = r;
        this.parserFactory = parserFactory;
    }

    /**
     * Returns the restapi call node instance.
     * @return
     */
    public RestapiCallNode getRestapiCallNode() {
        return restapiCallNode;
    }


    /**
     * Returns the yang parser factory instance
     * @return
     */
    public YangParserFactory getParserFactory() {
        return parserFactory;
    }

    /**
     * set the yang parser factory instance
     * @return
     */
    public void setParserFactory(YangParserFactory parserFactory) {
        this.parserFactory = parserFactory;
    }



    /**
     * Sends the restconf request using the parameters map and the memory
     * context. And this method allows the directed graphs to interact with
     * the restconf api call node
     *
     * @param paramMap parameters map
     * @param ctx      service logic context
     * @throws SvcLogicException when svc logic exception occurs
     */
    public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx)
            throws SvcLogicException {
        sendRequest(paramMap, ctx, 0);
    }

    /**
     * Sends the restconf request using the parameters map and the memory
     * context along with the retry count.
     *
     * @param paramMap   parameters map
     * @param ctx        service logic context
     * @param retryCount number of retry counts
     * @throws SvcLogicException when svc logic exception occurs
     */
    public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx,
                            Integer retryCount) throws SvcLogicException {
        RestapiCallNode rest = getRestapiCallNode();
        HttpResponse r = new HttpResponse();
        try {
            YangParameters p = getYangParameters(paramMap);

            String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
            Map<String, String> props = new HashMap<>((Map)ctx.toProperties());
            String uri = parseUrl(p.restapiUrl, p.httpMethod);
            InstanceIdentifierContext<?> insIdCtx = getInsIdCtx(p, uri);

            String req = null;
            if (p.httpMethod != GET && p.httpMethod != DELETE) {
                req = serializeRequest(props, p, uri, insIdCtx);
                if (p.httpMethod == PUT || p.httpMethod == PATCH) {
                    updateReq(req, p, insIdCtx);
                }
            }
            if (req == null && p.requestBody != null) {
                req = p.requestBody;
            }

            r = rest.sendHttpRequest(req, p);
            if (p.returnRequestPayload && req != null) {
                ctx.setAttribute(pp + HTTP_REQ, req);
            }

            String response = getResponse(ctx, p, pp, r);
            if (response != null) {
                try {
                    Map<String, String> resProp = serializeResponse(
                            p, uri, response, insIdCtx);
                    for (Map.Entry<String, String> pro : resProp.entrySet()) {
                        ctx.setAttribute(pro.getKey(), pro.getValue());
                    }
                } catch (SvcLogicException e) {
                    convertToNormalRes(ctx, p, pp, response);
                }
            }
        } catch (SvcLogicException e) {
            boolean shouldRetry = false;
            if (e.getCause().getCause() instanceof SocketException) {
                shouldRetry = true;
            }

            log.error(REQ_ERR + e.getMessage(), e);
            String prefix = parseParam(paramMap, RES_PRE, false, null);
            setFailureResponseStatus(ctx, prefix, e.getMessage());
        }

        if (r != null && r.code >= 300) {
            throw new SvcLogicException(valueOf(r.code) +
                                                COLON + " " + r.message);
        }
    }

    private void convertToNormalRes(SvcLogicContext ctx ,
                                    YangParameters p, String pp, String body)
            throws SvcLogicException {
        if (p.convertResponse) {
            Map<String, String> mm = null;
            if (p.format == Format.XML) {
                mm = XmlParser.convertToProperties(body, p.listNameList);
            } else if (p.format == Format.JSON) {
                mm = org.onap.ccsdk.sli.plugins.restapicall.JsonParser
                        .convertToProperties(body);
            }

            if (mm != null) {
                for (Map.Entry<String, String> entry : mm.entrySet()) {
                    ctx.setAttribute(pp + entry.getKey(),
                                     entry.getValue());
                }
            }
        }
    }

    /**
     * Serializes the request message to JSON or XML from the properties.
     *
     * @param properties properties
     * @param params     YANG parameters
     * @param uri        URI
     * @param insIdCtx   instance identifier context
     * @return JSON or XML message to be sent
     * @throws SvcLogicException when serializing the request fails
     */
     public String serializeRequest(Map<String, String> properties,
                                    YangParameters params, String uri,
                                    InstanceIdentifierContext insIdCtx)
             throws SvcLogicException {
        PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
                insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
        DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
                null, uri, null, propSer);
        DataFormatSerializer ser = DfSerializerFactory.instance()
                .getSerializer(serCtx, params);
         //TODO: Handling of XML annotations
        return ser.encode(properties, null);
    }

    /**
     * Serializes the response message from JSON or XML to the properties.
     *
     * @param params   YANG parameters
     * @param uri      URI
     * @param response response message
     * @param insIdCtx instance identifier context
     * @return response message as properties
     * @throws SvcLogicException when serializing the response fails
     */
    public Map<String, String> serializeResponse(YangParameters params,
                                                 String uri, String response,
                                                 InstanceIdentifierContext insIdCtx)
            throws SvcLogicException {
        PropertiesNodeSerializer propSer = new MdsalPropertiesNodeSerializer(
                insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
        SerializerHelper helper = new MdsalSerializerHelper(
                insIdCtx.getSchemaNode(), insIdCtx.getSchemaContext(), uri);
        Listener listener = instance().getListener(helper, params);
        DataFormatSerializerContext serCtx = new DataFormatSerializerContext(
                listener, uri, null, propSer);
        DataFormatSerializer ser = DfSerializerFactory.instance()
                .getSerializer(serCtx, params);
        return ser.decode(response);
    }

    /**
     * Returns instance identifier context for a uri using the schema context.
     *
     * @param params YANG parameters
     * @param uri    URI
     * @return instance identifier context
     * @throws SvcLogicException when getting schema context fails
     */
    private InstanceIdentifierContext<?> getInsIdCtx(YangParameters params,
                                                     String uri)
            throws SvcLogicException {
        EffectiveModelContext context = getSchemaContext(params);
        return ParserIdentifier.toInstanceIdentifier(uri, context, null);
    }

    /**
     * Returns the global schema context or schema context of particular YANG
     * files present in a directory path.
     *
     * @param params YANG parameters
     * @return schema context
     * @throws SvcLogicException when schema context fetching fails
     */
    private EffectiveModelContext getSchemaContext(YangParameters params) throws SvcLogicException {
        try {

            if (params.dirPath != null) {
                return getSchemaCtxFromDir(getParserFactory(), params.dirPath);
            } else {
                return (getParserFactory().createParser().buildEffectiveModel());
            }
        } catch (YangParserException e) {
            throw new SvcLogicException("Caught exception creating yang model context", e);
        }
    }

    /**
     * Returns the response message body of a http response message.
     *
     * @param ctx    svc logic context
     * @param params parameters
     * @param pre    prefix to be appended
     * @param res    http response
     * @return response message body
     */
    public String getResponse(SvcLogicContext ctx, YangParameters params,
                               String pre, HttpResponse res) {
        ctx.setAttribute(pre + RES_CODE, valueOf(res.code));
        ctx.setAttribute(pre + RES_MSG, res.message);

        if (params.dumpHeaders && res.headers != null) {
            for (Map.Entry<String, List<String>> a : res.headers.entrySet()) {
                ctx.setAttribute(pre + HEADER + a.getKey(),
                                 join(a.getValue(), COMMA));
            }
        }

        if (res.body != null && res.body.trim().length() > 0) {
            ctx.setAttribute(pre + HTTP_RES, res.body);
            return res.body;
        }
        return null;
    }

    /**
     * Sets the failure response status in the context memory.
     *
     * @param ctx    service logic context
     * @param prefix prefix to be added
     * @param errMsg error message
     */
    private void setFailureResponseStatus(SvcLogicContext ctx, String prefix,
                                          String errMsg) {
        HttpResponse res = new HttpResponse();
        res.code = 500;
        res.message = errMsg;
        ctx.setAttribute(prefix + RES_CODE, valueOf(res.code));
        ctx.setAttribute(prefix + RES_MSG, res.message);
    }

    /**
     * Updates request message for JSON and XML data format, when the HTTP
     * method points it as PUT or PATCH.
     *
     * @param req      current request message
     * @param p        YANG parameters
     * @param insIdCtx instance identifier context
     * @return update request message
     * @throws SvcLogicException when the data format type is wrong
     */
    public String updateReq(String req, YangParameters p,
                             InstanceIdentifierContext<?> insIdCtx)
            throws SvcLogicException {

        SchemaNode schemaNode = insIdCtx.getSchemaNode();
        Namespace modNs = getModuleNamespace(schemaNode.getQName(),
                                             insIdCtx.getSchemaContext());
        String nodeName = schemaNode.getQName().getLocalName();

        switch (p.format) {
            case JSON:
                return getUpdatedJsonReq(req, nodeName, modNs.moduleName());

            case XML:
                return getXmlReqForPutOp(req, nodeName, modNs.moduleNs());

            default:
                throw new SvcLogicException(format(FORMAT_ERR, p.format));
        }
    }

    /**
     * Returns the updated JSON request message, when the HTTP method
     * points to PUT or PATCH.
     *
     * @param req      current JSON request message
     * @param nodeName root node name
     * @param modName  module name of the root node
     * @return update JSON request message
     */
    private String getUpdatedJsonReq(String req, String nodeName,
                                     String modName) {
        Writer writer = new StringWriter();
        JsonWriter jsonWriter = new JsonWriter(writer);
        jsonWriter.setIndent(repeat(" ", 4));

        JsonParser jsonParser = new JsonParser();
        JsonObject oldJson = (JsonObject)jsonParser.parse(req);
        oldJson = remChildModName(oldJson, modName);
        JsonObject newJson = new JsonObject();
        newJson.add(modName + COLON + nodeName, oldJson.deepCopy());

        Gson gson= new Gson();
        gson.toJson(newJson, jsonWriter);
        return writer.toString();
    }

    /**
     * Removes module name from all the updated first level child node, if it
     * is same as the root node added.
     *
     * @param oldJson JSON object for old request
     * @param modName module name of root node
     * @return JSON object for old request with updated child module name
     */
    private JsonObject remChildModName(JsonObject oldJson, String modName) {
        Iterator<Map.Entry<String, JsonElement>> it = oldJson.entrySet().iterator();
        Map<String, JsonElement> m = new HashMap<>();
        while (it.hasNext()) {
            Map.Entry<String, JsonElement> jNode = it.next();
            if (jNode.getKey().contains(COLON)) {
                String[] modArr = jNode.getKey().split(COLON);
                if (modArr[0].equals(modName)) {
                    it.remove();
                    m.put(modArr[1], jNode.getValue());
                }
            }
        }
        if (!m.isEmpty()) {
            for (Map.Entry<String, JsonElement> element : m.entrySet()) {
                oldJson.add(element.getKey(), element.getValue());
            }
        }
        return oldJson;
    }

    /**
     * Returns the updated XML request message, when the HTTP method points
     * to PUT or PATCH.
     *
     * @param req      current JSON request message
     * @param nodeName root node name
     * @param modNs    module namespace of the root node
     * @return update JSON request message
     * @throws SvcLogicException when XML parsing fails
     */
    private String getXmlReqForPutOp(String req, String nodeName,
                                     URI modNs) throws SvcLogicException {
        req = getUpdatedXmlReq(req, nodeName, modNs.toString());
        Document oldDoc;
        try {
            oldDoc = DocumentHelper.parseText(req);
        } catch (DocumentException e) {
            throw new SvcLogicException(XML_TREE_ERR, e);
        }
        Writer writer = getXmlWriter(
                UTF_HEADER + oldDoc.getRootElement().asXML(), "4");
        return writer.toString();
    }
}