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