summaryrefslogtreecommitdiffstats
path: root/activiti-extension/src/main/java/org/onap/workflow/activitiext/restservicetask/HttpUtil.java
blob: ea84ce3f4d7a6a58b483bbfdf3f1647fc6ceb95c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/**
 * 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 boolean 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<Parameter> 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);
		
		return true;
	}

	/**
	 * 
	 * @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<String> 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<String> 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
	 */
	public 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
	 */
	public static Queue<String> parseExpressionToQueue(String expStr) {

		Queue<String> queue = new LinkedList<String>();

		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;
	}

}