F2BPM 开发Api与RESTfull应用服务Api 层次关系以及示范

authorJson:主要是接口位置的说明相关参数,校验访问者的发源合法性

           Parallel类
主要提供相互循环和区域之支持,主要发生三个办法For、Foreach、Invoke,主要说一下Invoke方法,Invoke方法会简化启动同组并行操作,它承受一组Action[]数组。

不无RESTfull都合并就生应声有限独Json参数  

    1. 首先栽是调用Task.ContinueWith方法
    2. 次栽是.Net
      Framework4.5增产的Awaiter方法,它非常主要,因为C#5.0的异步功能就是是以这种艺术。先押程序代码来证明

RESTfull参数方式

     所以结论是:
       -CPU Bound:适合采用多线程;
       -IO  Bound:适合采用异步;

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

  • Async与await关键词
    有async修饰词不自然有await运算符,但发生await运算符一定有async修饰词,按照微软的建议,开发人员自己编写的异步方法极其好与否动“Async”结尾。
  • 异步与线程池
    当当应用程序中大量施用多线程技术时,首先发出好几务必注意。.net
    framework
    会在IIS维护一个线程池,当iis接受到一个请求时,就会从线程池读取一个线程处理的求,如果利用并处理程序方式处理者要,此线程直到程序处理完毕前,都见面一直为和谐请服务,并且是线程无法再为外请求进行服务,就是所谓的自律。
    如果线程池够好,就从未有过什么问题,不过线程池的数是个别的,当有恢宏突发请求,或只是应伸手线程都没空后端高延迟性网络任务时,所有线程池的线程都于律,这种情景称线程耗尽。发生线程耗尽,IIS会开始以呼吁排入队列,如果队列已满时,IIS就会拒绝请求,并显现http503状态,如果异步应用程序正常,但是有时会时有发生http503状态,那么可开拍,事故也宗近的景象,可以试试着调强队列长度,例如调强至一千。
  • 大抵线程与异步
    Task->新线程->读取网络资源
    大抵线程只是变一长线程来代表原本会被锁定的主线程,也便是故线程资源(CPU与内存)换可响应的接口。如果换成异步呢?
    异步->线程池->读取网络资源
    在线程池中经常利用DMA(Direct Memory
    Access,直接内存访问)模式,直接内存访问是一模一样栽不通过CPU而直接进行内存数据读取的机制。CLR提供的异步程序模型就是叫开发者充分利用DMA功能来降低CPU压力

脚下更进一步多的企业架构解决方案更加趋于于依据http协议“微服务”访问过系统调用,而非使统传的WebService调用,即由此RESTfull方式展开相互,更加轻量整合调用更加有益于。本文档中所有F2BPM开发接口API都足以发表成RESTfull对外应用服务接口

   
调用Task.GetAwaiter方法会返回一个awaiter(等待者)对象,它会叫原先的Task在成就或者错后执行一个委,如果先的Task出现错误,那么当接续工作调用awaited.GetResult()时即见面弹来不同。使用GetResult的好处是,当先底Task出错时,例外得直接弹出,而无会见封装在
aggregateException中。

 

       
  Task.Delay方法以成立时间推移之后才见面完成的做事,简单地游说,它便是Thread.Sleep的异步版本

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 }

 

  • 线程:
    每个Windows进程都有用于进入次葡京在线开户的入点(entry point)的主线程(Main
    Thread),例如.Net
    framework执行顺序(控制台、Windows
    WPF等应用程序)使用Main()方法作为次的进入点,调用该方式时见面自动建立主线程。
    线程是Windows进程中之独执行单元,每个线程都有一个主线程(在尽上点时成立)并且每个线程还得以程序方法建立新的线程。
    线程的分配与开行需要自然的时跟基金开销,所以这进程并无是实时的。

  • Task类:
    与Thread相比,Task是双重抽象的概念,MSDN说明就是大概一词:“表示异步操作”,即为能坐差不多线程执行之异步操作,从net
    framework4.5初步,要确立落实Task后台线程最简易的措施就是是用静态方法Task.Run(),在.Net
    Framework 4.0方可调用Task.Factory.StartNew方法,可以实现同的效果

 

           
持续工作会告诉Task在得后持续实行后续的功课,持续工作便由一个回调方法来落实,它会于任务就后实施同样不行。将一个Task加上频频工作发生一定量种植办法,

    Task<int> task=Task.Run(
         ()=>Enumerable.Range(1,5000000).Count(n=>(n%3)==0);
         var awaiter=task.GetAwaiter();
         awaiter.OnCompleted(()=>
       {
         int result=awaiter.GetResult();
         Console.WriteLine("整除3的个数有:"+Result);
         Console.WriteLine("Task执行中...")
         Console.ReadLine();
       });

生一致步是早晚看看 .Net Core了。