Add unit test for vfc-nfvo-wfengine
[vfc/nfvo/wfengine.git] / activiti-extension / src / main / java / org / onap / workflow / activitiext / restservicetask / HttpUtil.java
index 75a6b2f..0acab5f 100644 (file)
@@ -1,5 +1,5 @@
 /**\r
- * Copyright 2016-2017 ZTE Corporation.\r
+ * Copyright 2017 ZTE Corporation.\r
  *\r
  * Licensed under the Apache License, Version 2.0 (the "License");\r
  * you may not use this file except in compliance with the License.\r
  */\r
 package org.onap.workflow.activitiext.restservicetask;\r
 \r
-import java.util.HashMap;\r
+import java.util.LinkedList;\r
 import java.util.List;\r
-import java.util.Map;\r
+import java.util.Queue;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
 \r
 import org.activiti.engine.ActivitiException;\r
 import org.activiti.engine.delegate.BpmnError;\r
@@ -26,11 +28,18 @@ import org.activiti.engine.delegate.Expression;
 import org.activiti.engine.delegate.JavaDelegate;\r
 import org.activiti.engine.impl.context.Context;\r
 import org.apache.commons.lang3.StringUtils;\r
+import org.onap.workflow.activitiext.common.ConstString;\r
+import org.onap.workflow.activitiext.common.Parameter;\r
+import org.onap.workflow.activitiext.common.RestInfo;\r
+import org.onap.workflow.utils.MsbUtils;\r
 import org.slf4j.Logger;\r
 import org.slf4j.LoggerFactory;\r
 \r
-import com.alibaba.fastjson.JSON;\r
 import com.alibaba.fastjson.JSONArray;\r
+import com.google.gson.JsonArray;\r
+import com.google.gson.JsonObject;\r
+import com.google.gson.JsonParser;\r
+import com.google.gson.JsonPrimitive;\r
 \r
 /**\r
  * rest service\r
@@ -42,7 +51,10 @@ public class HttpUtil implements JavaDelegate {
 \r
        private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);\r
 \r
-       private Expression uri;\r
+       private Expression name;\r
+       private Expression version;\r
+       private Expression url;\r
+       private Expression path;\r
        private Expression method;\r
        private Expression accept;\r
        private Expression contentType;\r
@@ -54,7 +66,6 @@ public class HttpUtil implements JavaDelegate {
                try {\r
                        this.executeMethod(execution);\r
                } catch (Exception e) {\r
-\r
                        logger.error("Invoke rest service failed!", e);\r
                        throw new BpmnError(e.getMessage());\r
                }\r
@@ -65,40 +76,38 @@ public class HttpUtil implements JavaDelegate {
         * \r
         * @param execution\r
         */\r
