Deploy plan file to WSO2 get error
[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.common.Config;
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("/")
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       //Config.getConfigration().getMsbServerAddr();
104      /* String uploadFilePath = ConfigManager.getInstance().getProperty("wso2.uploadfile.path");
105       String jksFile = ConfigManager.getInstance().getProperty("wso2.ssl.jks.file");
106       String trustStorePassword =
107           ConfigManager.getInstance().getProperty("wso2.ssl.trustStorePassword");
108       String httpUsername =
109           ConfigManager.getInstance().getProperty("wso2.http.authenticator.username");
110       String httpPassword =
111           ConfigManager.getInstance().getProperty("wso2.http.authenticator.password");
112       String host = ConfigManager.getInstance().getProperty("wso2.host");
113       String port = ConfigManager.getInstance().getProperty("wso2.http.port");*/
114       String uploadFilePath = Config.getConfigration().getWso2UploadFilePath();
115       String jksFile = Config.getConfigration().getWso2SslJksFile();
116       String trustStorePassword = Config.getConfigration().getWso2SslJksPassword();
117       String httpUsername = Config.getConfigration().getWso2AuthUserName();
118       String httpPassword = Config.getConfigration().getWso2AuthPassword();
119       String host = Config.getConfigration().getWso2Host();
120       String port = Config.getConfigration().getWso2HostPort();
121       configMap.put("uploadFilePath", uploadFilePath);
122       configMap.put("jksFile", jksFile);
123       configMap.put("trustStorePassword", trustStorePassword);
124       configMap.put("httpUsername", httpUsername);
125       configMap.put("httpPassword", httpPassword);
126       configMap.put("host", host);
127       configMap.put("port", port);
128     }
129     if (configMap.containsKey(key)) {
130       return configMap.get(key);
131     } else {
132       return "";
133     }
134   }
135
136   @SuppressWarnings("unchecked")
137   @POST
138   @Path("process/instance")
139   @Consumes(MediaType.APPLICATION_JSON)
140   @Produces(value = MediaType.APPLICATION_JSON)
141   @ApiOperation(value = "startProcess", response = Map.class)
142   @Timed
143   public Map<String, Object> startProcess(JsonNode jsonObj, @Context HttpServletRequest request) {
144     Map<String, Object> map = new LinkedHashMap<String, Object>();
145     String errorMessage = "unkown";
146
147     Map<String, Object> paramMap = new HashMap<String, Object>();
148     try {
149       paramMap = JsonUtil.json2Bean(jsonObj.toString(), Map.class);
150       String processId = (String) paramMap.get("processId");
151
152       Object params = paramMap.get("params");
153
154       String wsdlUrl = getWsdlUrl(processId);
155       String response = invokeWsdl(wsdlUrl, params);
156
157       map.put("status", STATUS_SUCCESS);
158       map.put("message", "success");
159       // map.put("wsdl", wsdlUrl);
160       map.put("response", response);
161       return map;
162     } catch (JsonParseException e) {
163       errorMessage = e.getLocalizedMessage();
164       log.error(e.getMessage(), e);
165       e.printStackTrace();
166     } catch (JsonMappingException e) {
167       errorMessage = e.getLocalizedMessage();
168       log.error(e.getMessage(), e);
169       e.printStackTrace();
170     } catch (IOException e) {
171       errorMessage = e.getLocalizedMessage();
172       log.error(e.getMessage(), e);
173       e.printStackTrace();
174     } catch (Exception e) {
175       errorMessage = e.getLocalizedMessage();
176       log.error(e.getMessage(), e);
177       e.printStackTrace();
178     }
179
180     map.put("status", STATUS_FAIL);
181     map.put("message", errorMessage);
182     return map;
183   }
184
185   public static String invokeWsdl(String wsdlUrl, Object params) throws Exception {
186     return invokeWsdl(wsdlUrl, params, null);
187   }
188
189   @SuppressWarnings({"unused", "rawtypes"})
190   public static String invokeWsdl(String wsdlUrl, Object params,
191       HttpTransportProperties.Authenticator authenticator) throws Exception {
192     SoapUtil soapUtil = new SoapUtil();
193     Request[] requestTemplates = soapUtil.getRequestTemplate(wsdlUrl);
194     String requestTemplate = null;
195     Request invokeRequest = null;
196     for (Request requestXML : requestTemplates) {
197
198       InputStream is = new ByteArrayInputStream(requestXML.getRequestContent().getBytes());
199       OMXMLParserWrapper builder = OMXMLBuilderFactory.createOMBuilder(
200           OMAbstractFactory.getOMFactory(), StAXParserConfiguration.STANDALONE, is);
201       OMElement root = builder.getDocumentElement();
202       OMDocument omDocument = builder.getDocument();
203       Iterator iter = omDocument.getChildren();
204       OMElement bodyElement = null;
205       while (iter.hasNext()) {
206         OMElement node = (OMElement) iter.next();
207         String nodeName = node.getLocalName();
208         if (nodeName.equals("Envelope")) {
209           Iterator envChildren = node.getChildElements();
210           while (envChildren.hasNext()) {
211             Object childNode = envChildren.next();
212             if (childNode instanceof OMElement) {
213               if (((OMElement) childNode).getLocalName().equals("Body")) {
214                 bodyElement = (OMElement) childNode;
215               }
216             }
217           }
218         }
219       }
220       Set<String> paramSet = new HashSet<String>();
221       Iterator bodyIter = bodyElement.getChildElements();
222       while (bodyIter.hasNext()) {
223         Object obj = bodyIter.next();
224         OMElement requestBody = (OMElement) obj;
225         paramSet.add(requestBody.getLocalName());
226       }
227       if (params instanceof Map) {
228         Set paramKeySet = ((Map) params).keySet();
229         boolean matched = true;
230         for (Object key : paramKeySet) {
231           if (!paramSet.contains(key)) {
232             matched = false;
233             continue;
234           }
235         }
236         if (matched) {
237           invokeRequest = requestXML;
238           requestTemplate = requestXML.getRequestContent();
239           break;
240         }
241       }
242     }
243     if (requestTemplate == null) {
244       throw new Exception("Invalid param.");
245     }
246
247     InputStream is = new ByteArrayInputStream(requestTemplate.getBytes());
248     OMXMLParserWrapper builder = OMXMLBuilderFactory
249         .createOMBuilder(OMAbstractFactory.getOMFactory(), StAXParserConfiguration.STANDALONE, is);
250     OMElement root = builder.getDocumentElement();
251     OMDocument omDocument = builder.getDocument();
252     Iterator iter = omDocument.getChildren();
253     OMElement bodyElement = null;
254     while (iter.hasNext()) {
255       OMElement node = (OMElement) iter.next();
256       String nodeName = node.getLocalName();
257       if (nodeName.equals("Envelope")) {
258         Iterator envChildren = node.getChildElements();
259         while (envChildren.hasNext()) {
260           Object childNode = envChildren.next();
261           if (childNode instanceof OMElement) {
262             if (((OMElement) childNode).getLocalName().equals("Body")) {
263               bodyElement = (OMElement) childNode;
264             }
265           }
266         }
267       }
268     }
269
270     Options options = new Options();
271     EndpointReference targetEPR = new EndpointReference(wsdlUrl);
272     options.setTo(targetEPR);
273     if (authenticator != null) {
274       options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
275     }
276     ServiceClient sender = new ServiceClient();
277     sender.setOptions(options);
278     OMFactory factory = OMAbstractFactory.getOMFactory();
279     OMElement requestBody = null;
280     Iterator bodyIter = bodyElement.getChildElements();
281     while (bodyIter.hasNext()) {
282       Object obj = bodyIter.next();
283       requestBody = (OMElement) obj;
284     }
285
286     // Iterator requestBodyIter = requestBody.getChildElements();
287     setParams(requestBody, params);
288
289     requestBody.build();
290     OMElement result = null;
291     boolean needResponse = false;
292     try {
293       MessagePart[] parts = invokeRequest.getResponseParts();
294       if (parts != null && parts.length > 0) {
295         needResponse = true;
296       }
297     } catch (RuntimeException e) {
298       e.printStackTrace();
299     } catch (Throwable e) {
300       e.printStackTrace();
301     }
302     if (needResponse) {
303       result = sender.sendReceive(requestBody);
304       return Xml2JsonUtil.xml2JSON(result.toString());
305     } else {
306       sender.sendRobust(requestBody);
307       return "";
308     }
309   }
310
311   @SuppressWarnings({"rawtypes", "unchecked"})
312   private static void setParams(OMElement requestBody, Object params) {
313     Object currentParams = null;
314     if (params instanceof Map) {
315       currentParams = ((Map) params).get((requestBody).getLocalName());
316       Object obj = requestBody.getFirstElement();
317       if (obj == null) {
318         if (currentParams instanceof String) {
319           requestBody.setText((String) currentParams);
320         }
321       } else {
322         Iterator<OMElement> iter = requestBody.getChildElements();
323         while (iter.hasNext()) {
324           OMElement child = iter.next();
325           setParams((OMElement) child, currentParams);
326         }
327       }
328     }
329   }
330
331   @SuppressWarnings("unchecked")
332   public String getWsdlUrl(String pid) {
333     log.warn("rest begin...");
334     String wsdlUrl = null;
335     try {
336       System.setProperty("javax.net.ssl.trustStore", "*.keystore");
337
338       System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
339
340       System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile"));
341       System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword"));
342
343       String url = "https://" + getConfig("host") + ":" + getConfig("port")
344           + "/services/ProcessManagementService?wsdl";
345       RPCServiceClient serviceClient = new RPCServiceClient();
346       EndpointReference targetEPR = new EndpointReference(url);
347       Options options = serviceClient.getOptions();
348       options.setTo(targetEPR);
349       // options.setAction("sch:undeployBPELPackage");
350
351       options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(300000));
352       HttpTransportProperties.Authenticator authenticator =
353           new HttpTransportProperties.Authenticator();
354       List<String> auth = new ArrayList<String>();
355       auth.add(Authenticator.BASIC);
356       authenticator.setAuthSchemes(auth);
357       authenticator.setUsername(getConfig("httpUsername"));
358       authenticator.setPassword(getConfig("httpPassword"));
359       authenticator.setPreemptiveAuthentication(true);
360       options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
361
362       serviceClient.setOptions(options);
363
364       OMFactory fac = OMAbstractFactory.getOMFactory();
365       OMNamespace omNs = fac.createOMNamespace("http://wso2.org/bps/management/schema", "sch");
366
367       OMElement method = fac.createOMElement("getProcessInfoIn", omNs);
368       QName pidQName = QName.valueOf(pid);
369       OMElement pidElement = fac.createOMElement("pid", omNs);
370
371       pidElement.addChild(fac.createOMText(pidElement, pidQName));
372       method.addChild(pidElement);
373
374       method.build();
375
376       OMElement res = serviceClient.sendReceive(method);
377       res.getFirstElement().getText();
378
379       // System.out.println(JsonUtil.bean2Json(parse(res)));
380
381       Iterator<OMElement> iter = res.getChildrenWithLocalName("endpoints");
382       if (iter.hasNext()) {
383         OMElement endPoints = (OMElement) iter.next();
384         Iterator<OMElement> endPointIter = endPoints.getChildrenWithLocalName("endpointRef");
385         if (endPointIter.hasNext()) {
386           OMElement endpointRef = (OMElement) endPointIter.next();
387           Iterator<OMElement> endpointRefIter =
388               endpointRef.getChildrenWithLocalName("serviceLocations");
389           if (endpointRefIter.hasNext()) {
390             OMElement serviceLocations = (OMElement) endpointRefIter.next();
391             Iterator<OMElement> serviceLocationsIter =
392                 serviceLocations.getChildrenWithLocalName("serviceLocation");
393             while (serviceLocationsIter.hasNext()) {
394               OMElement serviceLocation = (OMElement) serviceLocationsIter.next();
395               String sUrl = serviceLocation.getText();
396               if (sUrl.endsWith("wsdl")) {
397                 wsdlUrl = sUrl;
398                 break;
399               }
400             }
401           }
402         }
403       }
404
405     } catch (AxisFault e) {
406       log.error(e.getMessage(), e);
407       e.printStackTrace();
408     } catch (Throwable e) {
409       log.error(e.getMessage(), e);
410       e.printStackTrace();
411     } finally {
412       log.warn("invoke finally...");
413     }
414     return wsdlUrl;
415   }
416
417   @SuppressWarnings({"unused", "rawtypes", "unchecked"})
418   private Map parse(OMElement node) {
419     Map resultMap = new HashMap();
420     Iterator attrIter = node.getAllAttributes();
421     while (attrIter.hasNext()) {
422       OMAttribute attr = (OMAttribute) attrIter.next();
423       resultMap.put(attr.getLocalName(), attr.getAttributeValue());
424     }
425     boolean hasChild = false;
426     List<Map> childList = new ArrayList<Map>();
427     Iterator childIter = node.getChildren();// getChildElements();
428     while (childIter.hasNext()) {
429       hasChild = true;
430       Object child = childIter.next();
431       if (child instanceof OMText) {
432         resultMap.put(node.getLocalName(), ((OMText) child).getText());
433       } else if (child instanceof OMElement) {
434         childList.add(parse((OMElement) child));
435         resultMap.put(node.getLocalName(), childList);
436       }
437     }
438     return resultMap;
439   }
440
441   public static void main1(String[] args) {
442     Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
443     WebTarget target = client.target("http://127.0.0.1:8080/wso2bpel/v1/process/instance");
444     String jsonObj =
445         "{\"processId\":\"{http://ode/bpel/unit-test}HelloWorld2-18\",\"params\": {\"hello\":{\"TestPart\":\"AAA\"}}}";
446     Response response = target.request(MediaType.APPLICATION_JSON)
447         .post(Entity.entity(jsonObj, MediaType.APPLICATION_JSON));
448     int responseCode = response.getStatus();
449     if (responseCode == 200) {
450       String excuteRespJson = response.readEntity(String.class);
451       // context.setExcuteRespJson(excuteRespJson);
452       // System.out.println("excute responseJson=====" +
453       // context.getExcuteRespJson());
454       System.out.println(excuteRespJson);
455     }
456
457     System.out.println("************************************************************************");
458     jsonObj =
459         "{\"processId\":\"{http://ode/bpel/unit-test}HelloWorld2-18\",\"params\": {\"hello\":{\"TestPart\":\"AAA\"}}}";
460     BpsProcess process = new BpsProcess();
461     try {
462       Map<String, Object> resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null);
463       System.out.println(JsonUtil.bean2Json(resultMap));
464     } catch (JsonProcessingException e) {
465       e.printStackTrace();
466     } catch (IOException e) {
467       e.printStackTrace();
468     }
469     System.out.println("************************************************************************");
470     jsonObj =
471         "{\"processId\":\"{http://ode/bpel/unit-test}HelloXslWorld-3\",\"params\": {\"helloXsl\":{\"TestPart\":{\"content\":\"AAA\"}}}}";
472     process = new BpsProcess();
473     try {
474       Map<String, Object> resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null);
475       System.out.println(JsonUtil.bean2Json(resultMap));
476     } catch (JsonProcessingException e) {
477       e.printStackTrace();
478     } catch (IOException e) {
479       e.printStackTrace();
480     }
481     System.out.println("************************************************************************");
482     jsonObj =
483         "{\"processId\":\"{http://wso2.org/bps/samples/While}While-5\",\"params\": {\"WhileRequest\":{\"input\":\"365\"}}}";
484     process = new BpsProcess();
485     try {
486       Map<String, Object> resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null);
487       System.out.println(JsonUtil.bean2Json(resultMap));
488     } catch (JsonProcessingException e) {
489       e.printStackTrace();
490     } catch (IOException e) {
491     }
492
493   }
494
495   @SuppressWarnings("unchecked")
496   public static void main(String[] args) {
497
498     Map<String, Object> map = new LinkedHashMap<String, Object>();
499     String errorMessage = "unkown";
500
501     Map<String, Object> paramMap = new HashMap<String, Object>();
502     try {
503       String param =
504           "{\"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\\\"}}}]\"}}";
505       String jsonObj =
506           "{\"processId\":\"{http://wso2.org/bps/samples/While}While-5\",\"params\":" + param + "}";
507       paramMap = JsonUtil.json2Bean(jsonObj.toString(), Map.class);
508       Object params = paramMap.get("params");
509       String wsdlUrl = "http://10.74.151.36:9763/services/initService?wsdl";
510       String response = invokeWsdl(wsdlUrl, params);
511       map.put("status", STATUS_SUCCESS);
512       map.put("message", "success");
513       map.put("response", response);
514       System.out.println(JsonUtil.bean2Json(map));
515     } catch (JsonParseException e) {
516       errorMessage = e.getLocalizedMessage();
517       log.error(e.getMessage(), e);
518       e.printStackTrace();
519     } catch (JsonMappingException e) {
520       errorMessage = e.getLocalizedMessage();
521       log.error(e.getMessage(), e);
522       e.printStackTrace();
523     } catch (IOException e) {
524       errorMessage = e.getLocalizedMessage();
525       log.error(e.getMessage(), e);
526       e.printStackTrace();
527     } catch (Exception e) {
528       errorMessage = e.getLocalizedMessage();
529       log.error(e.getMessage(), e);
530       e.printStackTrace();
531     }
532
533     map.put("status", STATUS_FAIL);
534     map.put("message", errorMessage);
535     try {
536       System.out.println(JsonUtil.bean2Json(map));
537     } catch (IOException e) {
538       errorMessage = e.getLocalizedMessage();
539       log.error(e.getMessage(), e);
540       e.printStackTrace();
541     }
542
543   }
544 }