workaroud for snor issue
[vfc/nfvo/wfengine.git] / wso2bpel-ext / wso2bpel-core / wso2bpel-mgr / src / main / java / org / openo / carbon / bpel / resources / BpsPackage.java
1 /**
2  * Copyright 2016-2017 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.File;
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.activation.DataHandler;
32 import javax.activation.DataSource;
33 import javax.activation.FileDataSource;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpServletResponse;
36 import javax.ws.rs.QueryParam;
37 import javax.ws.rs.Consumes;
38 import javax.ws.rs.DELETE;
39 import javax.ws.rs.GET;
40 import javax.ws.rs.POST;
41 import javax.ws.rs.Path;
42 import javax.ws.rs.PathParam;
43 import javax.ws.rs.Produces;
44 import javax.ws.rs.client.Client;
45 import javax.ws.rs.client.ClientBuilder;
46 import javax.ws.rs.client.Entity;
47 import javax.ws.rs.client.WebTarget;
48 import javax.ws.rs.core.Context;
49 import javax.ws.rs.core.MediaType;
50 import javax.xml.namespace.QName;
51
52 import org.apache.axiom.om.OMAbstractFactory;
53 import org.apache.axiom.om.OMElement;
54 import org.apache.axiom.om.OMFactory;
55 import org.apache.axiom.om.OMNamespace;
56 import org.apache.axis2.AxisFault;
57 import org.apache.axis2.addressing.EndpointReference;
58 import org.apache.axis2.client.Options;
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.io.FileUtils;
64 import org.apache.commons.logging.Log;
65 import org.apache.commons.logging.LogFactory;
66 import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
67 import org.glassfish.jersey.media.multipart.FormDataMultiPart;
68 import org.glassfish.jersey.media.multipart.FormDataParam;
69 import org.glassfish.jersey.media.multipart.MultiPartFeature;
70 import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
71 import org.wso2.carbon.bpel.stub.upload.types.UploadedFileItem;
72 import org.openo.carbon.bpel.common.Config;
73 import org.openo.carbon.bpel.util.JsonUtil;
74 import org.openo.carbon.bpel.util.Xml2JsonUtil;
75
76 import com.codahale.metrics.annotation.Timed;
77 import com.fasterxml.jackson.core.JsonParseException;
78 import com.fasterxml.jackson.databind.JsonMappingException;
79
80 import io.swagger.annotations.Api;
81 import io.swagger.annotations.ApiOperation;
82
83 @Path("/")
84 @Api(tags = {"wso2 bpel api"})
85 public class BpsPackage {
86
87   private static final Log log = LogFactory.getLog(BpsPackage.class);
88
89   public static final int STATUS_SUCCESS = 1;
90   public static final int STATUS_FAIL = 0;
91   /**
92    * 无错误
93    */
94   public static final int ERROR_CODE_NOERROR = 0;
95   /**
96    * 不支持的文件类型
97    */
98   public static final int ERROR_CODE_PACKAGE_UNSUPPORED_FILE = 10001;
99   /**
100    * 同名的包正在操作中
101    */
102   public static final int ERROR_CODE_PACKAGE_STATUS_BUSY = 10002;
103   /**
104    * 包名重复
105    */
106   public static final int ERROR_CODE_PACKAGE_DUPLICATED_NAME = 10003;
107   /**
108    * 未获取到包部署的信息
109    */
110   public static final int ERROR_CODE_PACKAGE_DEPLOY_INFORMATION_IS_LOST = 10004;
111   /**
112    * 卸载包失败
113    */
114   public static final int ERROR_CODE_PACKAGE_UNDEPLOY_FAILED = 10005;
115   /**
116    * 包不存在
117    */
118   public static final int ERROR_CODE_PACKAGE_NOTEXISTS = 10006;
119   /**
120    * 服务运行时异常
121    */
122   public static final int ERROR_CODE_RUNTIME_EXCEPTION = 20001;
123   /**
124    * Axis运行时异常
125    */
126   public static final int ERROR_CODE_RUNTIME_EXCEPTION_AXIS = 20002;
127   /**
128    * IO运行时异常
129    */
130   public static final int ERROR_CODE_RUNTIME_EXCEPTION_IO = 20003;
131
132   public static Set<String> packageNameSet = new HashSet<String>();
133
134   private Map<String, String> configMap = null;
135
136   @SuppressWarnings("unused")
137   private final AtomicLong counter;
138
139   public BpsPackage() {
140     this.counter = new AtomicLong();
141   }
142
143   private synchronized String getConfig(String key) {
144     if (configMap == null) {
145       configMap = new HashMap<String, String>();
146       String uploadFilePath = Config.getConfigration().getWso2UploadFilePath();
147       String jksFile = Config.getConfigration().getWso2SslJksFile();
148       String trustStorePassword = Config.getConfigration().getWso2SslJksPassword();
149       String httpUsername = Config.getConfigration().getWso2AuthUserName();
150       String httpPassword = Config.getConfigration().getWso2AuthPassword();
151       String host = Config.getConfigration().getWso2Host();
152       String port = Config.getConfigration().getWso2HostPort();
153       configMap.put("uploadFilePath", uploadFilePath);
154       configMap.put("jksFile", jksFile);
155       configMap.put("trustStorePassword", trustStorePassword);
156       configMap.put("httpUsername", httpUsername);
157       configMap.put("httpPassword", httpPassword);
158       configMap.put("host", host);
159       configMap.put("port", port);
160     }
161     if (configMap.containsKey(key)) {
162       return configMap.get(key);
163     } else {
164       return "";
165     }
166   }
167
168   public static boolean lockPackageName(String packageName) {
169     boolean succeed = false;
170     synchronized (packageNameSet) {
171       if (!packageNameSet.contains(packageName)) {
172         packageNameSet.add(packageName);
173         succeed = true;
174       }
175     }
176     return succeed;
177   }
178
179   public static boolean unlockPackageName(String packageName) {
180     boolean succeed = false;
181     synchronized (packageNameSet) {
182       if (packageNameSet.contains(packageName)) {
183         packageNameSet.remove(packageName);
184         succeed = true;
185       }
186     }
187     return succeed;
188   }
189
190   @POST
191   @Path(value = "package")
192   @Consumes(MediaType.MULTIPART_FORM_DATA)
193   @Produces(value = MediaType.APPLICATION_JSON)
194   @ApiOperation(value = "package process", response = Map.class)
195   @Timed
196   public Map<String, Object> uploadFile(@FormDataParam("filename") String filename,
197       @FormDataParam("file") InputStream fileInputStream,
198       @FormDataParam("file") FormDataContentDisposition fileDetail,
199       @Context HttpServletRequest request, @Context HttpServletResponse response)
200           throws IOException {
201     Map<String, Object> map = new LinkedHashMap<String, Object>();
202     String errorMessage = "unkown";
203     int errorCode = ERROR_CODE_NOERROR;
204
205     String fileName = fileDetail.getFileName();
206     String fullName = getConfig("uploadFilePath") + "/" + fileName;
207     File file = new File(fullName);
208     String packageName = null;
209     try {
210       if (fileName.endsWith(".zip")) {
211         packageName = fileName.substring(0, fileName.length() - 4);
212       } else {
213           errorCode = ERROR_CODE_PACKAGE_UNSUPPORED_FILE;
214         throw new Exception("Only support *.zip file.");
215       }
216       if (!lockPackageName(packageName)) {
217           errorCode = ERROR_CODE_PACKAGE_STATUS_BUSY;
218         throw new Exception("Package " + packageName + " is operating.");
219       }
220       FileUtils.copyInputStreamToFile(fileInputStream, file);
221       System.setProperty("javax.net.ssl.trustStore", "*.keystore");
222       System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
223       System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile"));
224       System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword"));
225
226       HttpTransportProperties.Authenticator authenticator =
227           new HttpTransportProperties.Authenticator();
228       List<String> auth = new ArrayList<String>();
229       auth.add(Authenticator.BASIC);
230       authenticator.setAuthSchemes(auth);
231       authenticator.setUsername(getConfig("httpUsername"));
232       authenticator.setPassword(getConfig("httpPassword"));
233       authenticator.setPreemptiveAuthentication(true);
234
235       map.putAll(bpsDeployPackage(fileName, fullName, packageName, authenticator));
236       map.put("status", STATUS_SUCCESS);
237       map.put("message", "success");
238       return map;
239     } catch (AxisFault e) {
240       errorMessage = e.getLocalizedMessage();
241       errorCode = ERROR_CODE_RUNTIME_EXCEPTION_AXIS;
242       log.error(e.getMessage(), e);
243       e.printStackTrace();
244     } catch (IOException e) {
245       errorMessage = e.getLocalizedMessage();
246       errorCode = ERROR_CODE_RUNTIME_EXCEPTION_IO;
247       log.error(e.getMessage(), e);
248       e.printStackTrace();
249     } catch (Throwable e) {
250       errorMessage = e.getLocalizedMessage();
251                 if (e instanceof BpsServiceException) {
252                         errorCode = ((BpsServiceException) e).getErrorCode();
253                 } else {
254                         errorCode = ERROR_CODE_RUNTIME_EXCEPTION;
255                 }
256       log.error(e.getMessage(), e);
257       e.printStackTrace();
258     } finally {
259       if (packageName != null) {
260         unlockPackageName(packageName);
261       }
262     }
263     map.put("errorCode", errorCode);
264     map.put("status", STATUS_FAIL);
265     map.put("message", errorMessage);
266     return map;
267   }
268
269   @SuppressWarnings("rawtypes")
270   private Map<String, Object> bpsDeployPackage(String fileName, String fullName, String packageName,
271       HttpTransportProperties.Authenticator authenticator)
272           throws JsonParseException, JsonMappingException, IOException, AxisFault, Exception {
273     Map<String, Object> map = new HashMap<String, Object>();
274     Map deployedPackageInfoMap = getDeployedPackageInfo(authenticator, packageName, "");
275     if (deployedPackageInfoMap.get("packageName") != null) {
276       throw new BpsServiceException(ERROR_CODE_PACKAGE_DUPLICATED_NAME,"Package " + deployedPackageInfoMap.get("packageName")
277           + " exist, please undeploy it first.");
278     }
279     OMElement element = deployPackage(fileName, fullName, authenticator);
280     System.out.println(Xml2JsonUtil.xml2JSON(element.toString()));
281
282     long timeout = 60 * 1000L;
283     long timeStart = System.currentTimeMillis();
284     while (System.currentTimeMillis() - timeStart < timeout) {
285       deployedPackageInfoMap = getDeployedPackageInfo(authenticator, packageName, "");
286       if (deployedPackageInfoMap.get("packageName") == null) {
287         Thread.sleep(2000);
288       } else {
289         break;
290       }
291     }
292     if (deployedPackageInfoMap.get("packageName") == null) {
293       throw new BpsServiceException(ERROR_CODE_PACKAGE_DEPLOY_INFORMATION_IS_LOST,
294           "Package " + packageName + " deploy failed or deploy information is lost.");
295     }
296     map.put("packageName", deployedPackageInfoMap.get("packageName"));
297     map.put("processId", deployedPackageInfoMap.get("pid"));
298     return map;
299   }
300
301   private OMElement deployPackage(String fileName, String fullName,
302       HttpTransportProperties.Authenticator authenticator) throws AxisFault {
303     String url =
304         "https://" + getConfig("host") + ":" + getConfig("port") + "/services/BPELUploader?wsdl";
305     RPCServiceClient serviceClient = new RPCServiceClient();
306     EndpointReference targetEPR = new EndpointReference(url);
307     Options options = serviceClient.getOptions();
308     options.setTo(targetEPR);
309     options.setAction("urn:uploadService");
310     options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(300000));
311     options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
312     serviceClient.setOptions(options);
313
314     QName qname = new QName("http://services.deployer.bpel.carbon.wso2.org", "uploadService");
315     UploadedFileItem fileItem = new UploadedFileItem();
316     fileItem.setFileName(fileName);
317     fileItem.setFileType("zip");
318
319     DataSource dataSource = new FileDataSource(fullName);
320     fileItem.setDataHandler(new DataHandler(dataSource));
321     UploadedFileItem[] parameters = new UploadedFileItem[] {fileItem};
322     OMElement element = serviceClient.invokeBlocking(qname, parameters);
323     return element;
324   }
325
326   @Path(value = "package/{packageName}")
327   @DELETE
328   @Produces(value = MediaType.APPLICATION_JSON)
329   @ApiOperation(value = "delete", response = Map.class)
330   @Timed
331   public Map<String, Object> delete(@PathParam("packageName") String packageName,
332       @Context HttpServletRequest request) {
333     Map<String, Object> map = new LinkedHashMap<String, Object>();
334     String errorMessage = "unkown";
335     int errorCode = ERROR_CODE_NOERROR;
336     try {
337       if (!lockPackageName(packageName)) {
338         throw new Exception("Package " + packageName + " is operating.");
339       }
340       System.setProperty("javax.net.ssl.trustStore", "*.keystore");
341       System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
342       System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile"));
343       System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword"));
344
345       HttpTransportProperties.Authenticator authenticator =
346           new HttpTransportProperties.Authenticator();
347       List<String> auth = new ArrayList<String>();
348       auth.add(Authenticator.BASIC);
349       authenticator.setAuthSchemes(auth);
350       authenticator.setUsername(getConfig("httpUsername"));
351       authenticator.setPassword(getConfig("httpPassword"));
352       authenticator.setPreemptiveAuthentication(true);
353
354       map.putAll(bpsUndeployPackage(packageName, authenticator));
355
356       return map;
357     } catch (AxisFault e) {
358       errorMessage = e.getLocalizedMessage();
359       errorCode = ERROR_CODE_RUNTIME_EXCEPTION_AXIS;
360       log.error(e.getMessage(), e);
361       e.printStackTrace();
362     } catch (Throwable e) {
363       errorMessage = e.getLocalizedMessage();
364                 if (e instanceof BpsServiceException) {
365                         errorCode = ((BpsServiceException) e).getErrorCode();
366                 } else {
367                         errorCode = ERROR_CODE_RUNTIME_EXCEPTION;
368                 }
369       log.error(e.getMessage(), e);
370       e.printStackTrace();
371     } finally {
372       if (packageName != null) {
373         unlockPackageName(packageName);
374       }
375     }
376     map.put("errorCode", errorCode);
377     map.put("status", STATUS_FAIL);
378     map.put("message", errorMessage);
379     return map;
380   }
381
382   @SuppressWarnings({"rawtypes", "unused"})
383   private Map<String, Object> bpsUndeployPackage(String packageName,
384       HttpTransportProperties.Authenticator authenticator)
385           throws JsonParseException, JsonMappingException, IOException, AxisFault, Exception {
386     Map<String, Object> map = new HashMap<String, Object>();
387     Map deployedPackageInfoMap = getDeployedPackageInfo(authenticator, packageName, "");
388     if (deployedPackageInfoMap.get("packageName") == null) {
389       throw new BpsServiceException(ERROR_CODE_PACKAGE_NOTEXISTS,"Package " + deployedPackageInfoMap.get("packageName")
390           + " does not exist, please deploy it first.");
391     }
392     OMElement element = undeployPackage(authenticator, packageName);
393     deployedPackageInfoMap = getDeployedPackageInfo(authenticator, packageName, "");
394     if (deployedPackageInfoMap.get("packageName") != null) {
395       throw new BpsServiceException(ERROR_CODE_PACKAGE_UNDEPLOY_FAILED,
396           "Package " + deployedPackageInfoMap.get("packageName") + " undeploy failed.");
397     }
398     map.put("status", STATUS_SUCCESS);
399     map.put("message", "success");
400
401     return map;
402   }
403
404   private OMElement undeployPackage(HttpTransportProperties.Authenticator authenticator,
405       String packageName) throws AxisFault {
406     String url = "https://" + getConfig("host") + ":" + getConfig("port")
407         + "/services/BPELPackageManagementService?wsdl";
408     RPCServiceClient serviceClient = new RPCServiceClient();
409     EndpointReference targetEPR = new EndpointReference(url);
410     Options options = serviceClient.getOptions();
411     options.setTo(targetEPR);
412     options.setAction("sch:undeployBPELPackage");
413     options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(300000));
414     options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
415     serviceClient.setOptions(options);
416     OMFactory fac = OMAbstractFactory.getOMFactory();
417     OMNamespace omNs = fac.createOMNamespace("http://wso2.org/bps/management/schema", "sch");
418     OMElement method = fac.createOMElement("undeployBPELPackage", omNs);
419     OMElement content = fac.createOMElement("package", omNs);
420     content.addChild(fac.createOMText(content, packageName));
421     method.addChild(content);
422     method.build();
423     OMElement res = serviceClient.sendReceive(method);
424     return res;
425   }
426   
427   @SuppressWarnings({"rawtypes", "unchecked"})
428   private Map getFullDeployedPackageInfo(HttpTransportProperties.Authenticator authenticator,
429               String packageName, String page) throws Exception {
430             String result;
431             String jsonTemplate =
432                 "{'listDeployedPackagesPaginated':{'page':'${page}','packageSearchString':'${searchString}'}}";
433             Map jsonParamMap = new HashMap();
434             jsonParamMap.put("page", page);
435             jsonParamMap.put("searchString", packageName);
436             Object params = getParams(jsonTemplate, jsonParamMap);
437             result = BpsProcess.invokeWsdl("https://" + getConfig("host") + ":" + getConfig("port")
438                 + "/services/BPELPackageManagementService?wsdl", params, authenticator);
439             Map<String, Object> processMap = JsonUtil.json2Bean(result, Map.class);
440             return processMap;
441           }
442
443   @SuppressWarnings({"rawtypes", "unchecked"})
444   private Map getDeployedPackageInfo(HttpTransportProperties.Authenticator authenticator,
445               String packageName, String page) throws Exception {
446             Map resultMap = new HashMap();
447             Map<String, Object> processMap = getFullDeployedPackageInfo(authenticator, packageName, page);
448             Object packages = ((Map) processMap.get("deployedPackagesPaginated")).get("package");
449             Map deployedPackage = null;
450             if (packages instanceof List) {
451               for (Iterator iter = ((List) packages).iterator(); iter.hasNext();) {
452                 Map packageMap = (Map) iter.next();
453                 String deployedPackageName = (String) packageMap.get("name");
454                 if (deployedPackageName.equals(packageName)) {
455                   deployedPackage = packageMap;
456                   break;
457                 }
458               }
459             } else if (packages instanceof Map) {
460               String deployedPackageName = (String) ((Map) packages).get("name");
461               if (deployedPackageName.equals(packageName)) {
462                 deployedPackage = (Map) packages;
463               }
464             }
465             if (deployedPackage != null) {
466               String fullPackageName = null;
467               String pid = null;
468               Object versions = ((Map) deployedPackage.get("versions")).get("version");
469               Map lastestVersion = null;
470               if (versions instanceof List) {
471                 for (Iterator iter = ((List) versions).iterator(); iter.hasNext();) {
472                   Map version = (Map) iter.next();
473                   if (version.get("isLatest").equals("true")) {
474                     lastestVersion = version;
475                   }
476                 }
477               } else if (versions instanceof Map) {
478                 lastestVersion = (Map) versions;
479               }
480               fullPackageName = (String) ((Map) ((Map) lastestVersion.get("processes")).get("process"))
481                   .get("packageName");
482               pid = (String) ((Map) ((Map) lastestVersion.get("processes")).get("process")).get("pid");
483               resultMap.put("packageName", fullPackageName);
484               resultMap.put("pid", pid);
485             }
486             return resultMap;
487 }
488
489
490   @SuppressWarnings({"rawtypes", "unchecked"})
491   public static Map<String, Object> getParams(String jsonTemplate, Map<String, Object> paramMap)
492       throws JsonParseException, JsonMappingException, IOException {
493     String json = jsonTemplate.replaceAll("'", "\"");
494                 for (Iterator iter = paramMap.keySet().iterator(); iter.hasNext();) {
495                         String key = (String) iter.next();
496                         String value = "";
497                         if (paramMap.get(key) != null) {
498                                 value = paramMap.get(key).toString().replaceAll("\"", "\\\\\"");
499                         }
500                         json = json.replaceAll("\\$\\{" + key + "\\}", value);
501                 }
502     return JsonUtil.json2Bean(json, Map.class);
503   }
504   
505   @GET
506   @Path(value = "listPackages")
507   @Produces(value = MediaType.APPLICATION_JSON)
508   @ApiOperation(value = "list packages", response = Map.class)
509   @Timed
510   public Map<String, Object> listPackages(@QueryParam("page") String page,
511               @QueryParam("searchString") String searchString, @Context HttpServletRequest request)
512           throws IOException {
513     Map<String, Object> map = new LinkedHashMap<String, Object>();
514     String errorMessage = "unkown";
515     int errorCode = ERROR_CODE_NOERROR;
516     String packageName = null;
517     try {
518       System.setProperty("javax.net.ssl.trustStore", "*.keystore");
519       System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
520       System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile"));
521       System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword"));
522
523       HttpTransportProperties.Authenticator authenticator =
524           new HttpTransportProperties.Authenticator();
525       List<String> auth = new ArrayList<String>();
526       auth.add(Authenticator.BASIC);
527       authenticator.setAuthSchemes(auth);
528       authenticator.setUsername(getConfig("httpUsername"));
529       authenticator.setPassword(getConfig("httpPassword"));
530       authenticator.setPreemptiveAuthentication(true);
531
532       map.putAll(getFullDeployedPackageInfo(authenticator,searchString,page));
533
534       map.put("status", STATUS_SUCCESS);
535       map.put("message", "success");
536       return map;
537     } catch (AxisFault e) {
538       errorMessage = e.getLocalizedMessage();
539       errorCode = ERROR_CODE_RUNTIME_EXCEPTION_AXIS;
540       log.error(e.getMessage(), e);
541       e.printStackTrace();
542     } catch (IOException e) {
543       errorMessage = e.getLocalizedMessage();
544       errorCode = ERROR_CODE_RUNTIME_EXCEPTION_IO;
545       log.error(e.getMessage(), e);
546       e.printStackTrace();
547     } catch (Throwable e) {
548                         if (e instanceof BpsServiceException) {
549                                 errorCode = ((BpsServiceException) e).getErrorCode();
550                         } else {
551                                 errorCode = ERROR_CODE_RUNTIME_EXCEPTION;
552                         }
553       errorMessage = e.getLocalizedMessage();
554       log.error(e.getMessage(), e);
555       e.printStackTrace();
556     } finally {
557       if (packageName != null) {
558         unlockPackageName(packageName);
559       }
560     }
561     map.put("errorCode", errorCode);
562     map.put("status", STATUS_FAIL);
563     map.put("message", errorMessage);
564     return map;
565   }
566
567   @SuppressWarnings("rawtypes")
568   public static void main(String[] args) {
569     try {
570
571       boolean remoteDebug = true;
572       boolean localDebug = false;
573       if (remoteDebug) {
574         Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
575         WebTarget target = client.target("http://localhost:8101/openoapi/wso2bpel/v1/package");
576         FileDataBodyPart bodyPart = new FileDataBodyPart("file",
577             new File("F:\\wso2bps-3.5.1\\wso2bps-3.5.1\\repository\\samples\\bpel\\Alarm.zip"));
578         FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
579         formDataMultiPart.field("fileName", "Alarm.zip").bodyPart(bodyPart);
580         String result = target.request(MediaType.APPLICATION_JSON)
581             .post(Entity.entity(formDataMultiPart, formDataMultiPart.getMediaType()), String.class);
582         System.out.println(result);
583       }
584       //
585       // System.out.println("************************************************************************");
586       //
587       // bodyPart = new FileDataBodyPart("file", new
588       // File("D:\\temp\\bpel-sample\\AssignDate\\AssignDate.zip"));
589       // formDataMultiPart = new FormDataMultiPart();
590       // formDataMultiPart.field("fileName",
591       // "AssignDate.zip").bodyPart(bodyPart);
592       // result = target.request(MediaType.APPLICATION_JSON)
593       // .post(Entity.entity(formDataMultiPart,
594       // formDataMultiPart.getMediaType()), String.class);
595       // System.out.println(result);
596       //
597       if (localDebug) {
598         System.setProperty("javax.net.ssl.trustStore", "*.keystore");
599         System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
600         System.setProperty("javax.net.ssl.trustStore",
601             "D:\\software\\WSO2\\wso2bps-3.5.1\\repository\\resources\\security\\wso2carbon.jks");
602         System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
603         HttpTransportProperties.Authenticator authenticator =
604             new HttpTransportProperties.Authenticator();
605         List<String> auth = new ArrayList<String>();
606         auth.add(Authenticator.BASIC);
607         authenticator.setAuthSchemes(auth);
608         authenticator.setUsername("admin");
609         authenticator.setPassword("admin");
610         authenticator.setPreemptiveAuthentication(true);
611         //
612         // String packageName = "RESTProcess";
613         // Map deployedPackageInfoMap =
614         // getDeployedPackageInfo(authenticator, packageName);
615
616         BpsPackage packageTest = new BpsPackage();
617         Map map;
618         // map = packageTest.bpsUndeployPackage("AssignDate",
619         // authenticator);
620         // System.out.println(JsonUtil.bean2Json(map));
621         map = packageTest.bpsDeployPackage("AssignDate.zip",
622             "D:\\temp\\bpel-sample\\AssignDate\\AssignDate.zip", "AssignDate", authenticator);
623         System.out.println(JsonUtil.bean2Json(map));
624         map = packageTest.bpsUndeployPackage("AssignDate", authenticator);
625         System.out.println(JsonUtil.bean2Json(map));
626       }
627
628     } catch (Exception e) {
629       e.printStackTrace();
630     }
631   }
632 }