CheckStyle corrections only
[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 com.att.eelf.configuration.EELFLogger;
26 import com.att.eelf.configuration.EELFManager;
27 import com.fasterxml.jackson.core.JsonProcessingException;
28 import com.fasterxml.jackson.databind.JsonNode;
29 import com.fasterxml.jackson.databind.ObjectMapper;
30 import java.io.FileInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.util.Map;
34 import java.util.Properties;
35 import org.apache.commons.lang3.StringUtils;
36 import org.onap.appc.flow.controller.data.Transaction;
37 import org.onap.appc.flow.controller.executorImpl.RestExecutor;
38 import org.onap.appc.flow.controller.utils.FlowControllerConstants;
39 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
40 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
41 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
42
43 public class RestServiceNode implements SvcLogicJavaPlugin {
44
45     private static final  EELFLogger log = EELFManager.getInstance().getLogger(RestServiceNode.class);
46     private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR";
47
48     public void sendRequest(Map<String, String> inParams, SvcLogicContext ctx) throws SvcLogicException {
49         String fn = "RestServiceNode.sendRequest";
50         log.info("Received processParamKeys call with params : " + inParams);
51         String responsePrefix = inParams.get(FlowControllerConstants.INPUT_PARAM_RESPONSE_PRIFIX);
52         try {
53             responsePrefix = StringUtils.isNotBlank(responsePrefix) ? (responsePrefix + ".") : "";
54             //Remove below for Block
55             for (Object key : ctx.getAttributeKeySet()) {
56                 String parmName = (String) key;
57                 String parmValue = ctx.getAttribute(parmName);
58                 log.info(fn  + "Getting Key = "  + parmName + "and Value = " +  parmValue);
59             }
60             
61             send(ctx, inParams);
62             ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS,
63                 FlowControllerConstants.OUTPUT_STATUS_SUCCESS);
64             
65         } catch (Exception e) {
66             ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_STATUS,
67                 FlowControllerConstants.OUTPUT_STATUS_FAILURE);
68             ctx.setAttribute(responsePrefix + FlowControllerConstants.OUTPUT_PARAM_ERROR_MESSAGE,
69                 e.getMessage());
70             log.error("Error Message : "  + e.getMessage(), e);
71             throw new SvcLogicException(e.getMessage());
72         }
73     }
74
75     private void send(SvcLogicContext ctx, Map<String, String> inParams) throws Exception {
76         try {
77             Properties prop = loadProperties();
78             log.info("Loaded Properties " + prop.toString());
79             String responsePrefix = inParams.get(FlowControllerConstants.INPUT_PARAM_RESPONSE_PRIFIX);
80             String resourceUri = "";
81             if (ctx.getAttribute(FlowControllerConstants.INPUT_URL) != null
82                 && !(ctx.getAttribute(FlowControllerConstants.INPUT_URL).isEmpty())) {
83                 resourceUri = ctx.getAttribute(FlowControllerConstants.INPUT_URL);
84
85             } else {
86                 resourceUri = resourceUri.concat(FlowControllerConstants.HTTP);
87                 log.info("resourceUri=  " + resourceUri );
88                 resourceUri = resourceUri.concat(ctx.getAttribute(FlowControllerConstants.INPUT_HOST_IP_ADDRESS));
89                 resourceUri = resourceUri.concat(":");
90                 resourceUri = resourceUri.concat(ctx.getAttribute(FlowControllerConstants.INPUT_PORT_NUMBER));
91
92                 if (ctx.getAttribute(FlowControllerConstants.INPUT_CONTEXT) != null
93                     && !ctx.getAttribute(FlowControllerConstants.INPUT_CONTEXT).isEmpty()) {
94                     resourceUri = resourceUri
95                         .concat("/")
96                         .concat(ctx.getAttribute(FlowControllerConstants.INPUT_CONTEXT));
97                     log.info("resourceUri= " + resourceUri );
98
99                 } else if (prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION)
100                     .concat(".context")) != null ) {
101                     log.info("resourceUri = " + resourceUri );
102                     resourceUri = resourceUri
103                         .concat("/")
104                         .concat(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION)
105                             .concat(".context")));
106
107                 } else {
108                     throw new Exception("Could Not found the context for operation "
109                         + ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION));
110                 }
111
112                 if (ctx.getAttribute(FlowControllerConstants.INPUT_SUB_CONTEXT) != null
113                     && !ctx.getAttribute(FlowControllerConstants.INPUT_SUB_CONTEXT).isEmpty()) {
114                     resourceUri = resourceUri
115                         .concat("/")
116                         .concat(ctx.getAttribute(FlowControllerConstants.INPUT_SUB_CONTEXT));
117                     log.info("resourceUri" + resourceUri );
118
119                 } else if (prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION)
120                     .concat(".sub-context")) != null ) {
121                     resourceUri = resourceUri
122                         .concat("/")
123                         .concat(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION)
124                             .concat(".sub-context")));
125                     log.info("resourceUri" + resourceUri );
126                 }
127             }
128             log.info("Rest Constructed URL : " + resourceUri);
129
130             Transaction transaction = new Transaction();
131             transaction.setExecutionEndPoint(resourceUri);
132             transaction.setExecutionRPC(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE));
133             transaction.setAction(FlowControllerConstants.INPUT_REQUEST_ACTION);
134             if (ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE) == null
135                 || ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE).isEmpty()) {
136                 throw new Exception("Dont know REST operation for Action " + transaction.getExecutionRPC());
137             }
138             if (ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION) == null
139                 || ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).isEmpty()) {
140                 throw new Exception("Dont know request-action " + transaction.getAction());
141             }
142
143             //This code need to get changed to get the UserID and pass from a common place.
144             if (transaction.getuId() == null) {
145                 transaction.setuId(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION)
146                     .concat(".default-rest-user")));
147             }
148             if (transaction.getPswd() == null) {
149                 transaction.setPswd(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION)
150                     .concat(".default-rest-pass")));
151             }
152
153             RestExecutor restRequestExecutor = new RestExecutor();
154             Map<String, String> output = restRequestExecutor.execute(transaction, ctx);
155
156             if (isValidJson(output.get("restResponse")) != null) {
157                 ctx.setAttribute(responsePrefix + "." + FlowControllerConstants.OUTPUT_STATUS_MESSAGE,
158                     output.get("restResponse"));
159 //                JsonNode restResponse = isValidJson(output.get("restResponse"));
160 //                for (String key : inParams.keySet()) {
161 //                    if(key !=null &&  key.startsWith("output-")){
162 //                            log.info("Found Key = " + key);
163 //                            log.info("Found Key in Params " + inParams.get(key) + ".");
164 //                            JsonNode setValue =  restResponse.findValue(inParams.get(key));                            
165 //                             log.info("Found value = " + setValue);
166 //                             if(setValue !=null && setValue.textValue() !=null && !setValue.textValue().isEmpty())
167 //                                 ctx.setAttribute(responsePrefix + "." + key, setValue.textValue());
168 //                             else
169 //                                 ctx.setAttribute(responsePrefix + "." + key, null);
170 //                    }
171 //                }                
172             }
173             log.info("Response from Rest :" );
174
175         } catch(Exception e) {
176             log.error("Error Message: " + e.getMessage(), e);
177             throw e;
178         }
179     }
180
181     private Properties loadProperties() throws Exception {
182         Properties props = new Properties();
183         String propDir = System.getenv(SDNC_CONFIG_DIR_VAR);
184         if (propDir == null) {
185             throw new Exception("Cannot find Property file -" + SDNC_CONFIG_DIR_VAR);
186         }
187         String propFile = propDir + FlowControllerConstants.APPC_FLOW_CONTROLLER;
188         try (InputStream propStream = new FileInputStream(propFile)) {
189
190             props.load(propStream);
191         }
192         catch (Exception e) {
193             throw new Exception("Could not load properties file " + propFile, e);
194         }
195         return props;
196     }
197
198     private JsonNode isValidJson(String json) throws IOException {
199         JsonNode output;
200         log.info("Received response from Interface " + json);
201         if (json == null  || json.isEmpty()) {
202             return null;
203         }
204         try {
205             ObjectMapper objectMapper = new ObjectMapper();
206             output = objectMapper.readTree(json);
207         } catch(JsonProcessingException e) {
208             log.warn("Response received from interface is not a valid JSON block" + json, e);
209             return null;
210         }
211         log.info("state is " + output.findValue("state"));
212         return output;
213     }
214 }