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