0acab5f3b572b5630c7bfcd0d328733c4468ea3a
[vfc/nfvo/wfengine.git] / activiti-extension / src / main / java / org / onap / workflow / activitiext / restservicetask / HttpUtil.java
1 /**\r
2  * Copyright 2017 ZTE Corporation.\r
3  *\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 package org.onap.workflow.activitiext.restservicetask;\r
17 \r
18 import java.util.LinkedList;\r
19 import java.util.List;\r
20 import java.util.Queue;\r
21 import java.util.regex.Matcher;\r
22 import java.util.regex.Pattern;\r
23 \r
24 import org.activiti.engine.ActivitiException;\r
25 import org.activiti.engine.delegate.BpmnError;\r
26 import org.activiti.engine.delegate.DelegateExecution;\r
27 import org.activiti.engine.delegate.Expression;\r
28 import org.activiti.engine.delegate.JavaDelegate;\r
29 import org.activiti.engine.impl.context.Context;\r
30 import org.apache.commons.lang3.StringUtils;\r
31 import org.onap.workflow.activitiext.common.ConstString;\r
32 import org.onap.workflow.activitiext.common.Parameter;\r
33 import org.onap.workflow.activitiext.common.RestInfo;\r
34 import org.onap.workflow.utils.MsbUtils;\r
35 import org.slf4j.Logger;\r
36 import org.slf4j.LoggerFactory;\r
37 \r
38 import com.alibaba.fastjson.JSONArray;\r
39 import com.google.gson.JsonArray;\r
40 import com.google.gson.JsonObject;\r
41 import com.google.gson.JsonParser;\r
42 import com.google.gson.JsonPrimitive;\r
43 \r
44 /**\r
45  * rest service\r
46  * \r
47  * @author 10222158\r
48  *\r
49  */\r
50 public class HttpUtil implements JavaDelegate {\r
51 \r
52         private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);\r
53 \r
54         private Expression name;\r
55         private Expression version;\r
56         private Expression url;\r
57         private Expression path;\r
58         private Expression method;\r
59         private Expression accept;\r
60         private Expression contentType;\r
61         private Expression parameters;\r
62 \r
63         @Override\r
64         public void execute(DelegateExecution execution) throws ActivitiException {\r
65 \r
66                 try {\r
67                         this.executeMethod(execution);\r
68                 } catch (Exception e) {\r
69                         logger.error("Invoke rest service failed!", e);\r
70                         throw new BpmnError(e.getMessage());\r
71                 }\r
72         }\r
73 \r
74         /**\r
75          * invoke rest service\r
76          * \r
77          * @param execution\r
78          */\r
79         public void executeMethod(DelegateExecution execution) throws Exception {\r
80 \r
81                 // get rest task information\r
82                 RestInfo restInfo = new RestInfo();\r
83                 restInfo.setName(getValue(name, execution));\r
84                 restInfo.setVersion(getValue(version, execution));\r
85                 restInfo.setUrl(getValue(url, execution));\r
86                 restInfo.setPath(getValue(path, execution));\r
87                 restInfo.setMethod(getValue(method, execution));\r
88                 restInfo.setAccept(getValue(accept, execution));\r
89                 restInfo.setContentType(getValue(contentType, execution));\r
90 \r
91                 String parametersValue = getValue(parameters, execution);\r
92 \r
93                 // real uri\r
94                 compeleteUri(restInfo);\r
95 \r
96                 if (!StringUtils.isEmpty(parametersValue)) {\r
97                         // Parse the parameter into Object List\r
98                         List<Parameter> parameters = JSONArray.parseArray(parametersValue, Parameter.class);\r
99 \r
100                         for (Parameter param : parameters) {\r
101 \r
102                                 restInfo = handleParam(execution, param, restInfo);\r
103                         }\r
104                 }\r
105 \r
106                 // invoke http service\r
107                 HttpResponseMessage msg = HighLevelRestApi.invoke(restInfo);\r
108 \r
109                 // inject the result to variable\r
110                 execution.setVariable(execution.getCurrentActivityId(), msg);\r
111         }\r
112 \r
113         /**\r
114          * \r
115          * @param execution\r
116          * @param param\r
117          * @param requestBody\r
118          * @param uriValue\r
119          */\r
120         public RestInfo handleParam(DelegateExecution execution, Parameter param, RestInfo restInfo)\r
121                         throws ActivitiException {\r
122 \r
123                 String realUri = restInfo.getRealUri();\r
124 \r
125                 if (ConstString.PARAMETER_VALUE_SOURCE_PLAN.equals(param.getValueSource())) {\r
126 \r
127                         String planValue = parsePlanExpression(param.getValue(), execution);\r
128                         param.setValue(planValue);\r
129                 } else if (ConstString.PARAMETER_VALUE_SOURCE_TOPOLOGY.equals(param.getValueSource())) {\r
130 \r
131                         String topValue = parseTopologyExpression(param.getValue(), execution);\r
132                         param.setValue(topValue);\r
133                 }else if(ConstString.PARAMETER_VALUE_SOURCE_VARIABLE.equals(param.getValueSource())) {\r
134 \r
135                         String varValue = parseVariableExpression(param.getValue(), execution);\r
136                         param.setValue(varValue);\r
137                 }\r
138 \r
139                 switch (param.getPosition()) {\r
140                 case ConstString.PARAMETER_POSITION_PATH:\r
141 \r
142                         // replace the path parameter\r
143                         realUri = realUri.replaceAll("\\{+" + param.getName() + "+\\}", param.getValue());\r
144                         restInfo.setRealUri(realUri);\r
145                         break;\r
146                 case ConstString.PARAMETER_POSITION_QUERY:\r
147 \r
148                         // add the query parameter\r
149                         if (!realUri.contains("?")) {\r
150                                 realUri = realUri + "?" + param.getName() + "=" + param.getValue();\r
151                         } else {\r
152                                 realUri = realUri + "&" + param.getName() + "=" + param.getValue();\r
153                         }\r
154                         restInfo.setRealUri(realUri);\r
155                         break;\r
156                 case ConstString.PARAMETER_POSITION_BODY:\r
157 \r
158                         // add parameter to request body\r
159                         String value = param.getValue();\r
160 \r
161                         JsonObject obj = new JsonParser().parse(value).getAsJsonObject();\r
162 \r
163                         JsonObject res = GsonUtil.formatJsonObject(null, obj, execution);\r
164 \r
165                         restInfo.setRequestBody(res.toString());\r
166                         break;\r
167                 default:\r
168                         logger.info("The position {} is illegal, please check your input!",param.getPosition());\r
169                 }\r
170 \r
171                 return restInfo;\r
172         }\r
173 \r
174         /**\r
175          * get value from VariableScope\r
176          * \r
177          * @param expression\r
178          * @param execution\r
179          * @return\r
180          */\r
181         public String getValue(Expression expression, DelegateExecution execution) {\r
182 \r
183                 String result = new String();\r
184                 if (expression != null) {\r
185                         result = (String) expression.getValue(execution);\r
186                 }\r
187 \r
188                 return result;\r
189         }\r
190 \r
191         /**\r
192          * parse plan expression\r
193          * \r
194          * @param execution\r
195          * @param expStr\r
196          * @return\r
197          */\r
198         public static String parsePlanExpression(String expStr, DelegateExecution execution) {\r
199 \r
200                 String result = "";\r
201                 String key = "";\r
202                 try {\r
203 \r
204                         Queue<String> planQueue = parseExpressionToQueue(expStr);\r
205                         Object planObj = execution.getVariable(planQueue.poll());\r
206                         \r
207                         if (planQueue.isEmpty()) {\r
208                                 result = String.valueOf(planObj);\r
209                         } else if(planObj instanceof HttpResponseMessage) {\r
210                                 \r
211                                 JsonObject jsonObj = new JsonParser().parse(planObj.toString()).getAsJsonObject();\r
212                                 while (!planQueue.isEmpty()) {\r
213                                         \r
214                                         key = planQueue.poll();\r
215                                         Object obj = jsonObj.get(key);\r
216                                         if (obj instanceof JsonArray) {\r
217                                                 \r
218                                                 break;\r
219                                         }else if(obj instanceof JsonObject){\r
220                                                 \r
221                                                 jsonObj = (JsonObject) obj;\r
222                                         }else if(obj instanceof JsonPrimitive){\r
223                                                 \r
224                                                 JsonPrimitive jsonPri = (JsonPrimitive)obj;\r
225                                                 result = jsonPri.getAsString();\r
226                                         }\r
227                                 }\r
228                         }\r
229                 } catch (Exception e) {\r
230                         logger.error("expression {} is illegal, parse key {} failed!", expStr, key, e);\r
231                         throw e;\r
232                 }\r
233 \r
234                 return result;\r
235         }\r
236 \r
237         /**\r
238          * parse topology expression\r
239          * \r
240          * @param expStr\r
241          * @param csarId\r
242          * @return\r
243          */\r
244         public static String parseTopologyExpression(String expStr, DelegateExecution execution) {\r
245 \r
246                 String csarId = getCsarId(execution);\r
247                 Queue<String> topQueue = parseExpressionToQueue(expStr);\r
248 \r
249                 // parse topology expression\r
250                 if (topQueue.size() != 2) {\r
251                         logger.error("topology data {} is illegal!", expStr);\r
252                         return new String();\r
253                 }\r
254 \r
255                 // obtain topology json data\r
256                 String topJsonStr = CatalogServiceConsumer.getTopologyJson(csarId, topQueue.poll());\r
257                 JsonObject topJsonObj = new JsonParser().parse(topJsonStr).getAsJsonObject();\r
258 \r
259                 // obtain topology value\r
260                 String topValue = topJsonObj.get(topQueue.poll()).getAsString();\r
261 \r
262                 logger.info("topology expression {} : {}", expStr, topValue);\r
263 \r
264                 return topValue;\r
265         }\r
266         \r
267         /**\r
268          * parse variable expression\r
269          * \r
270          * @param execution\r
271          * @param expStr\r
272          * @return\r
273          */\r
274         public static String parseVariableExpression(String expStr, DelegateExecution execution) {\r
275 \r
276                 String result = "";\r
277                 \r
278                 try {\r
279                         Expression expression = Context.getProcessEngineConfiguration().getExpressionManager()\r
280                                         .createExpression(expStr);\r
281                         \r
282                         result = String.valueOf(expression.getValue(execution));\r
283                 } catch (Exception e) {\r
284                         logger.error("variable expression illegal!",e);\r
285                 }\r
286 \r
287                 return result;\r
288         }\r
289         \r
290         /**\r
291          * obtain csar id\r
292          * \r
293          * @param execution\r
294          */\r
295         private static String getCsarId(DelegateExecution execution) {\r
296 \r
297                 String csarId = "";\r
298                 csarId = String.valueOf(execution.getVariable(ConstString.CSARID_EXPRESSION));\r
299 \r
300                 return csarId;\r
301         }\r
302 \r
303         /**\r
304          * compelete uri\r
305          * \r
306          * @param restInfo\r
307          * @return\r
308          */\r
309         private static String compeleteUri(RestInfo restInfo) {\r
310 \r
311                 String publishUrl = "";\r
312                 try {\r
313                         publishUrl = new MsbUtils().getServiceAddress(restInfo.getName(), restInfo.getVersion());\r
314                 } catch (Exception e) {\r
315                         logger.error("get service publish address error!", e);\r
316                 }\r
317                 String realUri = null;\r
318                 if (StringUtils.isNotEmpty(publishUrl)) {\r
319                         realUri = publishUrl + restInfo.getPath();\r
320                 } else {\r
321                         realUri = PropertyUtil.getBasePath() + restInfo.getUrl() + restInfo.getPath();\r
322                 }\r
323 \r
324                 logger.info("realUri is " + realUri);\r
325                 restInfo.setRealUri(realUri);\r
326 \r
327                 return realUri;\r
328         }\r
329 \r
330         /**\r
331          * prase expression as a queue\r
332          * \r
333          * @param expStr\r
334          * @return\r
335          */\r
336         private static Queue<String> parseExpressionToQueue(String expStr) {\r
337 \r
338                 Queue<String> queue = new LinkedList<String>();\r
339 \r
340                 if (StringUtils.isNotEmpty(expStr) && expStr.startsWith("[")) {\r
341 \r
342                         Pattern p = Pattern.compile("[\\[]+[^]]+[\\]]");\r
343                         Matcher m = p.matcher(expStr);\r
344                         String key = "";\r
345                         while (m.find()) {\r
346                                 key = m.group();\r
347                                 key = key.substring(1, key.length() - 1);\r
348                                 queue.offer(key);\r
349                         }\r
350                 }\r
351 \r
352                 return queue;\r
353         }\r
354 \r
355 }\r