2 * Copyright 2016 ZTE Corporation.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.openo.carbon.bpel.resources;
18 import java.io.ByteArrayInputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.Iterator;
25 import java.util.LinkedHashMap;
26 import java.util.List;
29 import java.util.concurrent.atomic.AtomicLong;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.ws.rs.Consumes;
33 import javax.ws.rs.POST;
34 import javax.ws.rs.Path;
35 import javax.ws.rs.Produces;
36 import javax.ws.rs.client.Client;
37 import javax.ws.rs.client.ClientBuilder;
38 import javax.ws.rs.client.Entity;
39 import javax.ws.rs.client.WebTarget;
40 import javax.ws.rs.core.Context;
41 import javax.ws.rs.core.MediaType;
42 import javax.ws.rs.core.Response;
43 import javax.xml.namespace.QName;
45 import org.apache.axiom.om.OMAbstractFactory;
46 import org.apache.axiom.om.OMAttribute;
47 import org.apache.axiom.om.OMDocument;
48 import org.apache.axiom.om.OMElement;
49 import org.apache.axiom.om.OMFactory;
50 import org.apache.axiom.om.OMNamespace;
51 import org.apache.axiom.om.OMText;
52 import org.apache.axiom.om.OMXMLBuilderFactory;
53 import org.apache.axiom.om.OMXMLParserWrapper;
54 import org.apache.axiom.om.util.StAXParserConfiguration;
55 import org.apache.axis2.AxisFault;
56 import org.apache.axis2.addressing.EndpointReference;
57 import org.apache.axis2.client.Options;
58 import org.apache.axis2.client.ServiceClient;
59 import org.apache.axis2.rpc.client.RPCServiceClient;
60 import org.apache.axis2.transport.http.HTTPConstants;
61 import org.apache.axis2.transport.http.HttpTransportProperties;
62 import org.apache.axis2.transport.http.HttpTransportProperties.Authenticator;
63 import org.apache.commons.logging.Log;
64 import org.apache.commons.logging.LogFactory;
65 import org.glassfish.jersey.media.multipart.MultiPartFeature;
66 import org.openo.carbon.bpel.config.ConfigManager;
67 import org.openo.carbon.bpel.util.JsonUtil;
68 import org.openo.carbon.bpel.util.SoapUtil;
69 import org.openo.carbon.bpel.util.Xml2JsonUtil;
71 import com.codahale.metrics.annotation.Timed;
72 import com.eviware.soapui.model.iface.MessagePart;
73 import com.eviware.soapui.model.iface.Request;
74 import com.fasterxml.jackson.core.JsonParseException;
75 import com.fasterxml.jackson.core.JsonProcessingException;
76 import com.fasterxml.jackson.databind.JsonMappingException;
77 import com.fasterxml.jackson.databind.JsonNode;
79 import io.swagger.annotations.Api;
80 import io.swagger.annotations.ApiOperation;
82 @Path("/openoapi/wso2bpel/v1")
83 @Api(tags = {"wso2 bpel api"})
84 public class BpsProcess {
86 private static final Log log = LogFactory.getLog(BpsProcess.class);
88 public static final int STATUS_SUCCESS = 1;
89 public static final int STATUS_FAIL = 0;
91 private Map<String, String> configMap = null;
93 @SuppressWarnings("unused")
94 private final AtomicLong counter;
97 this.counter = new AtomicLong();
100 private synchronized String getConfig(String key) {
101 if (configMap == null) {
102 configMap = new HashMap<String, String>();
103 String uploadFilePath = ConfigManager.getInstance().getProperty("wso2.uploadfile.path");
104 String jksFile = ConfigManager.getInstance().getProperty("wso2.ssl.jks.file");
105 String trustStorePassword =
106 ConfigManager.getInstance().getProperty("wso2.ssl.trustStorePassword");
107 String httpUsername =
108 ConfigManager.getInstance().getProperty("wso2.http.authenticator.username");
109 String httpPassword =
110 ConfigManager.getInstance().getProperty("wso2.http.authenticator.password");
111 String host = ConfigManager.getInstance().getProperty("wso2.host");
112 String port = ConfigManager.getInstance().getProperty("wso2.http.port");
113 configMap.put("uploadFilePath", uploadFilePath);
114 configMap.put("jksFile", jksFile);
115 configMap.put("trustStorePassword", trustStorePassword);
116 configMap.put("httpUsername", httpUsername);
117 configMap.put("httpPassword", httpPassword);
118 configMap.put("host", host);
119 configMap.put("port", port);
121 if (configMap.containsKey(key)) {
122 return configMap.get(key);
124 return ConfigManager.getInstance().getProperty(key);
128 @SuppressWarnings("unchecked")
130 @Path("process/instance")
131 @Consumes(MediaType.APPLICATION_JSON)
132 @Produces(value = MediaType.APPLICATION_JSON)
133 @ApiOperation(value = "startProcess", response = Map.class)
135 public Map<String, Object> startProcess(JsonNode jsonObj, @Context HttpServletRequest request) {
136 Map<String, Object> map = new LinkedHashMap<String, Object>();
137 String errorMessage = "unkown";
139 Map<String, Object> paramMap = new HashMap<String, Object>();
141 paramMap = JsonUtil.json2Bean(jsonObj.toString(), Map.class);
142 String processId = (String) paramMap.get("processId");
144 Object params = paramMap.get("params");
146 String wsdlUrl = getWsdlUrl(processId);
147 String response = invokeWsdl(wsdlUrl, params);
149 map.put("status", STATUS_SUCCESS);
150 map.put("message", "success");
151 // map.put("wsdl", wsdlUrl);
152 map.put("response", response);
154 } catch (JsonParseException e) {
155 errorMessage = e.getLocalizedMessage();
156 log.error(e.getMessage(), e);
158 } catch (JsonMappingException e) {
159 errorMessage = e.getLocalizedMessage();
160 log.error(e.getMessage(), e);
162 } catch (IOException e) {
163 errorMessage = e.getLocalizedMessage();
164 log.error(e.getMessage(), e);
166 } catch (Exception e) {
167 errorMessage = e.getLocalizedMessage();
168 log.error(e.getMessage(), e);
172 map.put("status", STATUS_FAIL);
173 map.put("message", errorMessage);
177 public static String invokeWsdl(String wsdlUrl, Object params) throws Exception {
178 return invokeWsdl(wsdlUrl, params, null);
181 @SuppressWarnings({"unused", "rawtypes"})
182 public static String invokeWsdl(String wsdlUrl, Object params,
183 HttpTransportProperties.Authenticator authenticator) throws Exception {
184 SoapUtil soapUtil = new SoapUtil();
185 Request[] requestTemplates = soapUtil.getRequestTemplate(wsdlUrl);
186 String requestTemplate = null;
187 Request invokeRequest = null;
188 for (Request requestXML : requestTemplates) {
190 InputStream is = new ByteArrayInputStream(requestXML.getRequestContent().getBytes());
191 OMXMLParserWrapper builder = OMXMLBuilderFactory.createOMBuilder(
192 OMAbstractFactory.getOMFactory(), StAXParserConfiguration.STANDALONE, is);
193 OMElement root = builder.getDocumentElement();
194 OMDocument omDocument = builder.getDocument();
195 Iterator iter = omDocument.getChildren();
196 OMElement bodyElement = null;
197 while (iter.hasNext()) {
198 OMElement node = (OMElement) iter.next();
199 String nodeName = node.getLocalName();
200 if (nodeName.equals("Envelope")) {
201 Iterator envChildren = node.getChildElements();
202 while (envChildren.hasNext()) {
203 Object childNode = envChildren.next();
204 if (childNode instanceof OMElement) {
205 if (((OMElement) childNode).getLocalName().equals("Body")) {
206 bodyElement = (OMElement) childNode;
212 Set<String> paramSet = new HashSet<String>();
213 Iterator bodyIter = bodyElement.getChildElements();
214 while (bodyIter.hasNext()) {
215 Object obj = bodyIter.next();
216 OMElement requestBody = (OMElement) obj;
217 paramSet.add(requestBody.getLocalName());
219 if (params instanceof Map) {
220 Set paramKeySet = ((Map) params).keySet();
221 boolean matched = true;
222 for (Object key : paramKeySet) {
223 if (!paramSet.contains(key)) {
229 invokeRequest = requestXML;
230 requestTemplate = requestXML.getRequestContent();
235 if (requestTemplate == null) {
236 throw new Exception("Invalid param.");
239 InputStream is = new ByteArrayInputStream(requestTemplate.getBytes());
240 OMXMLParserWrapper builder = OMXMLBuilderFactory
241 .createOMBuilder(OMAbstractFactory.getOMFactory(), StAXParserConfiguration.STANDALONE, is);
242 OMElement root = builder.getDocumentElement();
243 OMDocument omDocument = builder.getDocument();
244 Iterator iter = omDocument.getChildren();
245 OMElement bodyElement = null;
246 while (iter.hasNext()) {
247 OMElement node = (OMElement) iter.next();
248 String nodeName = node.getLocalName();
249 if (nodeName.equals("Envelope")) {
250 Iterator envChildren = node.getChildElements();
251 while (envChildren.hasNext()) {
252 Object childNode = envChildren.next();
253 if (childNode instanceof OMElement) {
254 if (((OMElement) childNode).getLocalName().equals("Body")) {
255 bodyElement = (OMElement) childNode;
262 Options options = new Options();
263 EndpointReference targetEPR = new EndpointReference(wsdlUrl);
264 options.setTo(targetEPR);
265 if (authenticator != null) {
266 options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
268 ServiceClient sender = new ServiceClient();
269 sender.setOptions(options);
270 OMFactory factory = OMAbstractFactory.getOMFactory();
271 OMElement requestBody = null;
272 Iterator bodyIter = bodyElement.getChildElements();
273 while (bodyIter.hasNext()) {
274 Object obj = bodyIter.next();
275 requestBody = (OMElement) obj;
278 // Iterator requestBodyIter = requestBody.getChildElements();
279 setParams(requestBody, params);
282 OMElement result = null;
283 boolean needResponse = false;
285 MessagePart[] parts = invokeRequest.getResponseParts();
286 if (parts != null && parts.length > 0) {
289 } catch (RuntimeException e) {
291 } catch (Throwable e) {
295 result = sender.sendReceive(requestBody);
296 return Xml2JsonUtil.xml2JSON(result.toString());
298 sender.sendRobust(requestBody);
303 @SuppressWarnings({"rawtypes", "unchecked"})
304 private static void setParams(OMElement requestBody, Object params) {
305 Object currentParams = null;
306 if (params instanceof Map) {
307 currentParams = ((Map) params).get((requestBody).getLocalName());
308 Object obj = requestBody.getFirstElement();
310 if (currentParams instanceof String) {
311 requestBody.setText((String) currentParams);
314 Iterator<OMElement> iter = requestBody.getChildElements();
315 while (iter.hasNext()) {
316 OMElement child = iter.next();
317 setParams((OMElement) child, currentParams);
323 @SuppressWarnings("unchecked")
324 public String getWsdlUrl(String pid) {
325 log.warn("rest begin...");
326 String wsdlUrl = null;
328 System.setProperty("javax.net.ssl.trustStore", "*.keystore");
330 System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
332 System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile"));
333 System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword"));
335 String url = "https://" + getConfig("host") + ":" + getConfig("port")
336 + "/services/ProcessManagementService?wsdl";
337 RPCServiceClient serviceClient = new RPCServiceClient();
338 EndpointReference targetEPR = new EndpointReference(url);
339 Options options = serviceClient.getOptions();
340 options.setTo(targetEPR);
341 // options.setAction("sch:undeployBPELPackage");
343 options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(300000));
344 HttpTransportProperties.Authenticator authenticator =
345 new HttpTransportProperties.Authenticator();
346 List<String> auth = new ArrayList<String>();
347 auth.add(Authenticator.BASIC);
348 authenticator.setAuthSchemes(auth);
349 authenticator.setUsername(getConfig("httpUsername"));
350 authenticator.setPassword(getConfig("httpPassword"));
351 authenticator.setPreemptiveAuthentication(true);
352 options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
354 serviceClient.setOptions(options);
356 OMFactory fac = OMAbstractFactory.getOMFactory();
357 OMNamespace omNs = fac.createOMNamespace("http://wso2.org/bps/management/schema", "sch");
359 OMElement method = fac.createOMElement("getProcessInfoIn", omNs);
360 QName pidQName = QName.valueOf(pid);
361 OMElement pidElement = fac.createOMElement("pid", omNs);
363 pidElement.addChild(fac.createOMText(pidElement, pidQName));
364 method.addChild(pidElement);
368 OMElement res = serviceClient.sendReceive(method);
369 res.getFirstElement().getText();
371 // System.out.println(JsonUtil.bean2Json(parse(res)));
373 Iterator<OMElement> iter = res.getChildrenWithLocalName("endpoints");
374 if (iter.hasNext()) {
375 OMElement endPoints = (OMElement) iter.next();
376 Iterator<OMElement> endPointIter = endPoints.getChildrenWithLocalName("endpointRef");
377 if (endPointIter.hasNext()) {
378 OMElement endpointRef = (OMElement) endPointIter.next();
379 Iterator<OMElement> endpointRefIter =
380 endpointRef.getChildrenWithLocalName("serviceLocations");
381 if (endpointRefIter.hasNext()) {
382 OMElement serviceLocations = (OMElement) endpointRefIter.next();
383 Iterator<OMElement> serviceLocationsIter =
384 serviceLocations.getChildrenWithLocalName("serviceLocation");
385 while (serviceLocationsIter.hasNext()) {
386 OMElement serviceLocation = (OMElement) serviceLocationsIter.next();
387 String sUrl = serviceLocation.getText();
388 if (sUrl.endsWith("wsdl")) {
397 } catch (AxisFault e) {
398 log.error(e.getMessage(), e);
400 } catch (Throwable e) {
401 log.error(e.getMessage(), e);
404 log.warn("invoke finally...");
409 @SuppressWarnings({"unused", "rawtypes", "unchecked"})
410 private Map parse(OMElement node) {
411 Map resultMap = new HashMap();
412 Iterator attrIter = node.getAllAttributes();
413 while (attrIter.hasNext()) {
414 OMAttribute attr = (OMAttribute) attrIter.next();
415 resultMap.put(attr.getLocalName(), attr.getAttributeValue());
417 boolean hasChild = false;
418 List<Map> childList = new ArrayList<Map>();
419 Iterator childIter = node.getChildren();// getChildElements();
420 while (childIter.hasNext()) {
422 Object child = childIter.next();
423 if (child instanceof OMText) {
424 resultMap.put(node.getLocalName(), ((OMText) child).getText());
425 } else if (child instanceof OMElement) {
426 childList.add(parse((OMElement) child));
427 resultMap.put(node.getLocalName(), childList);
433 public static void main1(String[] args) {
434 Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
435 WebTarget target = client.target("http://127.0.0.1:8080/wso2bpel/v1/process/instance");
437 "{\"processId\":\"{http://ode/bpel/unit-test}HelloWorld2-18\",\"params\": {\"hello\":{\"TestPart\":\"AAA\"}}}";
438 Response response = target.request(MediaType.APPLICATION_JSON)
439 .post(Entity.entity(jsonObj, MediaType.APPLICATION_JSON));
440 int responseCode = response.getStatus();
441 if (responseCode == 200) {
442 String excuteRespJson = response.readEntity(String.class);
443 // context.setExcuteRespJson(excuteRespJson);
444 // System.out.println("excute responseJson=====" +
445 // context.getExcuteRespJson());
446 System.out.println(excuteRespJson);
449 System.out.println("************************************************************************");
451 "{\"processId\":\"{http://ode/bpel/unit-test}HelloWorld2-18\",\"params\": {\"hello\":{\"TestPart\":\"AAA\"}}}";
452 BpsProcess process = new BpsProcess();
454 Map<String, Object> resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null);
455 System.out.println(JsonUtil.bean2Json(resultMap));
456 } catch (JsonProcessingException e) {
458 } catch (IOException e) {
461 System.out.println("************************************************************************");
463 "{\"processId\":\"{http://ode/bpel/unit-test}HelloXslWorld-3\",\"params\": {\"helloXsl\":{\"TestPart\":{\"content\":\"AAA\"}}}}";
464 process = new BpsProcess();
466 Map<String, Object> resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null);
467 System.out.println(JsonUtil.bean2Json(resultMap));
468 } catch (JsonProcessingException e) {
470 } catch (IOException e) {
473 System.out.println("************************************************************************");
475 "{\"processId\":\"{http://wso2.org/bps/samples/While}While-5\",\"params\": {\"WhileRequest\":{\"input\":\"365\"}}}";
476 process = new BpsProcess();
478 Map<String, Object> resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null);
479 System.out.println(JsonUtil.bean2Json(resultMap));
480 } catch (JsonProcessingException e) {
482 } catch (IOException e) {
487 @SuppressWarnings("unchecked")
488 public static void main(String[] args) {
490 Map<String, Object> map = new LinkedHashMap<String, Object>();
491 String errorMessage = "unkown";
493 Map<String, Object> paramMap = new HashMap<String, Object>();
496 "{\"planInput\":{\"sfc_count\":\"2\",\"nsInstanceId\":\"223\",\"vnfmId\":\"112\",\"instanceId\":\"334\",\"object_context\":\"{\\\"e\\\":{\\\"f\\\":\\\"4\\\"}}\",\"vnf_count\":\"2\",\"serviceTemplateId\":\"?\",\"vl_count\":\"2\",\"containerapiUrl\":\"?\",\"object_additionalParamForVnf\":\"[{\\\"b\\\":1},{\\\"c\\\":{\\\"d\\\":\\\"2\\\"}}}]\",\"object_additionalParamForNs\":\"[{\\\"a\\\":3},{\\\"e\\\":{\\\"f\\\":\\\"4\\\"}}}]\"}}";
498 "{\"processId\":\"{http://wso2.org/bps/samples/While}While-5\",\"params\":" + param + "}";
499 paramMap = JsonUtil.json2Bean(jsonObj.toString(), Map.class);
500 Object params = paramMap.get("params");
501 String wsdlUrl = "http://10.74.151.36:9763/services/initService?wsdl";
502 String response = invokeWsdl(wsdlUrl, params);
503 map.put("status", STATUS_SUCCESS);
504 map.put("message", "success");
505 map.put("response", response);
506 System.out.println(JsonUtil.bean2Json(map));
507 } catch (JsonParseException e) {
508 errorMessage = e.getLocalizedMessage();
509 log.error(e.getMessage(), e);
511 } catch (JsonMappingException e) {
512 errorMessage = e.getLocalizedMessage();
513 log.error(e.getMessage(), e);
515 } catch (IOException e) {
516 errorMessage = e.getLocalizedMessage();
517 log.error(e.getMessage(), e);
519 } catch (Exception e) {
520 errorMessage = e.getLocalizedMessage();
521 log.error(e.getMessage(), e);
525 map.put("status", STATUS_FAIL);
526 map.put("message", errorMessage);
528 System.out.println(JsonUtil.bean2Json(map));
529 } catch (IOException e) {
530 errorMessage = e.getLocalizedMessage();
531 log.error(e.getMessage(), e);