/** * Copyright 2017 ZTE Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onap.workflow.activitiext.restservicetask; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.activiti.engine.ActivitiException; import org.activiti.engine.delegate.BpmnError; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.Expression; import org.activiti.engine.delegate.JavaDelegate; import org.activiti.engine.impl.context.Context; import org.apache.commons.lang3.StringUtils; import org.onap.workflow.activitiext.common.ConstString; import org.onap.workflow.activitiext.common.Parameter; import org.onap.workflow.activitiext.common.RestInfo; import org.onap.workflow.utils.MsbUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSONArray; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; /** * rest service * * @author 10222158 * */ public class HttpUtil implements JavaDelegate { private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class); private Expression name; private Expression version; private Expression url; private Expression path; private Expression method; private Expression accept; private Expression contentType; private Expression parameters; @Override public void execute(DelegateExecution execution) throws ActivitiException { try { this.executeMethod(execution); } catch (Exception e) { logger.error("Invoke rest service failed!", e); throw new BpmnError(e.getMessage()); } } /** * invoke rest service * * @param execution */ public void executeMethod(DelegateExecution execution) throws Exception { // get rest task information RestInfo restInfo = new RestInfo(); restInfo.setName(getValue(name, execution)); restInfo.setVersion(getValue(version, execution)); restInfo.setUrl(getValue(url, execution)); restInfo.setPath(getValue(path, execution)); restInfo.setMethod(getValue(method, execution)); restInfo.setAccept(getValue(accept, execution)); restInfo.setContentType(getValue(contentType, execution)); String parametersValue = getValue(parameters, execution); // real uri compeleteUri(restInfo); if (!StringUtils.isEmpty(parametersValue)) { // Parse the parameter into Object List List parameters = JSONArray.parseArray(parametersValue, Parameter.class); for (Parameter param : parameters) { restInfo = handleParam(execution, param, restInfo); } } // invoke http service HttpResponseMessage msg = HighLevelRestApi.invoke(restInfo); // inject the result to variable execution.setVariable(execution.getCurrentActivityId(), msg); } /** * * @param execution * @param param * @param requestBody * @param uriValue */ public RestInfo handleParam(DelegateExecution execution, Parameter param, RestInfo restInfo) throws ActivitiException { String realUri = restInfo.getRealUri(); if (ConstString.PARAMETER_VALUE_SOURCE_PLAN.equals(param.getValueSource())) { String planValue = parsePlanExpression(param.getValue(), execution); param.setValue(planValue); } else if (ConstString.PARAMETER_VALUE_SOURCE_TOPOLOGY.equals(param.getValueSource())) { String topValue = parseTopologyExpression(param.getValue(), execution); param.setValue(topValue); }else if(ConstString.PARAMETER_VALUE_SOURCE_VARIABLE.equals(param.getValueSource())) { String varValue = parseVariableExpression(param.getValue(), execution); param.setValue(varValue); } switch (param.getPosition()) { case ConstString.PARAMETER_POSITION_PATH: // replace the path parameter realUri = realUri.replaceAll("\\{+" + param.getName() + "+\\}", param.getValue()); restInfo.setRealUri(realUri); break; case ConstString.PARAMETER_POSITION_QUERY: // add the query parameter if (!realUri.contains("?")) { realUri = realUri + "?" + param.getName() + "=" + param.getValue(); } else { realUri = realUri + "&" + param.getName() + "=" + param.getValue(); } restInfo.setRealUri(realUri); break; case ConstString.PARAMETER_POSITION_BODY: // add parameter to request body String value = param.getValue(); JsonObject obj = new JsonParser().parse(value).getAsJsonObject(); JsonObject res = GsonUtil.formatJsonObject(null, obj, execution); restInfo.setRequestBody(res.toString()); break; default: logger.info("The position {} is illegal, please check your input!",param.getPosition()); } return restInfo; } /** * get value from VariableScope * * @param expression * @param execution * @return */ public String getValue(Expression expression, DelegateExecution execution) { String result = new String(); if (expression != null) { result = (String) expression.getValue(execution); } return result; } /** * parse plan expression * * @param execution * @param expStr * @return */ public static String parsePlanExpression(String expStr, DelegateExecution execution) { String result = ""; String key = ""; try { Queue planQueue = parseExpressionToQueue(expStr); Object planObj = execution.getVariable(planQueue.poll()); if (planQueue.isEmpty()) { result = String.valueOf(planObj); } else if(planObj instanceof HttpResponseMessage) { JsonObject jsonObj = new JsonParser().parse(planObj.toString()).getAsJsonObject(); while (!planQueue.isEmpty()) { key = planQueue.poll(); Object obj = jsonObj.get(key); if (obj instanceof JsonArray) { break; }else if(obj instanceof JsonObject){ jsonObj = (JsonObject) obj; }else if(obj instanceof JsonPrimitive){ JsonPrimitive jsonPri = (JsonPrimitive)obj; result = jsonPri.getAsString(); } } } } catch (Exception e) { logger.error("expression {} is illegal, parse key {} failed!", expStr, key, e); throw e; } return result; } /** * parse topology expression * * @param expStr * @param csarId * @return */ public static String parseTopologyExpression(String expStr, DelegateExecution execution) { String csarId = getCsarId(execution); Queue topQueue = parseExpressionToQueue(expStr); // parse topology expression if (topQueue.size() != 2) { logger.error("topology data {} is illegal!", expStr); return new String(); } // obtain topology json data String topJsonStr = CatalogServiceConsumer.getTopologyJson(csarId, topQueue.poll()); JsonObject topJsonObj = new JsonParser().parse(topJsonStr).getAsJsonObject(); // obtain topology value String topValue = topJsonObj.get(topQueue.poll()).getAsString(); logger.info("topology expression {} : {}", expStr, topValue); return topValue; } /** * parse variable expression * * @param execution * @param expStr * @return */ public static String parseVariableExpression(String expStr, DelegateExecution execution) { String result = ""; try { Expression expression = Context.getProcessEngineConfiguration().getExpressionManager() .createExpression(expStr); result = String.valueOf(expression.getValue(execution)); } catch (Exception e) { logger.error("variable expression illegal!",e); } return result; } /** * obtain csar id * * @param execution */ private static String getCsarId(DelegateExecution execution) { String csarId = ""; csarId = String.valueOf(execution.getVariable(ConstString.CSARID_EXPRESSION)); return csarId; } /** * compelete uri * * @param restInfo * @return */ private static String compeleteUri(RestInfo restInfo) { String publishUrl = ""; try { publishUrl = new MsbUtils().getServiceAddress(restInfo.getName(), restInfo.getVersion()); } catch (Exception e) { logger.error("get service publish address error!", e); } String realUri = null; if (StringUtils.isNotEmpty(publishUrl)) { realUri = publishUrl + restInfo.getPath(); } else { realUri = PropertyUtil.getBasePath() + restInfo.getUrl() + restInfo.getPath(); } logger.info("realUri is " + realUri); restInfo.setRealUri(realUri); return realUri; } /** * prase expression as a queue * * @param expStr * @return */ private static Queue parseExpressionToQueue(String expStr) { Queue queue = new LinkedList(); if (StringUtils.isNotEmpty(expStr) && expStr.startsWith("[")) { Pattern p = Pattern.compile("[\\[]+[^]]+[\\]]"); Matcher m = p.matcher(expStr); String key = ""; while (m.find()) { key = m.group(); key = key.substring(1, key.length() - 1); queue.offer(key); } } return queue; } }