Update java files with correct license text
[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 java.io.FileInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.util.HashMap;
29 import java.util.Map;
30 import java.util.Properties;
31
32 import org.apache.commons.lang3.StringUtils;
33 import org.onap.appc.flow.controller.data.Transaction;
34 import org.onap.appc.flow.controller.executorImpl.RestExecutor;
35 import org.onap.appc.flow.controller.utils.FlowControllerConstants;
36 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
37 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
38 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
39
40 import com.att.eelf.configuration.EELFLogger;
41 import com.att.eelf.configuration.EELFManager;
42 import com.fasterxml.jackson.core.JsonProcessingException;
43 import com.fasterxml.jackson.databind.JsonNode;
44 import com.fasterxml.jackson.databind.ObjectMapper;
45
46 public class RestServiceNode implements SvcLogicJavaPlugin{
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             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             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             RestExecutor restRequestExecutor = new RestExecutor();
81             String resourceUri = "";
82             if(ctx.getAttribute(FlowControllerConstants.INPUT_URL) != null && !(ctx.getAttribute(FlowControllerConstants.INPUT_URL).isEmpty()))
83                 resourceUri = ctx.getAttribute(FlowControllerConstants.INPUT_URL);
84             else {
85                 resourceUri = resourceUri.concat(FlowControllerConstants.HTTP);
86                 log.info("resourceUri=  " + resourceUri );
87                 resourceUri = resourceUri.concat(ctx.getAttribute(FlowControllerConstants.INPUT_HOST_IP_ADDRESS));
88                 resourceUri = resourceUri.concat(":");
89                 resourceUri = resourceUri.concat(ctx.getAttribute(FlowControllerConstants.INPUT_PORT_NUMBER));
90
91                 if(ctx.getAttribute(FlowControllerConstants.INPUT_CONTEXT) != null && !ctx.getAttribute(FlowControllerConstants.INPUT_CONTEXT).isEmpty()){
92                     resourceUri = resourceUri.concat("/").concat(ctx.getAttribute(FlowControllerConstants.INPUT_CONTEXT));
93                     log.info("resourceUri= " + resourceUri );
94                 }
95                 else if(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".context")) != null ){
96                     log.info("resourceUri = " + resourceUri );
97                     resourceUri = resourceUri.concat("/").concat(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".context")));
98                 } else {
99                     throw new Exception("Could Not found the context for operation " + ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION));
100                 }
101
102                 if(ctx.getAttribute(FlowControllerConstants.INPUT_SUB_CONTEXT) != null && !ctx.getAttribute(FlowControllerConstants.INPUT_SUB_CONTEXT).isEmpty()){
103                     resourceUri = resourceUri.concat("/").concat(ctx.getAttribute(FlowControllerConstants.INPUT_SUB_CONTEXT));
104                     log.info("resourceUri" + resourceUri );
105                 }
106                 else if(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".sub-context")) != null ){
107                     resourceUri = resourceUri.concat("/").concat(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".sub-context")));
108                     log.info("resourceUri" + resourceUri );
109                 }
110             }
111
112             log.info("Rest Constructed URL : " + resourceUri);
113             Transaction transaction = new Transaction();
114
115             transaction.setExecutionEndPoint(resourceUri);
116             transaction.setExecutionRPC(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE));
117             transaction.setAction(FlowControllerConstants.INPUT_REQUEST_ACTION);
118             if(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE) == null || ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION_TYPE).isEmpty())
119                 throw new Exception("Dont know REST operation for Action " + transaction.getExecutionRPC());
120             if(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION) == null || ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).isEmpty())
121                 throw new Exception("Dont know request-action " + transaction.getAction());
122
123             //This code need to get changed to get the UserID and pass from a common place.
124             if(transaction.getuId() == null)
125                 transaction.setuId(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".default-rest-user")));
126             if(transaction.getPswd() == null)
127                 transaction.setPswd(prop.getProperty(ctx.getAttribute(FlowControllerConstants.INPUT_REQUEST_ACTION).concat(".default-rest-pass")));    
128
129             HashMap<String, String> output = restRequestExecutor.execute(transaction, ctx);
130
131             if(isValidJSON(output.get("restResponse")) != null) {
132                 ctx.setAttribute(responsePrefix + "." + FlowControllerConstants.OUTPUT_STATUS_MESSAGE , output.get("restResponse"));
133 //                JsonNode restResponse = isValidJSON(output.get("restResponse"));
134 //                for (String key : inParams.keySet()) {
135 //                    if(key !=null &&  key.startsWith("output-")){
136 //                            log.info("Found Key = " + key);
137 //                            log.info("Found Key in Params " + inParams.get(key) + ".");
138 //                            JsonNode setValue =  restResponse.findValue(inParams.get(key));                            
139 //                             log.info("Found value = " + setValue);
140 //                             if(setValue !=null && setValue.textValue() !=null && !setValue.textValue().isEmpty())
141 //                                 ctx.setAttribute(responsePrefix + "." + key, setValue.textValue());
142 //                             else
143 //                                 ctx.setAttribute(responsePrefix + "." + key, null);
144 //                    }
145 //                }                
146             }
147             log.info("Response from Rest :" );
148
149         } catch(Exception e) {
150             log.error("Error Message: " + e.getMessage(), e);
151             throw e;
152         }
153     }
154
155     private Properties loadProperties() throws Exception {
156         Properties props = new Properties();
157         String propDir = System.getenv(SDNC_CONFIG_DIR_VAR);
158         if (propDir == null)
159             throw new Exception("Cannot find Property file -" + SDNC_CONFIG_DIR_VAR);
160         String propFile = propDir + FlowControllerConstants.APPC_FLOW_CONTROLLER;
161         try (InputStream propStream = new FileInputStream(propFile))
162         {
163             props.load(propStream);
164         }
165         catch (Exception e)
166         {
167             throw new Exception("Could not load properties file " + propFile, e);
168         }
169         return props;
170     }
171
172     private JsonNode isValidJSON(String json) throws IOException {
173         JsonNode output;
174         log.info("Received response from Interface " + json);
175         if(json == null  || json.isEmpty())
176             return null;
177         try {
178             ObjectMapper objectMapper = new ObjectMapper();
179             output = objectMapper.readTree(json);
180         } catch(JsonProcessingException e) {
181             log.warn("Response received from interface is not a valid JSON block" + json, e);
182             return null;
183         }
184         log.info("state is " + output.findValue("state"));
185         return output;
186     }
187 }