zoukankan      html  css  js  c++  java
  • F2BPM 开发Api与RESTfull应用服务Api 层次关系及示例

    目前越来越多的企业架构解决方案更加趋向于基于http协议“微服务”访问跨系统调用,而不使用统传的WebService调用,即通过RESTfull方式进行交互,更加轻量整合调用更加方便。本文档中所有F2BPM开发接口API都可以发布成RESTfull对外应用服务接口

    RESTfull参数方式

    authorJson:主要是接口身份的认证相关参数,校验访问者的来源合法性

    parmJson:请求业务数据的参数,比如分页参数,查询参数等

    所有RESTfull都统一只有这两个Json参数  

    API开发接口与RestFull API服务发布代码示例

    SmartFormRESTfullApi 在线表单的RestFull API服务

    package com.f2bpm.controller.restfullapi;
    
    import java.util.List;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import net.sf.json.JSONObject;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    
    import com.f2bpm.base.core.entity.AuthorEntity;
    import com.f2bpm.base.core.entity.MyInteger;
    import com.f2bpm.base.core.entity.PageParams;
    import com.f2bpm.base.core.enums.ExtensionValidateType;
    import com.f2bpm.base.core.utils.AppUtil;
    import com.f2bpm.base.core.utils.ExtensionValidate;
    import com.f2bpm.base.core.utils.FileDownUtil;
    import com.f2bpm.base.core.utils.FileUtil;
    import com.f2bpm.base.core.utils.JsonHelper;
    import com.f2bpm.base.core.utils.string.StringUtil;
    import com.f2bpm.base.core.utils.time.DateUtil;
    import com.f2bpm.system.admin.impl.model.Users;
    import com.f2bpm.system.security.utils.LogUtil;
    import com.f2bpm.system.security.web.WebHelper;
    import com.f2bpm.workflow.engine.api.entity.WorkflowInstanceContext;
    import com.f2bpm.workflow.engine.api.model.TaskInstance;
    import com.f2bpm.workflow.engine.api.model.TaskInstanceInfo;
    import com.f2bpm.workflow.engine.api.model.WorkflowForm;
    import com.f2bpm.workflow.engine.api.wapi.IWorkflowWAPIService;
    import com.f2bpm.workflow.engine.helper.WfWebHelper;
    import com.f2bpm.workflow.org.api.imodel.IUser;
    import com.f2bpm.workflow.org.api.iservice.IUserService;
    import com.f2bpm.workflow.smartForm.api.entity.BusObjectData;
    
    /*
     * 在线表单RestFull API服务接口
     */
    @Controller
    @RequestMapping("/restfullapi/smartForm/")
    public class SmartFormRESTfullApi {
        @Resource
        IUserService userService;
        public IWorkflowWAPIService WorkflowAPI = (IWorkflowWAPIService) AppUtil.getBean("WorkflowAPI");
    
        /**
         * 获取在线表单数据
         * 
         * @param parmJson
         * @param authorJson
         * @param response
         */
        @RequestMapping(value = "getOnlineFormData", method = RequestMethod.POST)
        public void getOnlineFormData(String parmJson, String authorJson, HttpServletResponse response) {
            String jsonResult = "";
            try {
                JSONObject jsonJSONObject = JSONObject.fromObject(parmJson);
                AuthorEntity authorEntity = JsonHelper.jsonToObject(authorJson, AuthorEntity.class);
                String loginAccount = authorEntity.getLoginAccount();
                // 流程实例ID
                String wiid = JsonHelper.getString(jsonJSONObject, "wiid");
                // 表单业务键
                String businessKey = JsonHelper.getString(jsonJSONObject, "businessKey");
                List<BusObjectData> data = WorkflowAPI.getSmartFormApiManager().getBusObjectListData(wiid, businessKey);
                jsonResult = JsonHelper.objectToJSON(data);
            } catch (Exception ex) {
                jsonResult = JsonHelper.outResult(false, ex.toString());
            }
            JsonHelper.write(response, jsonResult);
        }
    
        /**
         * 获取表单应用定义
         * 
         * @param parmJson
         * @param authorJson
         * @param response
         */
        @RequestMapping(value = "getWorkflowForm", method = RequestMethod.POST)
        public void getWorkflowForm(String parmJson, String authorJson, HttpServletResponse response) {
            String jsonResult = "";
            try {
                JSONObject jsonJSONObject = JSONObject.fromObject(parmJson);
                AuthorEntity authorEntity = JsonHelper.jsonToObject(authorJson, AuthorEntity.class);
                String loginAccount = authorEntity.getLoginAccount();
                String wid = JsonHelper.getString(jsonJSONObject, "wid");
                String appId = JsonHelper.getString(jsonJSONObject, "appId");
                WorkflowForm form = null;
                if (StringUtil.isEmpty(wid)) {
                    // 启动时
                    form = WorkflowAPI.getProcessDefManager().getWorkflowInfo(appId).getWorkflowFormRunned();
                } else {
                    // 运行时
                    form = WorkflowAPI.getProcessDefManager().getWorkflowInfo(wid, appId).getWorkflowFormRunned();
    
                }
                jsonResult = JsonHelper.objectToJSON(form);
            } catch (Exception ex) {
                jsonResult = JsonHelper.outResult(false, ex.toString());
            }
            JsonHelper.write(response, jsonResult);
        }
    
        /**
         * 获取表单手机端Html模板
         * 
         * @param parmJson wid:启动时可为空
         * @param authorJson
         * @param response
         */
        @RequestMapping(value = "getWorkflowFormMobileHtml", method = RequestMethod.POST)
        public void getWorkflowFormMobileHtml(String parmJson, String authorJson, HttpServletResponse response) {
            String jsonResult = "";
            try {
                JSONObject jsonJSONObject = JSONObject.fromObject(parmJson);
                AuthorEntity authorEntity = JsonHelper.jsonToObject(authorJson, AuthorEntity.class);
                String loginAccount = authorEntity.getLoginAccount();
                String wid = JsonHelper.getString(jsonJSONObject, "wid");//启用时可为空
                String appId = JsonHelper.getString(jsonJSONObject, "appId");
                String html= null;
                if (StringUtil.isEmpty(wid)) {
                    // 启动时
                    html = WorkflowAPI.getProcessDefManager().getWorkflowInfo(appId).getWorkflowFormRunned().getMobileTemplateContent();
                } else {
                    // 运行时
                    html = WorkflowAPI.getProcessDefManager().getWorkflowInfo(wid, appId).getWorkflowFormRunned().getMobileTemplateContent();
    
                }
                jsonResult = html;
            } catch (Exception ex) {
                jsonResult = JsonHelper.outResult(false, ex.toString());
            }
            JsonHelper.write(response, jsonResult);
        }
    }

    WorkflowBusinessRESTfullApi 流程运行相关的服务接口

      1 package com.f2bpm.controller.restfullapi;
      2 
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.IOException;
      6 import java.io.InputStream;
      7 import java.io.OutputStream;
      8 import java.util.List;
      9 
     10 import javax.annotation.Resource;
     11 import javax.servlet.http.HttpServletRequest;
     12 import javax.servlet.http.HttpServletResponse;
     13 
     14 import net.sf.json.JSONObject;
     15 
     16 import org.springframework.stereotype.Controller;
     17 import org.springframework.web.bind.annotation.RequestMapping;
     18 import org.springframework.web.bind.annotation.RequestMethod;
     19 import org.springframework.web.bind.annotation.ResponseBody;
     20 import org.springframework.web.multipart.MultipartFile;
     21 import org.springframework.web.multipart.MultipartHttpServletRequest;
     22 
     23 import com.f2bpm.base.core.entity.AuthorEntity;
     24 import com.f2bpm.base.core.entity.MyInteger;
     25 import com.f2bpm.base.core.entity.PageParams;
     26 import com.f2bpm.base.core.enums.ExtensionValidateType;
     27 import com.f2bpm.base.core.utils.AppUtil;
     28 import com.f2bpm.base.core.utils.ExtensionValidate;
     29 import com.f2bpm.base.core.utils.FileDownUtil;
     30 import com.f2bpm.base.core.utils.FileUtil;
     31 import com.f2bpm.base.core.utils.JsonHelper;
     32 import com.f2bpm.base.core.utils.string.StringUtil;
     33 import com.f2bpm.base.core.utils.time.DateUtil;
     34 import com.f2bpm.system.admin.impl.model.Users;
     35 import com.f2bpm.system.security.utils.LogUtil;
     36 import com.f2bpm.system.security.web.WebHelper;
     37 import com.f2bpm.workflow.engine.api.entity.WorkflowInstanceContext;
     38 import com.f2bpm.workflow.engine.api.model.ActivityInfo;
     39 import com.f2bpm.workflow.engine.api.model.TaskInstance;
     40 import com.f2bpm.workflow.engine.api.model.TaskInstanceInfo;
     41 import com.f2bpm.workflow.engine.api.wapi.IWorkflowWAPIService;
     42 import com.f2bpm.workflow.engine.helper.WfWebHelper;
     43 import com.f2bpm.workflow.org.api.imodel.IUser;
     44 import com.f2bpm.workflow.org.api.iservice.IUserService;
     45 /*
     46  * 流程运行相关 RestFull API服务接口
     47  */
     48 @Controller
     49 @RequestMapping("/restfullapi/workflowBusiness/")
     50 public class WorkflowBusinessRESTfullApi {
     51     @Resource
     52     IUserService userService;
     53 
     54     public IWorkflowWAPIService WorkflowAPI = (IWorkflowWAPIService) AppUtil.getBean("WorkflowAPI");
     55 
     56     /**
     57      * 查找任务实例
     58      * @param id
     59      * @param request
     60      * @param response
     61      * @return
     62      * @throws IOException
     63      */
     64     @ResponseBody
     65     @RequestMapping(value = "getTask", method = RequestMethod.GET)
     66     public TaskInstance getTask(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
     67         TaskInstance task = new TaskInstance();
     68         id = "031d2404-94d1-4566-8ade-21126b620904";
     69         task = WorkflowAPI.getWorkTaskManager().getTaskInstanceByTaskId(id);
     70         return task;
     71     }
     72 
     73     /**
     74      *  获取待办列表
     75      * @param authorJson
     76      * @param parmJson
     77      * @param request
     78      * @param response
     79      * @throws Exception
     80      */
     81     @RequestMapping(value = "getTodoList", method = RequestMethod.GET)
     82     public void getTodoList(String authorJson, String parmJson, HttpServletRequest request, HttpServletResponse response) throws Exception {
     83         JSONObject jsonJSONObject = JSONObject.fromObject(parmJson);
     84         PageParams pageParams = JsonHelper.jsonToObject(parmJson, PageParams.class);
     85         AuthorEntity authorEntity = JsonHelper.jsonToObject(authorJson, AuthorEntity.class);
     86         String loginAccount = authorEntity.getLoginAccount();
     87         MyInteger recordCount = new MyInteger(0);
     88         MyInteger pageCount = new MyInteger(0);
     89         String whereStr = JsonHelper.getString(jsonJSONObject, "whereStr");
     90         IUser user = userService.getUserByAccount(loginAccount);
     91         List<TaskInstanceInfo> list = WorkflowAPI.getWorkTaskManager().getTodoList(user.getUserId(), whereStr.toString(), pageParams.getOrderBy(), pageParams.getPageIndex(), pageParams.getPageSize(), pageCount, recordCount, true);
     92         String jsonString = JsonHelper.listToJSON(list);
     93         String jsonResult = JsonHelper.convertToEasyUIJsonResult(jsonString, pageParams.getPageSize(), pageParams.getPageIndex(), recordCount.getValue(), pageCount.getValue());
     94         JsonHelper.write(response, jsonResult);
     95     }
     96 
     97     /**
     98      *  已办列表
     99      * @param authorJson
    100      * @param parmJson
    101      * @param request
    102      * @param response
    103      * @throws Exception
    104      */
    105     @RequestMapping(value = "getDoneList", method = RequestMethod.POST)
    106     public void getDoneList(String authorJson, String parmJson, HttpServletRequest request, HttpServletResponse response) throws Exception {
    107         JSONObject jsonJSONObject = JSONObject.fromObject(parmJson);
    108         PageParams pageParams = JsonHelper.jsonToObject(parmJson, PageParams.class);
    109         AuthorEntity authorEntity = JsonHelper.jsonToObject(authorJson, AuthorEntity.class);
    110         String loginAccount = authorEntity.getLoginAccount();
    111         MyInteger recordCount = new MyInteger(0);
    112         MyInteger pageCount = new MyInteger(0);
    113         String whereStr = JsonHelper.getString(jsonJSONObject, "whereStr");
    114         int isHistory = JsonHelper.getInt(jsonJSONObject, "isHistory");
    115         IUser user = userService.getUserByAccount(loginAccount);
    116         List<TaskInstanceInfo> list = null;
    117         if (isHistory == 1) {
    118             // 归档中的列表
    119             list = WorkflowAPI.getHistoryDataManager().getHistoryDoneList(user.getUserId(), whereStr.toString(), pageParams.getOrderBy(), pageParams.getPageIndex(), pageParams.getPageSize(), pageCount, recordCount, true);
    120         } else {
    121             // 进行中的已办
    122             list = WorkflowAPI.getWorkTaskManager().getDoneList(user.getUserId(), whereStr.toString(), pageParams.getOrderBy(), pageParams.getPageIndex(), pageParams.getPageSize(), pageCount, recordCount, true);
    123         }
    124 
    125         String jsonString = JsonHelper.listToJSON(list);
    126         String jsonResult = JsonHelper.convertToEasyUIJsonResult(jsonString, pageParams.getPageSize(), pageParams.getPageIndex(), recordCount.getValue(), pageCount.getValue());
    127         JsonHelper.write(response, jsonResult);
    128     }
    129 
    130     /**
    131      * 响应发起流程
    132      * @param authorJson
    133      * @param parmJson
    134      * @param request
    135      * @param response
    136      * @throws IOException
    137      */
    138     @RequestMapping(value = "startWorkflow", method = RequestMethod.POST)
    139     public void startWorkflow(String authorJson, String parmJson, HttpServletRequest request, HttpServletResponse response) throws IOException {
    140         JSONObject jsonJSONObject = JSONObject.fromObject(parmJson);
    141         AuthorEntity authorEntity = JsonHelper.jsonToObject(authorJson, AuthorEntity.class);
    142         String loginAccount = authorEntity.getLoginAccount();
    143         // IUser user = userService.getUserByAccount(loginAccount);
    144         String appId = JsonHelper.getString(jsonJSONObject, "appId");
    145         String wiid = JsonHelper.getString(jsonJSONObject, "wiid");
    146         String businessKey = JsonHelper.getString(jsonJSONObject, "businessKey");
    147         String title = JsonHelper.getString(jsonJSONObject, "title");
    148         String opinion = JsonHelper.getString(jsonJSONObject, "opinion");
    149         String jsonFormData = JsonHelper.getString(jsonJSONObject, "jsonFormData");
    150         StringBuilder message = new StringBuilder();
    151         boolean success = WorkflowAPI.getWorkflowEnactmentManager().startWorkflow(appId, wiid, businessKey, title, opinion, loginAccount, null, message, jsonFormData, null, 0, 0);
    152         String jsonResult = JsonHelper.outResult(success, message.toString());
    153         JsonHelper.write(response, jsonResult);
    154     }
    155 
    156     /**
    157      *  驳回流程
    158      * @param parmJson
    159      * @param authorJson
    160      * @param response
    161      */
    162     @RequestMapping(value = "rejectFlow", method = RequestMethod.POST)
    163     public void rejectFlow(String parmJson, String authorJson, HttpServletResponse response) {
    164         JSONObject jsonJSONObject = JSONObject.fromObject(parmJson);
    165         AuthorEntity authorEntity = JsonHelper.jsonToObject(authorJson, AuthorEntity.class);
    166         String loginAccount = authorEntity.getLoginAccount();
    167         String taskId = JsonHelper.getString(jsonJSONObject, "taskId");
    168         String opinion = JsonHelper.getString(jsonJSONObject, "opinion");
    169         StringBuilder message = new StringBuilder();
    170         boolean success = WorkflowAPI.getWorkflowEnactmentManager().rejectWorkflow(taskId, loginAccount, opinion, true, null, message);
    171         String jsonResult = JsonHelper.outResult(success, message.toString());
    172         JsonHelper.write(response, jsonResult);
    173     }
    174 
    175     /**
    176      * 作废流程实例
    177      * 
    178      * @param parmJson
    179      * @param authorJson
    180      * @param response
    181      */
    182     @RequestMapping(value = "invalidFlow", method = RequestMethod.POST)
    183     public void invalidFlow(String parmJson, String authorJson, HttpServletResponse response) {
    184         JSONObject jsonJSONObject = JSONObject.fromObject(parmJson);
    185         AuthorEntity authorEntity = JsonHelper.jsonToObject(authorJson, AuthorEntity.class);
    186         String loginAccount = authorEntity.getLoginAccount();
    187         String taskId = JsonHelper.getString(jsonJSONObject, "taskId");
    188         String opinion = JsonHelper.getString(jsonJSONObject, "opinion");
    189         TaskInstance taskInstance = WorkflowAPI.getWorkTaskManager().getTaskInstanceByTaskId(taskId);
    190         String wiid = taskInstance.getWorkflowInstanceId();
    191         StringBuilder message = new StringBuilder();
    192         IUser user = WorkflowAPI.getOrgEngineManager().getUserService().getUserByAccount(loginAccount);
    193         boolean success = WorkflowAPI.getWorkflowEnactmentManager().invalidWorkflowInstance(wiid, opinion, user);
    194         String jsonResult = JsonHelper.outResult(success, message.toString());
    195         JsonHelper.write(response, jsonResult);
    196     }
    197 
    198 
    199     
    200     /**
    201      * 审批执行代办任务
    202      * @param authorJson
    203      * @param parmJson
    204      * @param response
    205      */
    206     @RequestMapping(value = "approvalTask", method = RequestMethod.POST)
    207     public void approvalTask(String authorJson, String parmJson, HttpServletResponse response) {
    208         JSONObject jsonJSONObject = JSONObject.fromObject(parmJson);
    209         AuthorEntity authorEntity = JsonHelper.jsonToObject(authorJson, AuthorEntity.class);
    210         String loginAccount = authorEntity.getLoginAccount();
    211         String taskId = JsonHelper.getString(jsonJSONObject, "taskId");
    212         String opinion = JsonHelper.getString(jsonJSONObject, "opinion");
    213         StringBuilder message = new StringBuilder();
    214         boolean success = WorkflowAPI.getWorkflowEnactmentManager().sendWorkflowByTaskId(taskId, loginAccount, opinion, message);
    215         String jsonResult = JsonHelper.outResult(success, message.toString());
    216         JsonHelper.write(response, jsonResult);
    217     }
    218 
    219     /**
    220      * 获取任务指定节点的供选择人(计算出节点参与者)
    221      * @param authorJson
    222      * @param parmJson
    223      * @param response
    224      */
    225     @RequestMapping(value = "getActivityUsers", method = RequestMethod.POST)
    226     public void getActivityUsers(String authorJson, String parmJson, HttpServletResponse response) {
    227         JSONObject jsonJSONObject = JSONObject.fromObject(parmJson);
    228         AuthorEntity authorEntity = JsonHelper.jsonToObject(authorJson, AuthorEntity.class);
    229         String loginAccount = authorEntity.getLoginAccount();
    230         String taskId = JsonHelper.getString(jsonJSONObject, "taskId");
    231         String activityId = JsonHelper.getString(jsonJSONObject, "activityId");
    232         StringBuilder message = new StringBuilder();
    233         WorkflowInstanceContext wfContext=WorkflowAPI.getWorkflowEnactmentManager().getWorkflowInstanceContextOnTodo(taskId, loginAccount);
    234         TaskInstance  task = WorkflowAPI.getWorkTaskManager().getTaskInstanceByTaskId(taskId);
    235         ActivityInfo activityInfo=WorkflowAPI.getProcessDefManager().getActivityInfo(task.getWorkflowId(), activityId);
    236         List<IUser> list= WorkflowAPI.getWorkflowEnactmentManager().getListActorUserResultByActivityInfo(wfContext,activityInfo);
    237         String jsonResult =JsonHelper.objectToJSON(list);
    238         JsonHelper.write(response, jsonResult);
    239     }
    240     
    241     /**
    242      * 上传在线表单附件 上传在线表单附件, 返回字段值单个附件值,表单附件的字段值格式:
    243      * [{filePathName:"/attachments/workflow/files/20170714215409547.txt"
    244      * ,fileName:"TestClient.txt"}]
    245      * 
    246      * @param request
    247      * @param response
    248      */
    249     @RequestMapping("uploadFile")
    250     public void uploadFile(HttpServletRequest request, HttpServletResponse response) {
    251         String jsonResult = "";
    252         MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
    253         MultipartFile fileUpload = mRequest.getFile("FileUpload");
    254         if (!fileUpload.isEmpty()) {
    255 
    256             try {
    257                 String uploadType = WfWebHelper.query("UploadType", "");
    258 
    259                 String path = FileDownUtil.getWorkflowFilePath();
    260                 String uploadFileName = fileUpload.getOriginalFilename();
    261                 String fileExtension = uploadFileName.substring(uploadFileName.lastIndexOf("."));
    262 
    263                 if (!StringUtil.isNullOrWhiteSpace(uploadType)) {
    264                     path = path + uploadType + "/";
    265                     if (!FileUtil.isExistDirectory(path)) {
    266                         FileUtil.createFolder(path);
    267                     }
    268                 }
    269 
    270                 if (!ExtensionValidate.validateExtension(fileExtension, ExtensionValidateType.FileExtension)) {
    271                     jsonResult = JsonHelper.outResult(false, fileExtension + ",文件类型不允许上传!");
    272                     JsonHelper.write(response, jsonResult);
    273                     return;
    274                 }
    275                 uploadFileName = DateUtil.getCurrentDateTime("yyyyMMddHHmmssSSS") + fileExtension;
    276                 String filePathName = path + uploadFileName;
    277                 if (FileUtil.isExistFile(filePathName)) {
    278                     FileUtil.deleteFile(filePathName);
    279                 }
    280                 File filePath = new File(filePathName);// 上传地址
    281                 fileUpload.transferTo(filePath);
    282 
    283                 int index = filePathName.indexOf("attachments");
    284                 String downfielNamePath = filePathName.substring(index);
    285                 jsonResult = JsonHelper.outResult(true, "{filePathName:"/" + downfielNamePath + "",fileName:"" + fileUpload.getOriginalFilename() + ""}");
    286 
    287             } catch (RuntimeException | IOException ex) {
    288                 jsonResult = JsonHelper.outResult(false, "上传失败");
    289                 LogUtil.writeLog(ex.toString());
    290             }
    291         } else {
    292             jsonResult = JsonHelper.outResult(false, "请选择要上传的文件");
    293         }
    294         JsonHelper.write(response, jsonResult);
    295     }
    296 
    297     /**
    298      * 附件下载
    299      * @param authorJson
    300      * @param parmJson
    301      * @param request
    302      * @param response
    303      */
    304     @RequestMapping("downloadFile")
    305     public void downloadFile(String authorJson, String parmJson, HttpServletRequest request, HttpServletResponse response) {
    306         try {
    307             JSONObject jsonJSONObject = JSONObject.fromObject(parmJson);
    308             AuthorEntity authorEntity = JsonHelper.jsonToObject(authorJson, AuthorEntity.class);
    309             // String fileName = JsonHelper.getString(jsonJSONObject,
    310             // "fileName");
    311             String filePath = JsonHelper.getString(jsonJSONObject, "filePath");
    312             String path = AppUtil.getWebRootPath() + filePath;
    313             String fileName = new String(path.getBytes("iso8859-1"), "UTF-8");
    314             File file = new File(fileName);
    315             if (!file.exists()) {
    316                 response.setStatus(404);
    317                 String jsonResult = JsonHelper.outResult(false, "404 file not found!");
    318                 JsonHelper.write(response, jsonResult);
    319                 return;
    320             }
    321             // response.setCharacterEncoding("utf-8");
    322             // response.setContentType("multipart/form-data");
    323             // response.setHeader("Content-Disposition", "attachment;fileName="
    324             // + fileName);
    325             InputStream inputStream = new FileInputStream(file);
    326             OutputStream os = response.getOutputStream();
    327             byte[] b = new byte[1024];
    328             int length;
    329             while ((length = inputStream.read(b)) > 0) {
    330                 os.write(b, 0, length);
    331             }
    332             inputStream.close();
    333         } catch (Exception ex) {
    334             LogUtil.writeLog(ex.toString());
    335             response.setStatus(500);
    336             ex.printStackTrace();
    337             String jsonResult = JsonHelper.outResult(false, "500 err "+ex.getMessage());
    338             JsonHelper.write(response, jsonResult);
    339         }
    340     }
    341 }

    客户端调用示例

      1 package com.f2bpm.restfullapi;
      2 
      3 import java.util.HashMap;
      4 import java.util.Map;
      5 
      6 import org.apache.http.client.HttpClient;
      7 import org.apache.http.client.methods.HttpPost;
      8 import org.apache.http.impl.client.DefaultHttpClient;
      9 
     10 import com.f2bpm.base.core.utils.Guid;
     11 import com.f2bpm.base.core.utils.HttpClientUtil;
     12 import com.f2bpm.base.core.utils.string.StringUtil;
     13 
     14 public class WorkflowBusinessTestClient {
     15 
     16     String webApiUrl = "http://localhost:8081/f2bpm/restfullapi";
     17     
     18     /**
     19      * get请求 get只适合参数相对简单的请求,如果参数过长或参数字符复杂,则使用Post 来传参请求
     20      * 这里仅是一个get示例,不建议使用get统一使用Post来做 不建议使用get统一使用Post来做 不建议使用get统一使用Post来做
     21      * 不建议使用get统一使用Post来做
     22      */
     23     public void getTask() {
     24         String url = webApiUrl + "/workflowBusiness/getTask?";
     25         String queryString="id=123";
     26         String param = HttpClientUtil.urlEncode(queryString.toString()); // 特殊字符进行转义
     27         url = url + param;
     28         String jsonRes = HttpClientUtil.get(url);
     29         System.out.println(jsonRes);
     30     }
     31 
     32 
     33 //    public void getTodoList() {
     34 //        String urlString = webApiUrl + "/workflowBusiness/getTodoList/?";
     35 //        StringBuilder queryString = new StringBuilder();
     36 //        queryString.append(StringUtil.format("authorJson={loginAccount:"{0}"}", "admin"));
     37 //        queryString.append(StringUtil.format("&parmJson={pageIndex:{0},pageSize:{1},sort:"{2}",order:"{3}"}", 1, 2, "CreatedTime", "desc"));
     38 //        String param = HttpClientUtil.urlEncode(queryString.toString()); // 特殊字符进行转义
     39 //        urlString = urlString + param;
     40 //        String jsonRes = HttpClientUtil.get(urlString);
     41 //        System.out.println(jsonRes);
     42 //    }
     43     
     44     /**
     45      * 获取待办列表
     46      */
     47     public void getTodoList() {
     48         String  url= webApiUrl + "/workflowBusiness/getTodoList/";
     49         Map<String, String> params = new HashMap<String, String>();
     50         StringBuilder queryString = new StringBuilder();
     51         params.put("authorJson", StringUtil.format("{loginAccount:"{0}"}", "admin"));
     52         params.put("parmJson", StringUtil.format("{pageIndex:{0},pageSize:{1},sort:"{2}",order:"{3}",whereStr:"{4}",}", 1, 2, "CreatedTime", "desc", ""));
     53         String jsonRes = HttpClientUtil.post(url, params);
     54         System.out.println(jsonRes);
     55     }
     56     /**
     57      * 获取已办列表
     58      */
     59     public void getDoneList() {
     60         String urlString = webApiUrl + "/workflowBusiness/getDoneList/";
     61         Map<String, String> params = new HashMap<String, String>();
     62         StringBuilder queryString = new StringBuilder();
     63         params.put("authorJson", StringUtil.format("{loginAccount:"{0}"}", "admin"));
     64         // isHistory:0 进行中的已办,isHistory:1流程已结束并归档的已办
     65         params.put("parmJson", StringUtil.format("{isHistory:0,pageIndex:{0},pageSize:{1},sort:"{2}",order:"{3}",whereStr:"{4}",}", 1, 2, "CreatedTime", "desc", ""));
     66         String jsonRes = HttpClientUtil.post(urlString, params);
     67         System.out.println(jsonRes);
     68     }
     69 
     70     /**
     71      * 发起流程
     72      */
     73     public void startWorkflow() {
     74         String urlString = webApiUrl + "/workflowBusiness/startWorkflow/";
     75         Map<String, String> params = new HashMap<String, String>();
     76         String onlineFormData = StringUtil.format("[{"mainTable":"csb","data":[{"name":"csb.nl","value":"22"},{"name":"csb.MyId","value":""},{"name":"csb.zz","value":"RestFull测试"},{"name":"csb.xm","value":"RestFull姓名"}],"subTables":[]}]");
     77         params.put("authorJson", StringUtil.format("{loginAccount:"{0}"}", "admin"));
     78         params.put("parmJson", StringUtil.format("{appId:"{0}",wiid:"{1}",businessKey:"{2}",title:"{3}",opinion:"{4}",jsonFormData:{5}}", "ZX", Guid.getGuid(), Guid.getGuid(), "应用端RestFull请求测试", "同意", onlineFormData));
     79         // String param = HttpClientUtil.urlEncode(queryString.toString());
     80         // //特殊字符进行转义
     81         String jsonRes = HttpClientUtil.post(urlString, params);
     82         System.out.println(jsonRes);
     83     }
     84 
     85     /**
     86      * 驳回到提单
     87      */
     88     public void rejectFlow() {
     89         String urlString = webApiUrl + "/workflowBusiness/rejectFlow/";
     90         Map<String, String> params = new HashMap<String, String>();
     91         params.put("authorJson", StringUtil.format("{loginAccount:"{0}"}", "admin"));
     92         params.put("parmJson", StringUtil.format("{taskId:"{0}",opinion:"{1}"}", "d212c718-b6ea-481e-b7cc-1f44a9d47fd0", "驳回"));
     93         String jsonRes = HttpClientUtil.post(urlString, params);
     94         System.out.println(jsonRes);
     95     }
     96 
     97     /**
     98      * 作废工单
     99      */
    100     public void invalidFlow() {
    101         String urlString = webApiUrl + "/workflowBusiness/invalidFlow/";
    102         Map<String, String> params = new HashMap<String, String>();
    103         params.put("authorJson", StringUtil.format("{loginAccount:"{0}"}", "admin"));
    104         params.put("parmJson", StringUtil.format("{taskId:"{0}",opinion:"{1}"}", "eac4e893-822c-46ec-9ba6-a1c028a1cef3", "作废"));
    105         String jsonRes = HttpClientUtil.post(urlString, params);
    106         System.out.println(jsonRes);
    107     }
    108 
    109     /**
    110      * 审批执行代办任务
    111      */
    112     public void approvalTask() {
    113         String urlString = webApiUrl + "/workflowBusiness/approvalTask/";
    114         Map<String, String> params = new HashMap<String, String>();
    115         params.put("authorJson", StringUtil.format("{loginAccount:"{0}"}", "admin"));
    116         params.put("parmJson", StringUtil.format("{taskId:"{0}",opinion:"{1}"}", "5f267057-ddd4-470a-bca4-a797caac3e09", "原则同意"));
    117         String jsonRes = HttpClientUtil.post(urlString, params);
    118         System.out.println(jsonRes);
    119     }
    120 
    121 
    122     /**
    123      *上传在线表单附件,返回字段值单个附件值
    124     /表单附件的字段值格式:
    125     /#[{"value":"/attachments/workflow/files/20170714215204767.txt","text":"TestClient.txt"}]#
    126     */
    127     public void uploadFormFile() {
    128         String urlString = webApiUrl + "/workflowBusiness/uploadFile/?loginAccount=admin";
    129         String filepath = "C:\Users\Administrator\Desktop\TestClient.txt";
    130         String jsonRes = HttpClientUtil.postFile(urlString, filepath);
    131         System.out.println(jsonRes);
    132     }
    133     /**
    134      * 下载表单附件
    135      */
    136     public void downLoadFile() {
    137         String urlString = webApiUrl + "/workflowBusiness/downloadFile/";
    138         //保存到本地的地址
    139         String filepath = "C:\Users\Administrator\Desktop\TestClient.txt";
    140         
    141         Map<String, String> params = new HashMap<String, String>();
    142         params.put("authorJson", StringUtil.format("{login Account:"{0}"}", "admin"));
    143         params.put("parmJson", StringUtil.format("{filePath:"{0}"}", "/attachments/workflow/files/20170714215204767.txt"));
    144         String jsonRes = HttpClientUtil.downLoadFile(urlString,filepath, params);
    145         System.out.println(jsonRes);
    146         
    147     }
    148     
    149     public static void main(String[] args) {
    150         WorkflowBusinessTestClient client = new WorkflowBusinessTestClient();
    151         client.downLoadFile();
    152         System.out.print("结束");
    153     }
    154 
    155 }
  • 相关阅读:
    机器学习框架之sklearn简介
    ubuntu 16.04下使用 python pip的安装问题。
    ubuntu 16.04 搭建git小型服务器
    使用config 来管理ssh的会话
    【linux】su、sudo、sudo su、sudo -i的用法和区别
    【python】确保文件写入结束
    【python】描述符descriptor
    【python】类(资料+疑惑)
    【pymongo】mongodb cursor id not valid error
    【python】继承关系和isinstance
  • 原文地址:https://www.cnblogs.com/f2flow/p/7182025.html
Copyright © 2011-2022 走看看