-       public boolean executeMethod(DelegateExecution execution) throws Exception {\r
+       public void executeMethod(DelegateExecution execution) throws Exception {\r
+\r
+               // get rest task information\r
+               RestInfo restInfo = new RestInfo();\r
+               restInfo.setName(getValue(name, execution));\r
+               restInfo.setVersion(getValue(version, execution));\r
+               restInfo.setUrl(getValue(url, execution));\r
+               restInfo.setPath(getValue(path, execution));\r
+               restInfo.setMethod(getValue(method, execution));\r
+               restInfo.setAccept(getValue(accept, execution));\r
+               restInfo.setContentType(getValue(contentType, execution));\r
 \r
-               String uriValue = getValue(uri, execution);\r
-               String methodValue = getValue(method, execution);\r
-               String acceptValue = getValue(accept, execution);\r
-               String contentTypeValue = getValue(contentType, execution);\r
                String parametersValue = getValue(parameters, execution);\r
 \r
-               Map<String, String> requestBody = new HashMap<String, String>();\r
+               // real uri\r
+               compeleteUri(restInfo);\r
 \r
                if (!StringUtils.isEmpty(parametersValue)) {\r
-\r
                        // Parse the parameter into Object List\r
                        List<Parameter> parameters = JSONArray.parseArray(parametersValue, Parameter.class);\r
 \r
                        for (Parameter param : parameters) {\r
 \r
-                               handleParam(execution, param, requestBody, uriValue);\r
+                               restInfo = handleParam(execution, param, restInfo);\r
                        }\r
                }\r
 \r
-               String requestPayload = JSON.toJSONString(requestBody);\r
-\r
                // invoke http service\r
-               HttpResponseMessage msg = HighLevelRestApi.invoke(methodValue, uriValue, requestPayload, acceptValue,\r
-                               contentTypeValue);\r
+               HttpResponseMessage msg = HighLevelRestApi.invoke(restInfo);\r
 \r
                // inject the result to variable\r
                execution.setVariable(execution.getCurrentActivityId(), msg);\r
-\r
-               logger.info("statusCode: " + msg.getStatusCode());\r
-               logger.info("responseBody: " + msg.getResponseBody());\r
-               \r
-               return true;\r
        }\r
 \r
        /**\r
@@ -108,37 +117,58 @@ public class HttpUtil implements JavaDelegate {
         * @param requestBody\r
         * @param uriValue\r
         */\r
-       public void handleParam(DelegateExecution execution, Parameter param, Map<String, String> requestBody,\r
-                       String uriValue) throws ActivitiException {\r
+       public RestInfo handleParam(DelegateExecution execution, Parameter param, RestInfo restInfo)\r
+                       throws ActivitiException {\r
 \r
-               if (ConstString.PARAMETER_TYPE_EXPRESSION.equals(param.getType())) {\r
-                       handleExpression(execution, param);\r
+               String realUri = restInfo.getRealUri();\r
+\r
+               if (ConstString.PARAMETER_VALUE_SOURCE_PLAN.equals(param.getValueSource())) {\r
+\r
+                       String planValue = parsePlanExpression(param.getValue(), execution);\r
+                       param.setValue(planValue);\r
+               } else if (ConstString.PARAMETER_VALUE_SOURCE_TOPOLOGY.equals(param.getValueSource())) {\r
+\r
+                       String topValue = parseTopologyExpression(param.getValue(), execution);\r
+                       param.setValue(topValue);\r
+               }else if(ConstString.PARAMETER_VALUE_SOURCE_VARIABLE.equals(param.getValueSource())) {\r
+\r
+                       String varValue = parseVariableExpression(param.getValue(), execution);\r
+                       param.setValue(varValue);\r
                }\r
 \r
                switch (param.getPosition()) {\r
                case ConstString.PARAMETER_POSITION_PATH:\r
 \r
                        // replace the path parameter\r
-                       uriValue = uriValue.replaceAll("\\{+" + param.getName() + "+\\}", param.getValue());\r
+                       realUri = realUri.replaceAll("\\{+" + param.getName() + "+\\}", param.getValue());\r
+                       restInfo.setRealUri(realUri);\r
                        break;\r
                case ConstString.PARAMETER_POSITION_QUERY:\r
 \r
                        // add the query parameter\r
-                       if (!uriValue.contains("?")) {\r
-                               uriValue = uriValue + "?" + param.getName() + "=" + param.getValue();\r
+                       if (!realUri.contains("?")) {\r
+                               realUri = realUri + "?" + param.getName() + "=" + param.getValue();\r
                        } else {\r
-                               uriValue = uriValue + "&" + param.getName() + "=" + param.getValue();\r
+                               realUri = realUri + "&" + param.getName() + "=" + param.getValue();\r
                        }\r
+                       restInfo.setRealUri(realUri);\r
                        break;\r
                case ConstString.PARAMETER_POSITION_BODY:\r
 \r
                        // add parameter to request body\r
-                       requestBody.put(param.getName(), param.getValue());\r
+                       String value = param.getValue();\r
+\r
+                       JsonObject obj = new JsonParser().parse(value).getAsJsonObject();\r
+\r
+                       JsonObject res = GsonUtil.formatJsonObject(null, obj, execution);\r
+\r
+                       restInfo.setRequestBody(res.toString());\r
                        break;\r
                default:\r
-                       throw new ActivitiException(\r
-                                       "The position '" + param.getPosition() + "' is illegal, please check your input!");\r
+                       logger.info("The position {} is illegal, please check your input!",param.getPosition());\r
                }\r
+\r
+               return restInfo;\r
        }\r
 \r
        /**\r
@@ -150,27 +180,176 @@ public class HttpUtil implements JavaDelegate {
         */\r
        public String getValue(Expression expression, DelegateExecution execution) {\r
 \r
-               String value = new String();\r
+               String result = new String();\r
                if (expression != null) {\r
-                       value = (String) expression.getValue(execution);\r
+                       result = (String) expression.getValue(execution);\r
                }\r
 \r
-               return value;\r
+               return result;\r
        }\r
 \r
        /**\r
-        * parse expression in the parameter\r
+        * parse plan expression\r
         * \r
         * @param execution\r
-        * @param param\r
+        * @param expStr\r
+        * @return\r
         */\r
-       public void handleExpression(DelegateExecution execution, Parameter param) {\r
+       public static String parsePlanExpression(String expStr, DelegateExecution execution) {\r
 \r
-               Expression expression = Context.getProcessEngineConfiguration().getExpressionManager()\r
-                               .createExpression(param.getValue());\r
+               String result = "";\r
+               String key = "";\r
+               try {\r
 \r
-               String value = String.valueOf(expression.getValue(execution));\r
+                       Queue<String> planQueue = parseExpressionToQueue(expStr);\r
+                       Object planObj = execution.getVariable(planQueue.poll());\r
+                       \r
+                       if (planQueue.isEmpty()) {\r
+                               result = String.valueOf(planObj);\r
+                       } else if(planObj instanceof HttpResponseMessage) {\r
+                               \r
+                               JsonObject jsonObj = new JsonParser().parse(planObj.toString()).getAsJsonObject();\r
+                               while (!planQueue.isEmpty()) {\r
+                                       \r
+                                       key = planQueue.poll();\r
+                                       Object obj = jsonObj.get(key);\r
+                                       if (obj instanceof JsonArray) {\r
+                                               \r
+                                               break;\r
+                                       }else if(obj instanceof JsonObject){\r
+                                               \r
+                                               jsonObj = (JsonObject) obj;\r
+                                       }else if(obj instanceof JsonPrimitive){\r
+                                               \r
+                                               JsonPrimitive jsonPri = (JsonPrimitive)obj;\r
+                                               result = jsonPri.getAsString();\r
+                                       }\r
+                               }\r
+                       }\r
+               } catch (Exception e) {\r
+                       logger.error("expression {} is illegal, parse key {} failed!", expStr, key, e);\r
+                       throw e;\r
+               }\r
 \r
-               param.setValue(value);\r
+               return result;\r
        }\r
-}
\ No newline at end of file
+\r
+       /**\r
+        * parse topology expression\r
+        * \r
+        * @param expStr\r
+        * @param csarId\r
+        * @return\r
+        */\r
+       public static String parseTopologyExpression(String expStr, DelegateExecution execution) {\r
+\r
+               String csarId = getCsarId(execution);\r
+               Queue<String> topQueue = parseExpressionToQueue(expStr);\r
+\r
+               // parse topology expression\r
+               if (topQueue.size() != 2) {\r
+                       logger.error("topology data {} is illegal!", expStr);\r
+                       return new String();\r
+               }\r
+\r
+               // obtain topology json data\r
+               String topJsonStr = CatalogServiceConsumer.getTopologyJson(csarId, topQueue.poll());\r
+               JsonObject topJsonObj = new JsonParser().parse(topJsonStr).getAsJsonObject();\r
+\r
+               // obtain topology value\r
+               String topValue = topJsonObj.get(topQueue.poll()).getAsString();\r
+\r
+               logger.info("topology expression {} : {}", expStr, topValue);\r
+\r
+               return topValue;\r
+       }\r
+       \r
+       /**\r
+        * parse variable expression\r
+        * \r
+        * @param execution\r
+        * @param expStr\r
+        * @return\r
+        */\r
+       public static String parseVariableExpression(String expStr, DelegateExecution execution) {\r
+\r
+               String result = "";\r
+               \r
+               try {\r
+                       Expression expression = Context.getProcessEngineConfiguration().getExpressionManager()\r
+                                       .createExpression(expStr);\r
+                       \r
+                       result = String.valueOf(expression.getValue(execution));\r
+               } catch (Exception e) {\r
+                       logger.error("variable expression illegal!",e);\r
+               }\r
+\r
+               return result;\r
+       }\r
+       \r
+       /**\r
+        * obtain csar id\r
+        * \r
+        * @param execution\r
+        */\r
+       private static String getCsarId(DelegateExecution execution) {\r
+\r
+               String csarId = "";\r
+               csarId = String.valueOf(execution.getVariable(ConstString.CSARID_EXPRESSION));\r
+\r
+               return csarId;\r
+       }\r
+\r
+       /**\r
+        * compelete uri\r
+        * \r
+        * @param restInfo\r
+        * @return\r
+        */\r
+       private static String compeleteUri(RestInfo restInfo) {\r
+\r
+               String publishUrl = "";\r
+               try {\r
+                       publishUrl = new MsbUtils().getServiceAddress(restInfo.getName(), restInfo.getVersion());\r
+               } catch (Exception e) {\r
+                       logger.error("get service publish address error!", e);\r
+               }\r
+               String realUri = null;\r
+               if (StringUtils.isNotEmpty(publishUrl)) {\r
+                       realUri = publishUrl + restInfo.getPath();\r
+               } else {\r
+                       realUri = PropertyUtil.getBasePath() + restInfo.getUrl() + restInfo.getPath();\r
+               }\r
+\r
+               logger.info("realUri is " + realUri);\r
+               restInfo.setRealUri(realUri);\r
+\r
+               return realUri;\r
+       }\r
+\r
+       /**\r
+        * prase expression as a queue\r
+        * \r
+        * @param expStr\r
+        * @return\r
+        */\r
+       private static Queue<String> parseExpressionToQueue(String expStr) {\r
+\r
+               Queue<String> queue = new LinkedList<String>();\r
+\r
+               if (StringUtils.isNotEmpty(expStr) && expStr.startsWith("[")) {\r
+\r
+                       Pattern p = Pattern.compile("[\\[]+[^]]+[\\]]");\r
+                       Matcher m = p.matcher(expStr);\r
+                       String key = "";\r
+                       while (m.find()) {\r
+                               key = m.group();\r
+                               key = key.substring(1, key.length() - 1);\r
+                               queue.offer(key);\r
+                       }\r
+               }\r
+\r
+               return queue;\r
+       }\r
+\r
+}\r