c86a01e94e1c7a6d4fbe729b8b8f63d9747bb98e
[vfc/nfvo/wfengine.git] / wso2bpel-ext / wso2bpel-core / wso2bpel-mgr / src / main / java / org / openo / carbon / bpel / resources / BpsProcess.java
1 /**
2  * Copyright 2016 ZTE Corporation.
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 package org.openo.carbon.bpel.resources;
17
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;
27 import java.util.Map;
28 import java.util.Set;
29 import java.util.concurrent.atomic.AtomicLong;
30
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;
44
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;
70
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;
78
79 import io.swagger.annotations.Api;
80 import io.swagger.annotations.ApiOperation;
81
82 @Path("/openoapi/wso2bpel/v1")
83 @Api(tags = {"wso2 bpel api"})
84 public class BpsProcess {
85
86   private static final Log log = LogFactory.getLog(BpsProcess.class);
87
88   public static final int STATUS_SUCCESS = 1;
89   public static final int STATUS_FAIL = 0;
90
91   private Map<String, String> configMap = null;
92
93   @SuppressWarnings("unused")
94   private final AtomicLong counter;
95
96   public BpsProcess() {
97     this.counter = new AtomicLong();
98   }
99
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);
120     }
121     if (configMap.containsKey(key)) {
122       return configMap.get(key);
123     } else {
124       return ConfigManager.getInstance().getProperty(key);
125     }
126   }
127
128   @SuppressWarnings("unchecked")
129   @POST
130   @Path("process/instance")
131   @Consumes(MediaType.APPLICATION_JSON)
132   @Produces(value = MediaType.APPLICATION_JSON)
133   @ApiOperation(value = "startProcess", response = Map.class)
134   @Timed
135   public Map<String, Object> startProcess(JsonNode jsonObj, @Context HttpServletRequest request) {
136     Map<String, Object> map = new LinkedHashMap<String, Object>();
137     String errorMessage = "unkown";
138
139     Map<String, Object> paramMap = new HashMap<String, Object>();
140     try {
141       paramMap = JsonUtil.json2Bean(jsonObj.toString(), Map.class);
142       String processId = (String) paramMap.get("processId");
143
144       Object params = paramMap.get("params");
145
146       String wsdlUrl = getWsdlUrl(processId);
147       String response = invokeWsdl(wsdlUrl, params);
148
149       map.put("status", STATUS_SUCCESS);
150       map.put("message", "success");
151       // map.put("wsdl", wsdlUrl);
152       map.put("response", response);
153       return map;
154     } catch (JsonParseException e) {
155       errorMessage = e.getLocalizedMessage();
156       log.error(e.getMessage(), e);
157       e.printStackTrace();
158     } catch (JsonMappingException e) {
159       errorMessage = e.getLocalizedMessage();
160       log.error(e.getMessage(), e);
161       e.printStackTrace();
162     } catch (IOException e) {
163       errorMessage = e.getLocalizedMessage();
164       log.error(e.getMessage(), e);
165       e.printStackTrace();
166     } catch (Exception e) {
167       errorMessage = e.getLocalizedMessage();
168       log.error(e.getMessage(), e);
169       e.printStackTrace();
170     }
171
172     map.put("status", STATUS_FAIL);
173     map.put("message", errorMessage);
174     return map;
175   }
176
177   public static String invokeWsdl(String wsdlUrl, Object params) throws Exception {
178     return invokeWsdl(wsdlUrl, params, null);
179   }
180
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) {
189
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;
207               }
208             }
209           }
210         }
211       }
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());
218       }
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)) {
224             matched = false;
225             continue;
226           }
227         }
228         if (matched) {
229           invokeRequest = requestXML;
230           requestTemplate = requestXML.getRequestContent();
231           break;
232         }
233       }
234     }
235     if (requestTemplate == null) {
236       throw new Exception("Invalid param.");
237     }
238
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;
256             }
257           }
258         }
259       }
260     }
261
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);
267     }
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;
276     }
277
278     // Iterator requestBodyIter = requestBody.getChildElements();
279     setParams(requestBody, params);
280
281     requestBody.build();
282     OMElement result = null;
283     boolean needResponse = false;
284     try {
285       MessagePart[] parts = invokeRequest.getResponseParts();
286       if (parts != null && parts.length > 0) {
287         needResponse = true;
288       }
289     } catch (RuntimeException e) {
290       e.printStackTrace();
291     } catch (Throwable e) {
292       e.printStackTrace();
293     }
294     if (needResponse) {
295       result = sender.sendReceive(requestBody);
296       return Xml2JsonUtil.xml2JSON(result.toString());
297     } else {
298       sender.sendRobust(requestBody);
299       return "";
300     }
301   }
302
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();
309       if (obj == null) {
310         if (currentParams instanceof String) {
311           requestBody.setText((String) currentParams);
312         }
313       } else {
314         Iterator<OMElement> iter = requestBody.getChildElements();
315         while (iter.hasNext()) {
316           OMElement child = iter.next();
317           setParams((OMElement) child, currentParams);
318         }
319       }
320     }
321   }
322
323   @SuppressWarnings("unchecked")
324   public String getWsdlUrl(String pid) {
325     log.warn("rest begin...");
326     String wsdlUrl = null;
327     try {
328       System.setProperty("javax.net.ssl.trustStore", "*.keystore");
329
330       System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
331
332       System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile"));
333       System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword"));
334
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");
342
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);
353
354       serviceClient.setOptions(options);
355
356       OMFactory fac = OMAbstractFactory.getOMFactory();
357       OMNamespace omNs = fac.createOMNamespace("http://wso2.org/bps/management/schema", "sch");
358
359       OMElement method = fac.createOMElement("getProcessInfoIn", omNs);
360       QName pidQName = QName.valueOf(pid);
361       OMElement pidElement = fac.createOMElement("pid", omNs);
362
363       pidElement.addChild(fac.createOMText(pidElement, pidQName));
364       method.addChild(pidElement);
365
366       method.build();
367
368       OMElement res = serviceClient.sendReceive(method);
369       res.getFirstElement().getText();
370
371       // System.out.println(JsonUtil.bean2Json(parse(res)));
372
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")) {
389                 wsdlUrl = sUrl;
390                 break;
391               }
392             }
393           }
394         }
395       }
396
397     } catch (AxisFault e) {
398       log.error(e.getMessage(), e);
399       e.printStackTrace();
400     } catch (Throwable e) {
401       log.error(e.getMessage(), e);
402       e.printStackTrace();
403     } finally {
404       log.warn("invoke finally...");
405     }
406     return wsdlUrl;
407   }
408
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());
416     }
417     boolean hasChild = false;
418     List<Map> childList = new ArrayList<Map>();
419     Iterator childIter = node.getChildren();// getChildElements();
420     while (childIter.hasNext()) {
421       hasChild = true;
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);
428       }
429     }
430     return resultMap;
431   }
432
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");
436     String jsonObj =
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);
447     }
448
449     System.out.println("************************************************************************");
450     jsonObj =
451         "{\"processId\":\"{http://ode/bpel/unit-test}HelloWorld2-18\",\"params\": {\"hello\":{\"TestPart\":\"AAA\"}}}";
452     BpsProcess process = new BpsProcess();
453     try {
454       Map<String, Object> resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null);
455       System.out.println(JsonUtil.bean2Json(resultMap));
456     } catch (JsonProcessingException e) {
457       e.printStackTrace();
458     } catch (IOException e) {
459       e.printStackTrace();
460     }
461     System.out.println("************************************************************************");
462     jsonObj =
463         "{\"processId\":\"{http://ode/bpel/unit-test}HelloXslWorld-3\",\"params\": {\"helloXsl\":{\"TestPart\":{\"content\":\"AAA\"}}}}";
464     process = new BpsProcess();
465     try {
466       Map<String, Object> resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null);
467       System.out.println(JsonUtil.bean2Json(resultMap));
468     } catch (JsonProcessingException e) {
469       e.printStackTrace();
470     } catch (IOException e) {
471       e.printStackTrace();
472     }
473     System.out.println("************************************************************************");
474     jsonObj =
475         "{\"processId\":\"{http://wso2.org/bps/samples/While}While-5\",\"params\": {\"WhileRequest\":{\"input\":\"365\"}}}";
476     process = new BpsProcess();
477     try {
478       Map<String, Object> resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null);
479       System.out.println(JsonUtil.bean2Json(resultMap));
480     } catch (JsonProcessingException e) {
481       e.printStackTrace();
482     } catch (IOException e) {
483     }
484
485   }
486
487   @SuppressWarnings("unchecked")
488   public static void main(String[] args) {
489
490     Map<String, Object> map = new LinkedHashMap<String, Object>();
491     String errorMessage = "unkown";
492
493     Map<String, Object> paramMap = new HashMap<String, Object>();
494     try {
495       String param =
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\\\"}}}]\"}}";
497       String jsonObj =
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);
510       e.printStackTrace();
511     } catch (JsonMappingException e) {
512       errorMessage = e.getLocalizedMessage();
513       log.error(e.getMessage(), e);
514       e.printStackTrace();
515     } catch (IOException e) {
516       errorMessage = e.getLocalizedMessage();
517       log.error(e.getMessage(), e);
518       e.printStackTrace();
519     } catch (Exception e) {
520       errorMessage = e.getLocalizedMessage();
521       log.error(e.getMessage(), e);
522       e.printStackTrace();
523     }
524
525     map.put("status", STATUS_FAIL);
526     map.put("message", errorMessage);
527     try {
528       System.out.println(JsonUtil.bean2Json(map));
529     } catch (IOException e) {
530       errorMessage = e.getLocalizedMessage();
531       log.error(e.getMessage(), e);
532       e.printStackTrace();
533     }
534
535   }
536 }