Improve coverage in flow/controller/node
[appc.git] / appc-config / appc-flow-controller / provider / src / main / java / org / onap / appc / flow / controller / node / RestServiceNode.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. 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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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  *
19  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.appc.flow.controller.node;
24
25 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.APPC_FLOW_CONTROLLER;
26 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.INPUT_PARAM_RESPONSE_PREFIX;
27 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.INPUT_REQUEST_ACTION;
28 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE;
29 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.OUTPUT_PARAM_ERROR_MESSAGE;
30 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.OUTPUT_PARAM_STATUS;
31 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.OUTPUT_STATUS_FAILURE;
32 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.OUTPUT_STATUS_MESSAGE;
33 import static org.onap.appc.flow.controller.utils.FlowControllerConstants.OUTPUT_STATUS_SUCCESS;
34
35 import com.att.eelf.configuration.EELFLogger;
36 import com.att.eelf.configuration.EELFManager;
37 import com.fasterxml.jackson.core.JsonProcessingException;
38 import com.fasterxml.jackson.databind.JsonNode;
39 import com.fasterxml.jackson.databind.ObjectMapper;
40 import java.io.IOException;
41 import java.util.Map;
42 import java.util.Properties;
43 import org.apache.commons.lang3.StringUtils;
44 import org.onap.appc.flow.controller.data.Transaction;
45 import org.onap.appc.flow.controller.executorImpl.RestExecutor;
46 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
47 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
48 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
49
50 public class RestServiceNode implements SvcLogicJavaPlugin {
51
52   private static final EELFLogger log = EELFManager.getInstance().getLogger(RestServiceNode.class);
53   private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR";
54
55   public void sendRequest(Map<String, String> inParams, SvcLogicContext ctx)
56       throws SvcLogicException {
57     String fn = "RestServiceNode.sendRequest";
58     log.info("Received processParamKeys call with params : " + inParams);
59     String responsePrefix = inParams.get(INPUT_PARAM_RESPONSE_PREFIX);
60     try {
61       responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix + ".") : "";
62       //Remove below for Block
63       for (Object key : ctx.getAttributeKeySet()) {
64         String parmName = (String) key;
65         String parmValue = ctx.getAttribute(parmName);
66         log.info(fn + "Getting Key = " + parmName + "and Value = " + parmValue);
67       }
68
69       send(ctx, inParams);
70       ctx.setAttribute(responsePrefix + OUTPUT_PARAM_STATUS, OUTPUT_STATUS_SUCCESS);
71
72     } catch (Exception e) {
73       ctx.setAttribute(responsePrefix + OUTPUT_PARAM_STATUS, OUTPUT_STATUS_FAILURE);
74       ctx.setAttribute(responsePrefix + OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage());
75       log.error("Error Message : " + e.getMessage(), e);
76       throw new SvcLogicException(e.getMessage());
77     }
78   }
79
80   private void send(SvcLogicContext ctx, Map<String, String> inParams) throws Exception {
81     try {
82       Properties prop = loadProperties();
83       log.info("Loaded Properties " + prop.toString());
84       String responsePrefix = inParams.get(INPUT_PARAM_RESPONSE_PREFIX);
85       String resourceUri = ResourceUriExtractor.extractResourceUri(ctx, prop);
86       log.info("Rest Constructed URL : " + resourceUri);
87
88       Transaction transaction = new Transaction();
89       transaction.setExecutionEndPoint(resourceUri);
90       transaction
91           .setExecutionRPC(ctx.getAttribute(INPUT_REQUEST_ACTION_TYPE));
92       transaction.setAction(INPUT_REQUEST_ACTION);
93       if (ctx.getAttribute(INPUT_REQUEST_ACTION_TYPE) == null
94           || ctx.getAttribute(INPUT_REQUEST_ACTION_TYPE).isEmpty()) {
95         throw new Exception("Dont know REST operation for Action " + transaction.getExecutionRPC());
96       }
97       if (ctx.getAttribute(INPUT_REQUEST_ACTION) == null
98           || ctx.getAttribute(INPUT_REQUEST_ACTION).isEmpty()) {
99         throw new Exception("Dont know request-action " + transaction.getAction());
100       }
101
102       //This code need to get changed to get the UserID and pass from a common place.
103       if (transaction.getuId() == null) {
104         transaction
105             .setuId(prop.getProperty(ctx.getAttribute(INPUT_REQUEST_ACTION)
106                 .concat(".default-rest-user")));
107       }
108       if (transaction.getPswd() == null) {
109         transaction
110             .setPswd(prop.getProperty(ctx.getAttribute(INPUT_REQUEST_ACTION)
111                 .concat(".default-rest-pass")));
112       }
113
114       RestExecutor restRequestExecutor = new RestExecutor();
115       Map<String, String> output = restRequestExecutor.execute(transaction, ctx);
116
117       if (isValidJson(output.get("restResponse")) != null) {
118         ctx.setAttribute(responsePrefix + "." + OUTPUT_STATUS_MESSAGE,
119             output.get("restResponse"));
120 //                JsonNode restResponse = isValidJson(output.get("restResponse"));
121 //                for (String key : inParams.keySet()) {
122 //                    if(key !=null &&  key.startsWith("output-")){
123 //                            log.info("Found Key = " + key);
124 //                            log.info("Found Key in Params " + inParams.get(key) + ".");
125 //                            JsonNode setValue =  restResponse.findValue(inParams.get(key));                            
126 //                             log.info("Found value = " + setValue);
127 //                             if(setValue !=null && setValue.textValue() !=null && !setValue.textValue().isEmpty())
128 //                                 ctx.setAttribute(responsePrefix + "." + key, setValue.textValue());
129 //                             else
130 //                                 ctx.setAttribute(responsePrefix + "." + key, null);
131 //                    }
132 //                }                
133       }
134       log.info("Response from Rest :");
135
136     } catch (Exception e) {
137       log.error("Error Message: " + e.getMessage(), e);
138       throw e;
139     }
140   }
141
142   private Properties loadProperties() throws Exception {
143     String directory = System.getenv(SDNC_CONFIG_DIR_VAR);
144     if (directory == null) {
145       throw new Exception("Cannot find Property file: " + SDNC_CONFIG_DIR_VAR);
146     }
147     String path = directory + APPC_FLOW_CONTROLLER;
148     return PropertiesLoader.load(path);
149   }
150
151   private JsonNode isValidJson(String json) throws IOException {
152     JsonNode output;
153     log.info("Received response from Interface " + json);
154     if (json == null || json.isEmpty()) {
155       return null;
156     }
157     try {
158       ObjectMapper objectMapper = new ObjectMapper();
159       output = objectMapper.readTree(json);
160     } catch (JsonProcessingException e) {
161       log.warn("Response received from interface is not a valid JSON block" + json, e);
162       return null;
163     }
164     log.info("state is " + output.findValue("state"));
165     return output;
166   }
167 }