工具相关

Idea git提交代码忽略.idea等文件

idea需要下载一个专门的plugins 来忽略 .idea *.iml等文件

可以在 settings->plugins 搜索 .ignore 插件下载安装,在想忽略的文件或者目录右键
image.png
如果发现并没有生效,是由于此文件被git追踪过,执行:

  1. git rm -rf --cached .idea

即可;

PowerDesigner显示Comment注释列

在 Columns 标签下,一排按钮中找到这个按钮: Customize Columns and Filter
image.png

datagrip 查询结果不能修改

打开对应库的配置

image.png

选择要操作对Schemas

image.png

Springboot

Spring Security异常处理

  • AuthenticationEntryPoint 用来解决匿名用户访问无权限资源时的异常
  • AccessDeineHandler 用来解决认证过的用户访问无权限资源时的异常

    基础配置类

    1. @Configuration
    2. @EnableWebSecurity
    3. @EnableGlobalMethodSecurity(prePostEnabled=true)
    4. public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
    5. @Autowired
    6. private UserDetailsService userDetailsService;
    7. @Autowired
    8. private BCryptPasswordEncoder bCryptPasswordEncoder;
    9. @Override
    10. protected void configure(HttpSecurity http) throws Exception {
    11. http.cors()
    12. .and()
    13. .csrf().disable()
    14. .authorizeRequests()
    15. .antMatchers("/login").permitAll().anyRequest().authenticated()
    16. .and()
    17. .addFilter(new JWTLoginFilter(authenticationManager()))
    18. .addFilter(new JwtAuthenticationFilter(authenticationManager()));
    19. //添加自定义异常入口,处理accessdeine异常
    20. http.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
    21. .accessDeniedHandler(new CustomAccessDeineHandler());
    22. }
    23. @Override
    24. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    25. auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    26. }
    27. }

    自定义AuthenticationEntryPoint的实现类:

    ```java

import java.io.IOException;

import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint;

import com.alibaba.fastjson.JSONObject;

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

  1. @Override
  2. public void commence(HttpServletRequest request, HttpServletResponse response,
  3. AuthenticationException authException) throws IOException, ServletException {
  4. response.setCharacterEncoding("utf-8");
  5. response.setContentType("text/javascript;charset=utf-8");
  6. response.getWriter().print("没有访问权限!");
  7. }

}

  1. <a name="a4p5G"></a>
  2. ### 自定义AccessDeineHandler实现类:
  3. ```java
  4. import java.io.IOException;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import org.springframework.security.access.AccessDeniedException;
  9. import org.springframework.security.web.access.AccessDeniedHandler;
  10. import com.alibaba.fastjson.JSONObject;
  11. public class CustomAccessDeineHandler implements AccessDeniedHandler {
  12. @Override
  13. public void handle(HttpServletRequest request, HttpServletResponse response,
  14. AccessDeniedException accessDeniedException) throws IOException, ServletException {
  15. response.setCharacterEncoding("utf-8");
  16. response.setContentType("text/javascript;charset=utf-8");
  17. response.getWriter().print("没有访问权限!");
  18. }
  19. }

Java基础

LinkedHashMap转对象

想要将返回数据强转为对象

  1. 错误信息: org.springframework.util.LinkedCaseInsensitiveMap cannot be cast to com.richfit.ip.privilege.entity.Dept

image.png

  1. JSON.parseObject(JSON.toJSONString(d),new TypeReference<Dept>(){})

解决方法

1.直接使用Map对象来接

使用 Map<String,Object> map = data ,然后使用 map.get() 来获取里面的值。

注意:如果有多个字段的话,不建议使用这样来做,太傻了。

2.使用JSON字符串来转对象

使用阿里的fastJson来将这个linkedHashMap转换成对象。

  1. import com.alibaba.fastjson.JSON;
  2. import com.alibaba.fastjson.TypeReference;
  3. JSON.parseObject(JSON.toJSONString(数据), new TypeReference<对象>() {
  4. });

Java 快速按行读取文件

起因:
Java的IO总是很繁琐,而且需要你显式地处理IO抛出的异常,在一般的脚本化处理起来非常麻烦。每次仅仅是需要一个需求,那就是——快速按行读取文件,但是总是要查半天!
记录一下快速的按行读取文件的代码。我们知道Python什么的很好用:open —> read… read… -> close就好了,而JAVA很烦。

传统的

  1. private static void readFile2(File fin) throws IOException {
  2. // Construct BufferedReader from FileReader
  3. BufferedReader br = new BufferedReader(new FileReader(fin));
  4. String line = null;
  5. while ((line = br.readLine()) != null) {
  6. System.out.println(line);
  7. }
  8. br.close();
  9. }
  10. try with resource
  11. File file = new File("F:\\dogData\\VCF2Tree\\eGPS_result_ydl20190902\\sample.csv");
  12. try (BufferedReader br = new BufferedReader(new FileReader(file));) {
  13. String line = null;
  14. while ((line = br.readLine()) != null) {
  15. System.out.println(line);
  16. }
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. }

java8

  1. Charset charset = Charset.forName("US-ASCII");
  2. try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
  3. String line = null;
  4. while ((line = reader.readLine()) != null) {
  5. System.out.println(line);
  6. }
  7. } catch (IOException x) {
  8. System.err.format("IOException: %s%n", x);
  9. }

第三方库

  1. import org.apache.commons.io.FileUtils;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.List;
  5. public class ReadTextFile {
  6. public static void main(String[] args) throws IOException {
  7. try {
  8. File f = new File("src/com/mkyong/data.txt");
  9. System.out.println("Reading files using Apache IO:");
  10. List<String> lines = FileUtils.readLines(f, "UTF-8");
  11. for (String line : lines) {
  12. System.out.println(line);
  13. }
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }

工具

腾讯通

功能一:发送即时消息_1.调用方式:GET/POST URL:/sendnotify.cgi 用法举例(IE地址栏中输入):

  1. http://127.0.0.1:8012/sendnotify.cgi?msg=hello&receiver=wwjs

参数表:

  • receiver :接收者,用户昵称,多个接收者以“,”隔开。
  • msg :消息内容 ,如需要发隐式链接,格式如: [我的博客|http://www.baidu.com]
  • title :消息提醒的标题。
  • delaytime :消息提醒框的停留时间(毫秒),0表示不自动消失。
  • okurl :成功后IE自动定位到指定的url 格式类似为:okurl=www.baidu.com或者 okurl=http://www.baidu.com 注意:这里的url必须为绝对地址
  • errurl :失败后IE自动定位到指定的 url 。
  1. package com.rfxj.projects.swawp.task.util.Rtx;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.net.URLEncoder;
  9. /**
  10. * 腾讯通工具类
  11. *
  12. * @author DuebassLei
  13. * @version 1.0
  14. * @date 2020/9/21 19:20
  15. *
  16. */
  17. public class RtxMsgUtil {
  18. /** 字符集编码 {@value} */
  19. private static final String CHARSET = "gbk";
  20. /** 状态码 {@value} */
  21. private static final int HTTP_CODE = 200;
  22. /**
  23. * 发送腾讯通消息
  24. *
  25. * @param title 标题
  26. * @param msg 消息内容
  27. * @param receivers 接受消息人
  28. * @param delaytime 消息提醒框的停留时间(毫秒),0表示不自动消失。
  29. * @return 发送成功/失败
  30. * */
  31. public static boolean sendRtxNotify(String title, String msg, String[] receivers,String delaytime)
  32. {
  33. HttpURLConnection connection = null;
  34. InputStream inputStream = null;
  35. BufferedReader bufferedReader = null;
  36. String result = null;
  37. try
  38. {
  39. String baseUrl = "http://10.172.30.120:8012/sendnotify.cgi";
  40. String params = "";
  41. params += "?title=" + URLEncoder.encode(title, CHARSET);
  42. params += "&msg=" + URLEncoder.encode(msg, CHARSET);
  43. params += "&delaytime=" + URLEncoder.encode(delaytime, CHARSET);
  44. // params += "&receiver=13520";
  45. StringBuilder receiver = new StringBuilder();
  46. for (String item : receivers) {
  47. if(!receiver.toString().equals("")) {
  48. receiver.append(",");
  49. }
  50. receiver.append(item);
  51. }
  52. params += "&receiver=" + receiver;
  53. baseUrl = baseUrl + params;
  54. URL url = new URL(baseUrl);
  55. connection = (HttpURLConnection) url.openConnection();
  56. connection.setRequestProperty("Content-Type", "text/html;charset=gbk");
  57. connection.setRequestMethod("POST");
  58. connection.setConnectTimeout(15000);
  59. connection.setReadTimeout(60000);
  60. connection.connect();
  61. if(connection.getResponseCode() == HTTP_CODE) {
  62. inputStream = connection.getInputStream();
  63. bufferedReader = new BufferedReader(new InputStreamReader(inputStream, CHARSET));
  64. StringBuilder stringBuffer = new StringBuilder();
  65. String temp = null;
  66. while ((temp = bufferedReader.readLine()) != null) {
  67. stringBuffer.append(temp);
  68. stringBuffer.append("\r\n");
  69. }
  70. result = stringBuffer.toString();
  71. }
  72. } catch (IOException e) {
  73. e.printStackTrace();
  74. } finally {
  75. if(null != bufferedReader) {
  76. try {
  77. bufferedReader.close();
  78. } catch (IOException e) {
  79. e.printStackTrace();
  80. }
  81. }
  82. if (null != inputStream) {
  83. try {
  84. inputStream.close();
  85. } catch (IOException e) {
  86. e.printStackTrace();
  87. }
  88. }
  89. if(null != connection) {
  90. connection.disconnect();
  91. }
  92. }
  93. return result != null && result.contains("操作成功");
  94. }
  95. public static void main(String[] args) {
  96. sendRtxNotify("测试","您有未办理的流程",new String[]{"13520"},"9000");
  97. }
  98. }

Activiti 6 + Springboot1.5

配置类ActivitiConfig.java

  1. /**
  2. * @author DuebassLei
  3. * @version 1.0
  4. * @date 2021/5/26 9:43
  5. */
  6. @Configuration
  7. public class ActivitiConfig extends AbstractProcessEngineAutoConfiguration {
  8. // @Bean
  9. // @Primary
  10. // @ConfigurationProperties(prefix = "spring.iomOggDataSource")
  11. // public DataSource activitiDataSource() {
  12. // return DataSourceBuilder.create().build();
  13. //
  14. // }
  15. @Resource
  16. @Qualifier("iomOggDataSource")
  17. protected DataSource oggds;
  18. @Bean
  19. public PlatformTransactionManager transactionManager() throws Exception {
  20. // 配置事务管理, 使用事务时在方法头部添加@Transactional注解即可
  21. return new DataSourceTransactionManager(oggds);
  22. }
  23. @Bean
  24. public SpringProcessEngineConfiguration springProcessEngineConfiguration(
  25. PlatformTransactionManager transactionManager,
  26. SpringAsyncExecutor springAsyncExecutor) throws IOException {
  27. return baseSpringProcessEngineConfiguration(
  28. oggds,
  29. transactionManager,
  30. springAsyncExecutor);
  31. }
  32. }

控制器Controller

  1. @Autowired
  2. private RuntimeService runtimeService;
  3. @Autowired
  4. private TaskService taskService;
  5. @Autowired
  6. private RepositoryService repositoryService;
  7. @Autowired
  8. private HistoryService historyService;
  9. @Autowired
  10. private ProcessEngineConfiguration processEngineConfiguration;
  11. /**
  12. * activi测试
  13. * @param jsonParam 查询参数
  14. * @return PageListInfo 分页信息
  15. * */
  16. @ResponseBody
  17. @RequestMapping(value = "/act", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
  18. public void actTest(@RequestBody JSONObject jsonParam) {
  19. log.info( "调用流程存储服务,查询部署数量:" + repositoryService.createDeploymentQuery().count());
  20. Map<String,Object> map = new HashMap<String,Object>();
  21. map.put("apply","zhangsan");
  22. map.put("approve","lisi");
  23. ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("leave","10000024",map);
  24. System.out.println(processInstance.getBusinessKey());
  25. List<Task> tq=taskService.createTaskQuery().taskAssignee("zhangsan").list();
  26. System.out.println(tq.size());
  27. String assignee = "zhangsan";//当前任务办理人
  28. List<Task> tasks = taskService//与任务相关的Service
  29. .createTaskQuery()//创建一个任务查询对象
  30. .taskAssignee(assignee)
  31. .list();
  32. if(tasks !=null && tasks.size()>0){
  33. for(Task task:tasks){
  34. System.out.println("任务ID:"+task.getId());
  35. System.out.println("任务的办理人:"+task.getAssignee());
  36. System.out.println("任务名称:"+task.getName());
  37. System.out.println("任务的创建时间:"+task.getCreateTime());
  38. System.out.println("流程实例ID:"+task.getProcessInstanceId());
  39. System.out.println("#####################################");
  40. }
  41. }
  42. //创建
  43. System.out.println("method startActivityDemo end....");
  44. // return false;
  45. }
  46. /**
  47. * activi测试
  48. * @param jsonParam 查询参数
  49. * @return PageListInfo 分页信息
  50. * */
  51. @ResponseBody
  52. @RequestMapping(value = "/startProcess", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
  53. public void startProcess(@RequestBody JSONObject jsonParam) {
  54. log.info("--->调用流程存储服务,查询部署数量:{}",repositoryService.createDeploymentQuery().count());
  55. log.info("--->启动流程设置流程变量,指定下一个代理人是谁:");
  56. Map<String,Object> map = new HashMap<>();
  57. map.put("sponsor",jsonParam.getString("sponsor"));
  58. //设置过期时间
  59. map.put("dueDate","lisi");
  60. ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("leave","10000024",map);
  61. System.out.println(processInstance.getBusinessKey());
  62. List<Task> tq=taskService.createTaskQuery().taskAssignee("zhangsan").list();
  63. System.out.println(tq.size());
  64. String assignee = "zhangsan";//当前任务办理人
  65. List<Task> tasks = taskService//与任务相关的Service
  66. .createTaskQuery()//创建一个任务查询对象
  67. .taskAssignee(assignee)
  68. .list();
  69. if(tasks !=null && tasks.size()>0){
  70. for(Task task:tasks){
  71. System.out.println("任务ID:"+task.getId());
  72. System.out.println("任务的办理人:"+task.getAssignee());
  73. System.out.println("任务名称:"+task.getName());
  74. System.out.println("任务的创建时间:"+task.getCreateTime());
  75. System.out.println("流程实例ID:"+task.getProcessInstanceId());
  76. System.out.println("#####################################");
  77. }
  78. }
  79. System.out.println("method startActivityDemo end....");
  80. }
  81. /**
  82. * 删除流程实例
  83. *
  84. * */
  85. @ResponseBody
  86. @RequestMapping(value = "/delProcessByBusinessKey", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
  87. public void delProcessByBusinessKey(@RequestBody JSONObject jsonParam) {
  88. String businessKey = jsonParam.getString("businessKey");
  89. //获取该流程的实例id:   
  90. HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery()
  91. .processInstanceBusinessKey(businessKey)
  92. // .processInstanceId(businessKey)
  93. .singleResult();
  94. String processInstanceId = hpi.getId(); //流程实例ID
  95. // 判断该流程实例是否结束,未结束和结束两者删除表的信息是不一样的
  96. ProcessInstance pi = runtimeService.createProcessInstanceQuery()
  97. .processInstanceId(processInstanceId)
  98. .singleResult();
  99. if(pi==null){
  100. //该流程实例已经完成了
  101. historyService.deleteHistoricProcessInstance(processInstanceId);
  102. }else{
  103. //该流程实例未结束的
  104. runtimeService.deleteProcessInstance(processInstanceId,"");
  105. historyService.deleteHistoricProcessInstance(processInstanceId);//(顺序不能换)
  106. }
  107. }
  108. /**
  109. * 查询部署对象信息,对应表(act_re_deployment)
  110. * */
  111. @ResponseBody
  112. @RequestMapping(value = "/getDeploymentList", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
  113. public List<Deployment> getDeploymentList() {
  114. List<Deployment> list = repositoryService.createDeploymentQuery()//创建部署对象查询
  115. .orderByDeploymenTime().asc()//
  116. .list();
  117. return list;
  118. }
  119. /**
  120. * 查询流程定义的信息,对应表(act_re_procdef)
  121. * */
  122. @ResponseBody
  123. @RequestMapping(value = "/getProcessDefinitionList", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
  124. public List<ProcessDefinition> getProcessDefinitionList() {
  125. List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery()//创建流程定义查询
  126. .orderByProcessDefinitionVersion().desc()//
  127. .list();
  128. return list;
  129. }
  130. /**
  131. * 根据用户 id 获取 当前人的任务列表
  132. * */
  133. @ResponseBody
  134. @RequestMapping(value = "/getTaskListByUserId", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
  135. public void getTaskListByUserId(@RequestBody JSONObject jsonParam) {
  136. String userId = jsonParam.getString("userId");
  137. List<Task> tasks = taskService
  138. .createTaskQuery()//
  139. .taskAssignee(userId) //指定个人任务查询
  140. // .taskCandidateOrAssigned(String.valueOf(userId))
  141. .orderByTaskCreateTime().desc()//
  142. .list();
  143. if(tasks !=null && tasks.size()>0){
  144. for(Task task:tasks){
  145. System.out.println("任务ID:"+task.getId());
  146. System.out.println("任务的办理人:"+task.getAssignee());
  147. System.out.println("任务名称:"+task.getName());
  148. System.out.println("任务的创建时间:"+task.getCreateTime());
  149. System.out.println("流程实例ID:"+task.getProcessInstanceId());
  150. System.out.println("#####################################");
  151. }
  152. }
  153. }
  154. /**
  155. * 根据流程实例Id,获取实时流程图片
  156. *
  157. * @param processInstanceId
  158. * @param response
  159. * @return
  160. */
  161. // public void getFlowImgByInstanceId(String processInstanceId, OutputStream outputStream) {
  162. @RequestMapping(value = "/getFlowImg/{processInstanceId}")
  163. public void getFlowImgByInstanceId(@PathVariable("processInstanceId") String processInstanceId, HttpServletResponse response) {
  164. try {
  165. OutputStream outputStream = response.getOutputStream();
  166. if (StringUtils.isEmpty(processInstanceId)) {
  167. log.error("processInstanceId is null");
  168. return;
  169. }
  170. // 获取历史流程实例
  171. HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
  172. // 获取流程中已经执行的节点,按照执行先后顺序排序
  173. List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId)
  174. .orderByHistoricActivityInstanceId().asc().list();
  175. // 高亮已经执行流程节点ID集合
  176. List<String> highLightedActivitiIds = new ArrayList<>();
  177. for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
  178. highLightedActivitiIds.add(historicActivityInstance.getActivityId());
  179. }
  180. List<HistoricProcessInstance> historicFinishedProcessInstances = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).finished()
  181. .list();
  182. ProcessDiagramGenerator processDiagramGenerator = null;
  183. // 如果还没完成,流程图高亮颜色为绿色,如果已经完成为红色
  184. if (!CollectionUtils.isEmpty(historicFinishedProcessInstances)) {
  185. // 如果不为空,说明已经完成
  186. processDiagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
  187. } else {
  188. processDiagramGenerator = new CustomProcessDiagramGenerator();
  189. }
  190. BpmnModel bpmnModel = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());
  191. // 高亮流程已发生流转的线id集合
  192. List<String> highLightedFlowIds = getHighLightedFlows(bpmnModel, historicActivityInstances);
  193. // 使用默认配置获得流程图表生成器,并生成追踪图片字符流
  194. InputStream imageStream = processDiagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivitiIds, highLightedFlowIds, "宋体", "微软雅黑", "黑体", null, 2.0);
  195. // 输出图片内容
  196. byte[] b = new byte[1024];
  197. int len;
  198. while ((len = imageStream.read(b, 0, 1024)) != -1) {
  199. outputStream.write(b, 0, len);
  200. }
  201. } catch (Exception e) {
  202. log.error("processInstanceId" + processInstanceId + "生成流程图失败,原因:" + e.getMessage(), e);
  203. }
  204. }
  205. /**
  206. * 获取已经流转的线
  207. *
  208. * @param bpmnModel
  209. * @param historicActivityInstances
  210. * @return
  211. */
  212. private static List<String> getHighLightedFlows(BpmnModel bpmnModel, List<HistoricActivityInstance> historicActivityInstances) {
  213. // 高亮流程已发生流转的线id集合
  214. List<String> highLightedFlowIds = new ArrayList<>();
  215. // 全部活动节点
  216. List<FlowNode> historicActivityNodes = new ArrayList<>();
  217. // 已完成的历史活动节点
  218. List<HistoricActivityInstance> finishedActivityInstances = new ArrayList<>();
  219. for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
  220. FlowNode flowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(historicActivityInstance.getActivityId(), true);
  221. historicActivityNodes.add(flowNode);
  222. if (historicActivityInstance.getEndTime() != null) {
  223. finishedActivityInstances.add(historicActivityInstance);
  224. }
  225. }
  226. FlowNode currentFlowNode = null;
  227. FlowNode targetFlowNode = null;
  228. // 遍历已完成的活动实例,从每个实例的outgoingFlows中找到已执行的
  229. for (HistoricActivityInstance currentActivityInstance : finishedActivityInstances) {
  230. // 获得当前活动对应的节点信息及outgoingFlows信息
  231. currentFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(currentActivityInstance.getActivityId(), true);
  232. List<SequenceFlow> sequenceFlows = currentFlowNode.getOutgoingFlows();
  233. /**
  234. * 遍历outgoingFlows并找到已已流转的 满足如下条件认为已已流转: 1.当前节点是并行网关或兼容网关,则通过outgoingFlows能够在历史活动中找到的全部节点均为已流转 2.当前节点是以上两种类型之外的,通过outgoingFlows查找到的时间最早的流转节点视为有效流转
  235. */
  236. if ("parallelGateway".equals(currentActivityInstance.getActivityType()) || "inclusiveGateway".equals(currentActivityInstance.getActivityType())) {
  237. // 遍历历史活动节点,找到匹配流程目标节点的
  238. for (SequenceFlow sequenceFlow : sequenceFlows) {
  239. targetFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(sequenceFlow.getTargetRef(), true);
  240. if (historicActivityNodes.contains(targetFlowNode)) {
  241. highLightedFlowIds.add(targetFlowNode.getId());
  242. }
  243. }
  244. } else {
  245. List<Map<String, Object>> tempMapList = new ArrayList<>();
  246. for (SequenceFlow sequenceFlow : sequenceFlows) {
  247. for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
  248. if (historicActivityInstance.getActivityId().equals(sequenceFlow.getTargetRef())) {
  249. Map<String, Object> map = new HashMap<>();
  250. map.put("highLightedFlowId", sequenceFlow.getId());
  251. map.put("highLightedFlowStartTime", historicActivityInstance.getStartTime().getTime());
  252. tempMapList.add(map);
  253. }
  254. }
  255. }
  256. if (!CollectionUtils.isEmpty(tempMapList)) {
  257. // 遍历匹配的集合,取得开始时间最早的一个
  258. long earliestStamp = 0L;
  259. String highLightedFlowId = null;
  260. for (Map<String, Object> map : tempMapList) {
  261. long highLightedFlowStartTime = Long.valueOf(map.get("highLightedFlowStartTime").toString());
  262. if (earliestStamp == 0 || earliestStamp >= highLightedFlowStartTime) {
  263. highLightedFlowId = map.get("highLightedFlowId").toString();
  264. earliestStamp = highLightedFlowStartTime;
  265. }
  266. }
  267. highLightedFlowIds.add(highLightedFlowId);
  268. }
  269. }
  270. }
  271. return highLightedFlowIds;
  272. }

重绘流程图方法

  • 文件备份

CustomProcessDiagramGenerator.java
CustomProcessDiagramCanvas.java

CustomProcessDiagramCanvas.java

  1. package com.ztesoft.wfm.util.activiti;
  2. /* Licensed under the Apache License, Version 2.0 (the "License");
  3. * you may not use this file except in compliance with the License.
  4. * You may obtain a copy of the License at
  5. *
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. *
  8. * Unless required by applicable law or agreed to in writing, software
  9. * distributed under the License is distributed on an "AS IS" BASIS,
  10. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. * See the License for the specific language governing permissions and
  12. * limitations under the License.
  13. */
  14. import java.awt.BasicStroke;
  15. import java.awt.Color;
  16. import java.awt.Font;
  17. import java.awt.FontMetrics;
  18. import java.awt.Graphics2D;
  19. import java.awt.Paint;
  20. import java.awt.Point;
  21. import java.awt.Polygon;
  22. import java.awt.Rectangle;
  23. import java.awt.RenderingHints;
  24. import java.awt.Shape;
  25. import java.awt.Stroke;
  26. import java.awt.font.FontRenderContext;
  27. import java.awt.font.LineBreakMeasurer;
  28. import java.awt.font.TextAttribute;
  29. import java.awt.font.TextLayout;
  30. import java.awt.geom.AffineTransform;
  31. import java.awt.geom.Ellipse2D;
  32. import java.awt.geom.Line2D;
  33. import java.awt.geom.Path2D;
  34. import java.awt.geom.PathIterator;
  35. import java.awt.geom.Rectangle2D;
  36. import java.awt.geom.RoundRectangle2D;
  37. import java.awt.image.BufferedImage;
  38. import java.io.ByteArrayInputStream;
  39. import java.io.ByteArrayOutputStream;
  40. import java.io.IOException;
  41. import java.io.InputStream;
  42. import java.text.AttributedCharacterIterator;
  43. import java.text.AttributedString;
  44. import java.util.ArrayList;
  45. import java.util.List;
  46. import javax.imageio.ImageIO;
  47. import org.activiti.bpmn.model.AssociationDirection;
  48. import org.activiti.bpmn.model.GraphicInfo;
  49. import org.activiti.engine.ActivitiException;
  50. import org.activiti.image.exception.ActivitiImageException;
  51. import org.activiti.image.util.ReflectUtil;
  52. import org.slf4j.Logger;
  53. import org.slf4j.LoggerFactory;
  54. /**
  55. * Represents a canvas on which BPMN 2.0 constructs can be drawn. Some of the icons used are licensed under a Creative Commons Attribution 2.5 License, see
  56. * http://www.famfamfam.com/lab/icons/silk/
  57. *
  58. * @see org.activiti.engine.impl.bpmn.diagram.DefaultProcessDiagramGenerator
  59. * @author Joram Barrez
  60. */
  61. public class CustomProcessDiagramCanvas {
  62. protected static final Logger LOGGER = LoggerFactory.getLogger(CustomProcessDiagramCanvas.class);
  63. public enum SHAPE_TYPE {
  64. Rectangle, Rhombus, Ellipse
  65. }
  66. // Predefined sized
  67. protected static final int ARROW_WIDTH = 5;
  68. protected static final int CONDITIONAL_INDICATOR_WIDTH = 16;
  69. protected static final int DEFAULT_INDICATOR_WIDTH = 10;
  70. protected static final int MARKER_WIDTH = 12;
  71. protected static final int FONT_SIZE = 11;
  72. protected static final int FONT_SPACING = 2;
  73. protected static final int TEXT_PADDING = 3;
  74. protected static final int ANNOTATION_TEXT_PADDING = 7;
  75. protected static final int LINE_HEIGHT = FONT_SIZE + FONT_SPACING;
  76. // Colors
  77. protected static Color TASK_BOX_COLOR = new Color(249, 249, 249);
  78. protected static Color SUBPROCESS_BOX_COLOR = new Color(255, 255, 255);
  79. protected static Color EVENT_COLOR = new Color(255, 255, 255);
  80. protected static Color CONNECTION_COLOR = new Color(88, 88, 88);
  81. protected static Color CONDITIONAL_INDICATOR_COLOR = new Color(255, 255, 255);
  82. // protected static Color HIGHLIGHT_COLOR = Color.RED;
  83. protected static Color HIGHLIGHT_COLOR = Color.GREEN;
  84. protected static Color LABEL_COLOR = new Color(112, 146, 190);
  85. protected static Color TASK_BORDER_COLOR = new Color(187, 187, 187);
  86. protected static Color EVENT_BORDER_COLOR = new Color(88, 88, 88);
  87. protected static Color SUBPROCESS_BORDER_COLOR = new Color(0, 0, 0);
  88. // Fonts
  89. protected static Font LABEL_FONT = null;
  90. protected static Font ANNOTATION_FONT = new Font("Arial", Font.PLAIN, FONT_SIZE);
  91. protected static Font TASK_FONT = new Font("Arial", Font.PLAIN, FONT_SIZE);
  92. // Strokes
  93. protected static Stroke THICK_TASK_BORDER_STROKE = new BasicStroke(3.0f);
  94. protected static Stroke GATEWAY_TYPE_STROKE = new BasicStroke(3.0f);
  95. protected static Stroke END_EVENT_STROKE = new BasicStroke(3.0f);
  96. protected static Stroke MULTI_INSTANCE_STROKE = new BasicStroke(1.3f);
  97. protected static Stroke EVENT_SUBPROCESS_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1.0f, new float[] { 1.0f }, 0.0f);
  98. protected static Stroke NON_INTERRUPTING_EVENT_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1.0f, new float[] { 4.0f, 3.0f }, 0.0f);
  99. protected static Stroke HIGHLIGHT_FLOW_STROKE = new BasicStroke(1.3f);
  100. protected static Stroke ANNOTATION_STROKE = new BasicStroke(2.0f);
  101. protected static Stroke ASSOCIATION_STROKE = new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1.0f, new float[] { 2.0f, 2.0f }, 0.0f);
  102. // icons
  103. protected static int ICON_PADDING = 5;
  104. protected static BufferedImage USERTASK_IMAGE;
  105. protected static BufferedImage SCRIPTTASK_IMAGE;
  106. protected static BufferedImage SERVICETASK_IMAGE;
  107. protected static BufferedImage RECEIVETASK_IMAGE;
  108. protected static BufferedImage SENDTASK_IMAGE;
  109. protected static BufferedImage MANUALTASK_IMAGE;
  110. protected static BufferedImage BUSINESS_RULE_TASK_IMAGE;
  111. protected static BufferedImage SHELL_TASK_IMAGE;
  112. protected static BufferedImage MULE_TASK_IMAGE;
  113. protected static BufferedImage CAMEL_TASK_IMAGE;
  114. protected static BufferedImage TIMER_IMAGE;
  115. protected static BufferedImage COMPENSATE_THROW_IMAGE;
  116. protected static BufferedImage COMPENSATE_CATCH_IMAGE;
  117. protected static BufferedImage ERROR_THROW_IMAGE;
  118. protected static BufferedImage ERROR_CATCH_IMAGE;
  119. protected static BufferedImage MESSAGE_THROW_IMAGE;
  120. protected static BufferedImage MESSAGE_CATCH_IMAGE;
  121. protected static BufferedImage SIGNAL_CATCH_IMAGE;
  122. protected static BufferedImage SIGNAL_THROW_IMAGE;
  123. protected int canvasWidth = -1;
  124. protected int canvasHeight = -1;
  125. protected int minX = -1;
  126. protected int minY = -1;
  127. protected BufferedImage processDiagram;
  128. protected Graphics2D g;
  129. protected FontMetrics fontMetrics;
  130. protected boolean closed;
  131. protected ClassLoader customClassLoader;
  132. protected String activityFontName = "Arial";
  133. protected String labelFontName = "Arial";
  134. /**
  135. * Creates an empty canvas with given width and height. Allows to specify minimal boundaries on the left and upper side of the canvas. This is useful for diagrams that have
  136. * white space there. Everything beneath these minimum values will be cropped. It's also possible to pass a specific font name and a class loader for the icon images.
  137. */
  138. public CustomProcessDiagramCanvas(int width, int height, int minX, int minY, String imageType, String activityFontName, String labelFontName, ClassLoader customClassLoader) {
  139. this.canvasWidth = width;
  140. this.canvasHeight = height;
  141. this.minX = minX;
  142. this.minY = minY;
  143. if (activityFontName != null) {
  144. this.activityFontName = activityFontName;
  145. }
  146. if (labelFontName != null) {
  147. this.labelFontName = labelFontName;
  148. }
  149. this.customClassLoader = customClassLoader;
  150. initialize(imageType);
  151. }
  152. /**
  153. * Creates an empty canvas with given width and height. Allows to specify minimal boundaries on the left and upper side of the canvas. This is useful for diagrams that have
  154. * white space there (eg Signavio). Everything beneath these minimum values will be cropped.
  155. *
  156. * @param minX
  157. * Hint that will be used when generating the image. Parts that fall below minX on the horizontal scale will be cropped.
  158. * @param minY
  159. * Hint that will be used when generating the image. Parts that fall below minX on the horizontal scale will be cropped.
  160. */
  161. public CustomProcessDiagramCanvas(int width, int height, int minX, int minY, String imageType) {
  162. this.canvasWidth = width;
  163. this.canvasHeight = height;
  164. this.minX = minX;
  165. this.minY = minY;
  166. initialize(imageType);
  167. }
  168. public void initialize(String imageType) {
  169. if ("png".equalsIgnoreCase(imageType)) {
  170. this.processDiagram = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_ARGB);
  171. } else {
  172. this.processDiagram = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_RGB);
  173. }
  174. this.g = processDiagram.createGraphics();
  175. if ("png".equalsIgnoreCase(imageType) == false) {
  176. this.g.setBackground(new Color(255, 255, 255, 0));
  177. this.g.clearRect(0, 0, canvasWidth, canvasHeight);
  178. }
  179. g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  180. g.setPaint(Color.black);
  181. Font font = new Font(activityFontName, Font.BOLD, FONT_SIZE);
  182. g.setFont(font);
  183. this.fontMetrics = g.getFontMetrics();
  184. LABEL_FONT = new Font(labelFontName, Font.ITALIC, 10);
  185. try {
  186. USERTASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/userTask.png", customClassLoader));
  187. SCRIPTTASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/scriptTask.png", customClassLoader));
  188. SERVICETASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/serviceTask.png", customClassLoader));
  189. RECEIVETASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/receiveTask.png", customClassLoader));
  190. SENDTASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/sendTask.png", customClassLoader));
  191. MANUALTASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/manualTask.png", customClassLoader));
  192. BUSINESS_RULE_TASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/businessRuleTask.png", customClassLoader));
  193. SHELL_TASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/shellTask.png", customClassLoader));
  194. CAMEL_TASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/camelTask.png", customClassLoader));
  195. MULE_TASK_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/muleTask.png", customClassLoader));
  196. TIMER_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/timer.png", customClassLoader));
  197. COMPENSATE_THROW_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/compensate-throw.png", customClassLoader));
  198. COMPENSATE_CATCH_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/compensate.png", customClassLoader));
  199. ERROR_THROW_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/error-throw.png", customClassLoader));
  200. ERROR_CATCH_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/error.png", customClassLoader));
  201. MESSAGE_THROW_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/message-throw.png", customClassLoader));
  202. MESSAGE_CATCH_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/message.png", customClassLoader));
  203. SIGNAL_THROW_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/signal-throw.png", customClassLoader));
  204. SIGNAL_CATCH_IMAGE = ImageIO.read(ReflectUtil.getResource("org/activiti/icons/signal.png", customClassLoader));
  205. } catch (IOException e) {
  206. LOGGER.warn("Could not load image for process diagram creation: {}", e.getMessage());
  207. }
  208. }
  209. /**
  210. * Generates an image of what currently is drawn on the canvas. Throws an {@link ActivitiException} when {@link #close()} is already called.
  211. */
  212. public InputStream generateImage(String imageType) {
  213. if (closed) {
  214. throw new ActivitiImageException("ProcessDiagramGenerator already closed");
  215. }
  216. ByteArrayOutputStream out = new ByteArrayOutputStream();
  217. try {
  218. // Try to remove white space
  219. minX = (minX <= 5) ? 5 : minX;
  220. minY = (minY <= 5) ? 5 : minY;
  221. BufferedImage imageToSerialize = processDiagram;
  222. if (minX >= 0 && minY >= 0) {
  223. imageToSerialize = processDiagram.getSubimage(minX - 5, minY - 5, canvasWidth - minX + 5, canvasHeight - minY + 5);
  224. }
  225. ImageIO.write(imageToSerialize, imageType, out);
  226. } catch (IOException e) {
  227. throw new ActivitiImageException("Error while generating process image", e);
  228. } finally {
  229. try {
  230. if (out != null) {
  231. out.close();
  232. }
  233. } catch (IOException ignore) {
  234. // Exception is silently ignored
  235. }
  236. }
  237. return new ByteArrayInputStream(out.toByteArray());
  238. }
  239. /**
  240. * Generates an image of what currently is drawn on the canvas. Throws an {@link ActivitiException} when {@link #close()} is already called.
  241. */
  242. public BufferedImage generateBufferedImage(String imageType) {
  243. if (closed) {
  244. throw new ActivitiImageException("ProcessDiagramGenerator already closed");
  245. }
  246. // Try to remove white space
  247. minX = (minX <= 5) ? 5 : minX;
  248. minY = (minY <= 5) ? 5 : minY;
  249. BufferedImage imageToSerialize = processDiagram;
  250. if (minX >= 0 && minY >= 0) {
  251. imageToSerialize = processDiagram.getSubimage(minX - 5, minY - 5, canvasWidth - minX + 5, canvasHeight - minY + 5);
  252. }
  253. return imageToSerialize;
  254. }
  255. /**
  256. * Closes the canvas which dissallows further drawing and releases graphical resources.
  257. */
  258. public void close() {
  259. g.dispose();
  260. closed = true;
  261. }
  262. public void drawNoneStartEvent(GraphicInfo graphicInfo) {
  263. drawStartEvent(graphicInfo, null, 1.0);
  264. }
  265. public void drawTimerStartEvent(GraphicInfo graphicInfo, double scaleFactor) {
  266. drawStartEvent(graphicInfo, TIMER_IMAGE, scaleFactor);
  267. }
  268. public void drawSignalStartEvent(GraphicInfo graphicInfo, double scaleFactor) {
  269. drawStartEvent(graphicInfo, SIGNAL_CATCH_IMAGE, scaleFactor);
  270. }
  271. public void drawMessageStartEvent(GraphicInfo graphicInfo, double scaleFactor) {
  272. drawStartEvent(graphicInfo, MESSAGE_CATCH_IMAGE, scaleFactor);
  273. }
  274. public void drawStartEvent(GraphicInfo graphicInfo, BufferedImage image, double scaleFactor) {
  275. Paint originalPaint = g.getPaint();
  276. g.setPaint(EVENT_COLOR);
  277. Ellipse2D circle = new Ellipse2D.Double(graphicInfo.getX(), graphicInfo.getY(), graphicInfo.getWidth(), graphicInfo.getHeight());
  278. g.fill(circle);
  279. g.setPaint(EVENT_BORDER_COLOR);
  280. g.draw(circle);
  281. g.setPaint(originalPaint);
  282. if (image != null) {
  283. // calculate coordinates to center image
  284. int imageX = (int) Math.round(graphicInfo.getX() + (graphicInfo.getWidth() / 2) - (image.getWidth() / 2 * scaleFactor));
  285. int imageY = (int) Math.round(graphicInfo.getY() + (graphicInfo.getHeight() / 2) - (image.getHeight() / 2 * scaleFactor));
  286. g.drawImage(image, imageX, imageY, (int) (image.getWidth() / scaleFactor), (int) (image.getHeight() / scaleFactor), null);
  287. }
  288. }
  289. public void drawNoneEndEvent(GraphicInfo graphicInfo, double scaleFactor) {
  290. Paint originalPaint = g.getPaint();
  291. Stroke originalStroke = g.getStroke();
  292. g.setPaint(EVENT_COLOR);
  293. Ellipse2D circle = new Ellipse2D.Double(graphicInfo.getX(), graphicInfo.getY(), graphicInfo.getWidth(), graphicInfo.getHeight());
  294. g.fill(circle);
  295. g.setPaint(EVENT_BORDER_COLOR);
  296. if (scaleFactor == 1.0) {
  297. g.setStroke(END_EVENT_STROKE);
  298. } else {
  299. g.setStroke(new BasicStroke(2.0f));
  300. }
  301. g.draw(circle);
  302. g.setStroke(originalStroke);
  303. g.setPaint(originalPaint);
  304. }
  305. public void drawErrorEndEvent(String name, GraphicInfo graphicInfo, double scaleFactor) {
  306. drawErrorEndEvent(graphicInfo, scaleFactor);
  307. if (scaleFactor == 1.0) {
  308. drawLabel(name, graphicInfo);
  309. }
  310. }
  311. public void drawErrorEndEvent(GraphicInfo graphicInfo, double scaleFactor) {
  312. drawNoneEndEvent(graphicInfo, scaleFactor);
  313. g.drawImage(ERROR_THROW_IMAGE, (int) (graphicInfo.getX() + (graphicInfo.getWidth() / 4)), (int) (graphicInfo.getY() + (graphicInfo.getHeight() / 4)),
  314. (int) (ERROR_THROW_IMAGE.getWidth() / scaleFactor), (int) (ERROR_THROW_IMAGE.getHeight() / scaleFactor), null);
  315. }
  316. public void drawErrorStartEvent(GraphicInfo graphicInfo, double scaleFactor) {
  317. drawNoneStartEvent(graphicInfo);
  318. g.drawImage(ERROR_CATCH_IMAGE, (int) (graphicInfo.getX() + (graphicInfo.getWidth() / 4)), (int) (graphicInfo.getY() + (graphicInfo.getHeight() / 4)),
  319. (int) (ERROR_CATCH_IMAGE.getWidth() / scaleFactor), (int) (ERROR_CATCH_IMAGE.getHeight() / scaleFactor), null);
  320. }
  321. public void drawCatchingEvent(GraphicInfo graphicInfo, boolean isInterrupting, BufferedImage image, String eventType, double scaleFactor) {
  322. // event circles
  323. Ellipse2D outerCircle = new Ellipse2D.Double(graphicInfo.getX(), graphicInfo.getY(), graphicInfo.getWidth(), graphicInfo.getHeight());
  324. int innerCircleSize = (int) (4 / scaleFactor);
  325. if (innerCircleSize == 0) {
  326. innerCircleSize = 1;
  327. }
  328. int innerCircleX = (int) graphicInfo.getX() + innerCircleSize;
  329. int innerCircleY = (int) graphicInfo.getY() + innerCircleSize;
  330. int innerCircleWidth = (int) graphicInfo.getWidth() - (2 * innerCircleSize);
  331. int innerCircleHeight = (int) graphicInfo.getHeight() - (2 * innerCircleSize);
  332. Ellipse2D innerCircle = new Ellipse2D.Double(innerCircleX, innerCircleY, innerCircleWidth, innerCircleHeight);
  333. Paint originalPaint = g.getPaint();
  334. Stroke originalStroke = g.getStroke();
  335. g.setPaint(EVENT_COLOR);
  336. g.fill(outerCircle);
  337. g.setPaint(EVENT_BORDER_COLOR);
  338. if (isInterrupting == false) {
  339. g.setStroke(NON_INTERRUPTING_EVENT_STROKE);
  340. }
  341. g.draw(outerCircle);
  342. g.setStroke(originalStroke);
  343. g.setPaint(originalPaint);
  344. g.draw(innerCircle);
  345. if (image != null) {
  346. // calculate coordinates to center image
  347. int imageX = (int) (graphicInfo.getX() + (graphicInfo.getWidth() / 2) - (image.getWidth() / 2 * scaleFactor));
  348. int imageY = (int) (graphicInfo.getY() + (graphicInfo.getHeight() / 2) - (image.getHeight() / 2 * scaleFactor));
  349. if (scaleFactor == 1.0 && "timer".equals(eventType)) {
  350. // move image one pixel to center timer image
  351. imageX++;
  352. imageY++;
  353. }
  354. g.drawImage(image, imageX, imageY, (int) (image.getWidth() / scaleFactor), (int) (image.getHeight() / scaleFactor), null);
  355. }
  356. }
  357. public void drawCatchingCompensateEvent(String name, GraphicInfo graphicInfo, boolean isInterrupting, double scaleFactor) {
  358. drawCatchingCompensateEvent(graphicInfo, isInterrupting, scaleFactor);
  359. drawLabel(name, graphicInfo);
  360. }
  361. public void drawCatchingCompensateEvent(GraphicInfo graphicInfo, boolean isInterrupting, double scaleFactor) {
  362. drawCatchingEvent(graphicInfo, isInterrupting, COMPENSATE_CATCH_IMAGE, "compensate", scaleFactor);
  363. }
  364. public void drawCatchingTimerEvent(String name, GraphicInfo graphicInfo, boolean isInterrupting, double scaleFactor) {
  365. drawCatchingTimerEvent(graphicInfo, isInterrupting, scaleFactor);
  366. drawLabel(name, graphicInfo);
  367. }
  368. public void drawCatchingTimerEvent(GraphicInfo graphicInfo, boolean isInterrupting, double scaleFactor) {
  369. drawCatchingEvent(graphicInfo, isInterrupting, TIMER_IMAGE, "timer", scaleFactor);
  370. }
  371. public void drawCatchingErrorEvent(String name, GraphicInfo graphicInfo, boolean isInterrupting, double scaleFactor) {
  372. drawCatchingErrorEvent(graphicInfo, isInterrupting, scaleFactor);
  373. drawLabel(name, graphicInfo);
  374. }
  375. public void drawCatchingErrorEvent(GraphicInfo graphicInfo, boolean isInterrupting, double scaleFactor) {
  376. drawCatchingEvent(graphicInfo, isInterrupting, ERROR_CATCH_IMAGE, "error", scaleFactor);
  377. }
  378. public void drawCatchingSignalEvent(String name, GraphicInfo graphicInfo, boolean isInterrupting, double scaleFactor) {
  379. drawCatchingSignalEvent(graphicInfo, isInterrupting, scaleFactor);
  380. drawLabel(name, graphicInfo);
  381. }
  382. public void drawCatchingSignalEvent(GraphicInfo graphicInfo, boolean isInterrupting, double scaleFactor) {
  383. drawCatchingEvent(graphicInfo, isInterrupting, SIGNAL_CATCH_IMAGE, "signal", scaleFactor);
  384. }
  385. public void drawCatchingMessageEvent(GraphicInfo graphicInfo, boolean isInterrupting, double scaleFactor) {
  386. drawCatchingEvent(graphicInfo, isInterrupting, MESSAGE_CATCH_IMAGE, "message", scaleFactor);
  387. }
  388. public void drawCatchingMessageEvent(String name, GraphicInfo graphicInfo, boolean isInterrupting, double scaleFactor) {
  389. drawCatchingEvent(graphicInfo, isInterrupting, MESSAGE_CATCH_IMAGE, "message", scaleFactor);
  390. drawLabel(name, graphicInfo);
  391. }
  392. public void drawThrowingCompensateEvent(GraphicInfo graphicInfo, double scaleFactor) {
  393. drawCatchingEvent(graphicInfo, true, COMPENSATE_THROW_IMAGE, "compensate", scaleFactor);
  394. }
  395. public void drawThrowingSignalEvent(GraphicInfo graphicInfo, double scaleFactor) {
  396. drawCatchingEvent(graphicInfo, true, SIGNAL_THROW_IMAGE, "signal", scaleFactor);
  397. }
  398. public void drawThrowingNoneEvent(GraphicInfo graphicInfo, double scaleFactor) {
  399. drawCatchingEvent(graphicInfo, true, null, "none", scaleFactor);
  400. }
  401. public void drawSequenceflow(int srcX, int srcY, int targetX, int targetY, boolean conditional, double scaleFactor) {
  402. drawSequenceflow(srcX, srcY, targetX, targetY, conditional, false, scaleFactor);
  403. }
  404. public void drawSequenceflow(int srcX, int srcY, int targetX, int targetY, boolean conditional, boolean highLighted, double scaleFactor) {
  405. Paint originalPaint = g.getPaint();
  406. if (highLighted) {
  407. g.setPaint(HIGHLIGHT_COLOR);
  408. }
  409. Line2D.Double line = new Line2D.Double(srcX, srcY, targetX, targetY);
  410. g.draw(line);
  411. drawArrowHead(line, scaleFactor);
  412. if (conditional) {
  413. drawConditionalSequenceFlowIndicator(line, scaleFactor);
  414. }
  415. if (highLighted) {
  416. g.setPaint(originalPaint);
  417. }
  418. }
  419. public void drawAssociation(int[] xPoints, int[] yPoints, AssociationDirection associationDirection, boolean highLighted, double scaleFactor) {
  420. boolean conditional = false, isDefault = false;
  421. drawConnection(xPoints, yPoints, conditional, isDefault, "association", associationDirection, highLighted, scaleFactor);
  422. }
  423. public void drawSequenceflow(int[] xPoints, int[] yPoints, boolean conditional, boolean isDefault, boolean highLighted, double scaleFactor) {
  424. drawConnection(xPoints, yPoints, conditional, isDefault, "sequenceFlow", AssociationDirection.ONE, highLighted, scaleFactor);
  425. }
  426. public void drawConnection(int[] xPoints, int[] yPoints, boolean conditional, boolean isDefault, String connectionType, AssociationDirection associationDirection,
  427. boolean highLighted, double scaleFactor) {
  428. Paint originalPaint = g.getPaint();
  429. Stroke originalStroke = g.getStroke();
  430. g.setPaint(CONNECTION_COLOR);
  431. if (connectionType.equals("association")) {
  432. g.setStroke(ASSOCIATION_STROKE);
  433. } else if (highLighted) {
  434. g.setPaint(HIGHLIGHT_COLOR);
  435. g.setStroke(HIGHLIGHT_FLOW_STROKE);
  436. }
  437. for (int i = 1; i < xPoints.length; i++) {
  438. Integer sourceX = xPoints[i - 1];
  439. Integer sourceY = yPoints[i - 1];
  440. Integer targetX = xPoints[i];
  441. Integer targetY = yPoints[i];
  442. Line2D.Double line = new Line2D.Double(sourceX, sourceY, targetX, targetY);
  443. g.draw(line);
  444. }
  445. if (isDefault) {
  446. Line2D.Double line = new Line2D.Double(xPoints[0], yPoints[0], xPoints[1], yPoints[1]);
  447. drawDefaultSequenceFlowIndicator(line, scaleFactor);
  448. }
  449. if (conditional) {
  450. Line2D.Double line = new Line2D.Double(xPoints[0], yPoints[0], xPoints[1], yPoints[1]);
  451. drawConditionalSequenceFlowIndicator(line, scaleFactor);
  452. }
  453. if (associationDirection.equals(AssociationDirection.ONE) || associationDirection.equals(AssociationDirection.BOTH)) {
  454. Line2D.Double line = new Line2D.Double(xPoints[xPoints.length - 2], yPoints[xPoints.length - 2], xPoints[xPoints.length - 1], yPoints[xPoints.length - 1]);
  455. drawArrowHead(line, scaleFactor);
  456. }
  457. if (associationDirection.equals(AssociationDirection.BOTH)) {
  458. Line2D.Double line = new Line2D.Double(xPoints[1], yPoints[1], xPoints[0], yPoints[0]);
  459. drawArrowHead(line, scaleFactor);
  460. }
  461. g.setPaint(originalPaint);
  462. g.setStroke(originalStroke);
  463. }
  464. public void drawSequenceflowWithoutArrow(int srcX, int srcY, int targetX, int targetY, boolean conditional, double scaleFactor) {
  465. drawSequenceflowWithoutArrow(srcX, srcY, targetX, targetY, conditional, false, scaleFactor);
  466. }
  467. public void drawSequenceflowWithoutArrow(int srcX, int srcY, int targetX, int targetY, boolean conditional, boolean highLighted, double scaleFactor) {
  468. Paint originalPaint = g.getPaint();
  469. if (highLighted) {
  470. g.setPaint(HIGHLIGHT_COLOR);
  471. }
  472. Line2D.Double line = new Line2D.Double(srcX, srcY, targetX, targetY);
  473. g.draw(line);
  474. if (conditional) {
  475. drawConditionalSequenceFlowIndicator(line, scaleFactor);
  476. }
  477. if (highLighted) {
  478. g.setPaint(originalPaint);
  479. }
  480. }
  481. public void drawArrowHead(Line2D.Double line, double scaleFactor) {
  482. int doubleArrowWidth = (int) (2 * ARROW_WIDTH / scaleFactor);
  483. if (doubleArrowWidth == 0) {
  484. doubleArrowWidth = 2;
  485. }
  486. Polygon arrowHead = new Polygon();
  487. arrowHead.addPoint(0, 0);
  488. int arrowHeadPoint = (int) (-ARROW_WIDTH / scaleFactor);
  489. if (arrowHeadPoint == 0) {
  490. arrowHeadPoint = -1;
  491. }
  492. arrowHead.addPoint(arrowHeadPoint, -doubleArrowWidth);
  493. arrowHeadPoint = (int) (ARROW_WIDTH / scaleFactor);
  494. if (arrowHeadPoint == 0) {
  495. arrowHeadPoint = 1;
  496. }
  497. arrowHead.addPoint(arrowHeadPoint, -doubleArrowWidth);
  498. AffineTransform transformation = new AffineTransform();
  499. transformation.setToIdentity();
  500. double angle = Math.atan2(line.y2 - line.y1, line.x2 - line.x1);
  501. transformation.translate(line.x2, line.y2);
  502. transformation.rotate((angle - Math.PI / 2d));
  503. AffineTransform originalTransformation = g.getTransform();
  504. g.setTransform(transformation);
  505. g.fill(arrowHead);
  506. g.setTransform(originalTransformation);
  507. }
  508. public void drawDefaultSequenceFlowIndicator(Line2D.Double line, double scaleFactor) {
  509. double length = DEFAULT_INDICATOR_WIDTH / scaleFactor, halfOfLength = length / 2, f = 8;
  510. Line2D.Double defaultIndicator = new Line2D.Double(-halfOfLength, 0, halfOfLength, 0);
  511. double angle = Math.atan2(line.y2 - line.y1, line.x2 - line.x1);
  512. double dx = f * Math.cos(angle), dy = f * Math.sin(angle), x1 = line.x1 + dx, y1 = line.y1 + dy;
  513. AffineTransform transformation = new AffineTransform();
  514. transformation.setToIdentity();
  515. transformation.translate(x1, y1);
  516. transformation.rotate((angle - 3 * Math.PI / 4));
  517. AffineTransform originalTransformation = g.getTransform();
  518. g.setTransform(transformation);
  519. g.draw(defaultIndicator);
  520. g.setTransform(originalTransformation);
  521. }
  522. public void drawConditionalSequenceFlowIndicator(Line2D.Double line, double scaleFactor) {
  523. if (scaleFactor > 1.0) {
  524. return;
  525. }
  526. int horizontal = (int) (CONDITIONAL_INDICATOR_WIDTH * 0.7);
  527. int halfOfHorizontal = horizontal / 2;
  528. int halfOfVertical = CONDITIONAL_INDICATOR_WIDTH / 2;
  529. Polygon conditionalIndicator = new Polygon();
  530. conditionalIndicator.addPoint(0, 0);
  531. conditionalIndicator.addPoint(-halfOfHorizontal, halfOfVertical);
  532. conditionalIndicator.addPoint(0, CONDITIONAL_INDICATOR_WIDTH);
  533. conditionalIndicator.addPoint(halfOfHorizontal, halfOfVertical);
  534. AffineTransform transformation = new AffineTransform();
  535. transformation.setToIdentity();
  536. double angle = Math.atan2(line.y2 - line.y1, line.x2 - line.x1);
  537. transformation.translate(line.x1, line.y1);
  538. transformation.rotate((angle - Math.PI / 2d));
  539. AffineTransform originalTransformation = g.getTransform();
  540. g.setTransform(transformation);
  541. g.draw(conditionalIndicator);
  542. Paint originalPaint = g.getPaint();
  543. g.setPaint(CONDITIONAL_INDICATOR_COLOR);
  544. g.fill(conditionalIndicator);
  545. g.setPaint(originalPaint);
  546. g.setTransform(originalTransformation);
  547. }
  548. public void drawTask(BufferedImage icon, String name, GraphicInfo graphicInfo, double scaleFactor) {
  549. drawTask(name, graphicInfo);
  550. g.drawImage(icon, (int) (graphicInfo.getX() + ICON_PADDING / scaleFactor), (int) (graphicInfo.getY() + ICON_PADDING / scaleFactor), (int) (icon.getWidth() / scaleFactor),
  551. (int) (icon.getHeight() / scaleFactor), null);
  552. }
  553. public void drawTask(String name, GraphicInfo graphicInfo) {
  554. drawTask(name, graphicInfo, false);
  555. }
  556. public void drawPoolOrLane(String name, GraphicInfo graphicInfo) {
  557. int x = (int) graphicInfo.getX();
  558. int y = (int) graphicInfo.getY();
  559. int width = (int) graphicInfo.getWidth();
  560. int height = (int) graphicInfo.getHeight();
  561. g.drawRect(x, y, width, height);
  562. // Add the name as text, vertical
  563. if (name != null && name.length() > 0) {
  564. // Include some padding
  565. int availableTextSpace = height - 6;
  566. // Create rotation for derived font
  567. AffineTransform transformation = new AffineTransform();
  568. transformation.setToIdentity();
  569. transformation.rotate(270 * Math.PI / 180);
  570. Font currentFont = g.getFont();
  571. Font theDerivedFont = currentFont.deriveFont(transformation);
  572. g.setFont(theDerivedFont);
  573. String truncated = fitTextToWidth(name, availableTextSpace);
  574. int realWidth = fontMetrics.stringWidth(truncated);
  575. g.drawString(truncated, x + 2 + fontMetrics.getHeight(), 3 + y + availableTextSpace - (availableTextSpace - realWidth) / 2);
  576. g.setFont(currentFont);
  577. }
  578. }
  579. protected void drawTask(String name, GraphicInfo graphicInfo, boolean thickBorder) {
  580. Paint originalPaint = g.getPaint();
  581. int x = (int) graphicInfo.getX();
  582. int y = (int) graphicInfo.getY();
  583. int width = (int) graphicInfo.getWidth();
  584. int height = (int) graphicInfo.getHeight();
  585. // Create a new gradient paint for every task box, gradient depends on x and y and is not relative
  586. g.setPaint(TASK_BOX_COLOR);
  587. int arcR = 6;
  588. if (thickBorder) {
  589. arcR = 3;
  590. }
  591. // shape
  592. RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, height, arcR, arcR);
  593. g.fill(rect);
  594. g.setPaint(TASK_BORDER_COLOR);
  595. if (thickBorder) {
  596. Stroke originalStroke = g.getStroke();
  597. g.setStroke(THICK_TASK_BORDER_STROKE);
  598. g.draw(rect);
  599. g.setStroke(originalStroke);
  600. } else {
  601. g.draw(rect);
  602. }
  603. g.setPaint(originalPaint);
  604. // text
  605. if (name != null && name.length() > 0) {
  606. int boxWidth = width - (2 * TEXT_PADDING);
  607. int boxHeight = height - 16 - ICON_PADDING - ICON_PADDING - MARKER_WIDTH - 2 - 2;
  608. int boxX = x + width / 2 - boxWidth / 2;
  609. int boxY = y + height / 2 - boxHeight / 2 + ICON_PADDING + ICON_PADDING - 2 - 2;
  610. drawMultilineCentredText(name, boxX, boxY, boxWidth, boxHeight);
  611. }
  612. }
  613. protected void drawMultilineCentredText(String text, int x, int y, int boxWidth, int boxHeight) {
  614. drawMultilineText(text, x, y, boxWidth, boxHeight, true);
  615. }
  616. protected void drawMultilineAnnotationText(String text, int x, int y, int boxWidth, int boxHeight) {
  617. drawMultilineText(text, x, y, boxWidth, boxHeight, false);
  618. }
  619. protected void drawMultilineText(String text, int x, int y, int boxWidth, int boxHeight, boolean centered) {
  620. // Create an attributed string based in input text
  621. AttributedString attributedString = new AttributedString(text);
  622. attributedString.addAttribute(TextAttribute.FONT, g.getFont());
  623. attributedString.addAttribute(TextAttribute.FOREGROUND, Color.black);
  624. AttributedCharacterIterator characterIterator = attributedString.getIterator();
  625. int currentHeight = 0;
  626. // Prepare a list of lines of text we'll be drawing
  627. List<TextLayout> layouts = new ArrayList<TextLayout>();
  628. String lastLine = null;
  629. LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, g.getFontRenderContext());
  630. TextLayout layout = null;
  631. while (measurer.getPosition() < characterIterator.getEndIndex() && currentHeight <= boxHeight) {
  632. int previousPosition = measurer.getPosition();
  633. // Request next layout
  634. layout = measurer.nextLayout(boxWidth);
  635. int height = ((Float) (layout.getDescent() + layout.getAscent() + layout.getLeading())).intValue();
  636. if (currentHeight + height > boxHeight) {
  637. // The line we're about to add should NOT be added anymore, append three dots to previous one instead
  638. // to indicate more text is truncated
  639. if (!layouts.isEmpty()) {
  640. layouts.remove(layouts.size() - 1);
  641. if (lastLine.length() >= 4) {
  642. lastLine = lastLine.substring(0, lastLine.length() - 4) + "...";
  643. }
  644. layouts.add(new TextLayout(lastLine, g.getFont(), g.getFontRenderContext()));
  645. }
  646. } else {
  647. layouts.add(layout);
  648. lastLine = text.substring(previousPosition, measurer.getPosition());
  649. currentHeight += height;
  650. }
  651. }
  652. int currentY = y + (centered ? ((boxHeight - currentHeight) / 2) : 0);
  653. int currentX = 0;
  654. // Actually draw the lines
  655. for (TextLayout textLayout : layouts) {
  656. currentY += textLayout.getAscent();
  657. currentX = x + (centered ? ((boxWidth - ((Double) textLayout.getBounds().getWidth()).intValue()) / 2) : 0);
  658. textLayout.draw(g, currentX, currentY);
  659. currentY += textLayout.getDescent() + textLayout.getLeading();
  660. }
  661. }
  662. protected String fitTextToWidth(String original, int width) {
  663. String text = original;
  664. // remove length for "..."
  665. int maxWidth = width - 10;
  666. while (fontMetrics.stringWidth(text + "...") > maxWidth && text.length() > 0) {
  667. text = text.substring(0, text.length() - 1);
  668. }
  669. if (!text.equals(original)) {
  670. text = text + "...";
  671. }
  672. return text;
  673. }
  674. public void drawUserTask(String name, GraphicInfo graphicInfo, double scaleFactor) {
  675. drawTask(USERTASK_IMAGE, name, graphicInfo, scaleFactor);
  676. }
  677. public void drawScriptTask(String name, GraphicInfo graphicInfo, double scaleFactor) {
  678. drawTask(SCRIPTTASK_IMAGE, name, graphicInfo, scaleFactor);
  679. }
  680. public void drawServiceTask(String name, GraphicInfo graphicInfo, double scaleFactor) {
  681. drawTask(SERVICETASK_IMAGE, name, graphicInfo, scaleFactor);
  682. }
  683. public void drawReceiveTask(String name, GraphicInfo graphicInfo, double scaleFactor) {
  684. drawTask(RECEIVETASK_IMAGE, name, graphicInfo, scaleFactor);
  685. }
  686. public void drawSendTask(String name, GraphicInfo graphicInfo, double scaleFactor) {
  687. drawTask(SENDTASK_IMAGE, name, graphicInfo, scaleFactor);
  688. }
  689. public void drawManualTask(String name, GraphicInfo graphicInfo, double scaleFactor) {
  690. drawTask(MANUALTASK_IMAGE, name, graphicInfo, scaleFactor);
  691. }
  692. public void drawBusinessRuleTask(String name, GraphicInfo graphicInfo, double scaleFactor) {
  693. drawTask(BUSINESS_RULE_TASK_IMAGE, name, graphicInfo, scaleFactor);
  694. }
  695. public void drawCamelTask(String name, GraphicInfo graphicInfo, double scaleFactor) {
  696. drawTask(CAMEL_TASK_IMAGE, name, graphicInfo, scaleFactor);
  697. }
  698. public void drawMuleTask(String name, GraphicInfo graphicInfo, double scaleFactor) {
  699. drawTask(MULE_TASK_IMAGE, name, graphicInfo, scaleFactor);
  700. }
  701. public void drawExpandedSubProcess(String name, GraphicInfo graphicInfo, Boolean isTriggeredByEvent, double scaleFactor) {
  702. RoundRectangle2D rect = new RoundRectangle2D.Double(graphicInfo.getX(), graphicInfo.getY(), graphicInfo.getWidth(), graphicInfo.getHeight(), 8, 8);
  703. // Use different stroke (dashed)
  704. if (isTriggeredByEvent) {
  705. Stroke originalStroke = g.getStroke();
  706. g.setStroke(EVENT_SUBPROCESS_STROKE);
  707. g.draw(rect);
  708. g.setStroke(originalStroke);
  709. } else {
  710. Paint originalPaint = g.getPaint();
  711. g.setPaint(SUBPROCESS_BOX_COLOR);
  712. g.fill(rect);
  713. g.setPaint(SUBPROCESS_BORDER_COLOR);
  714. g.draw(rect);
  715. g.setPaint(originalPaint);
  716. }
  717. if (scaleFactor == 1.0 && name != null && !name.isEmpty()) {
  718. String text = fitTextToWidth(name, (int) graphicInfo.getWidth());
  719. g.drawString(text, (int) graphicInfo.getX() + 10, (int) graphicInfo.getY() + 15);
  720. }
  721. }
  722. public void drawCollapsedSubProcess(String name, GraphicInfo graphicInfo, Boolean isTriggeredByEvent) {
  723. drawCollapsedTask(name, graphicInfo, false);
  724. }
  725. public void drawCollapsedCallActivity(String name, GraphicInfo graphicInfo) {
  726. drawCollapsedTask(name, graphicInfo, true);
  727. }
  728. protected void drawCollapsedTask(String name, GraphicInfo graphicInfo, boolean thickBorder) {
  729. // The collapsed marker is now visualized separately
  730. drawTask(name, graphicInfo, thickBorder);
  731. }
  732. public void drawCollapsedMarker(int x, int y, int width, int height) {
  733. // rectangle
  734. int rectangleWidth = MARKER_WIDTH;
  735. int rectangleHeight = MARKER_WIDTH;
  736. Rectangle rect = new Rectangle(x + (width - rectangleWidth) / 2, y + height - rectangleHeight - 3, rectangleWidth, rectangleHeight);
  737. g.draw(rect);
  738. // plus inside rectangle
  739. Line2D.Double line = new Line2D.Double(rect.getCenterX(), rect.getY() + 2, rect.getCenterX(), rect.getMaxY() - 2);
  740. g.draw(line);
  741. line = new Line2D.Double(rect.getMinX() + 2, rect.getCenterY(), rect.getMaxX() - 2, rect.getCenterY());
  742. g.draw(line);
  743. }
  744. public void drawActivityMarkers(int x, int y, int width, int height, boolean multiInstanceSequential, boolean multiInstanceParallel, boolean collapsed) {
  745. if (collapsed) {
  746. if (!multiInstanceSequential && !multiInstanceParallel) {
  747. drawCollapsedMarker(x, y, width, height);
  748. } else {
  749. drawCollapsedMarker(x - MARKER_WIDTH / 2 - 2, y, width, height);
  750. if (multiInstanceSequential) {
  751. drawMultiInstanceMarker(true, x + MARKER_WIDTH / 2 + 2, y, width, height);
  752. } else {
  753. drawMultiInstanceMarker(false, x + MARKER_WIDTH / 2 + 2, y, width, height);
  754. }
  755. }
  756. } else {
  757. if (multiInstanceSequential) {
  758. drawMultiInstanceMarker(true, x, y, width, height);
  759. } else if (multiInstanceParallel) {
  760. drawMultiInstanceMarker(false, x, y, width, height);
  761. }
  762. }
  763. }
  764. public void drawGateway(GraphicInfo graphicInfo) {
  765. Polygon rhombus = new Polygon();
  766. int x = (int) graphicInfo.getX();
  767. int y = (int) graphicInfo.getY();
  768. int width = (int) graphicInfo.getWidth();
  769. int height = (int) graphicInfo.getHeight();
  770. rhombus.addPoint(x, y + (height / 2));
  771. rhombus.addPoint(x + (width / 2), y + height);
  772. rhombus.addPoint(x + width, y + (height / 2));
  773. rhombus.addPoint(x + (width / 2), y);
  774. g.draw(rhombus);
  775. }
  776. public void drawParallelGateway(GraphicInfo graphicInfo, double scaleFactor) {
  777. // rhombus
  778. drawGateway(graphicInfo);
  779. int x = (int) graphicInfo.getX();
  780. int y = (int) graphicInfo.getY();
  781. int width = (int) graphicInfo.getWidth();
  782. int height = (int) graphicInfo.getHeight();
  783. if (scaleFactor == 1.0) {
  784. // plus inside rhombus
  785. Stroke orginalStroke = g.getStroke();
  786. g.setStroke(GATEWAY_TYPE_STROKE);
  787. Line2D.Double line = new Line2D.Double(x + 10, y + height / 2, x + width - 10, y + height / 2); // horizontal
  788. g.draw(line);
  789. line = new Line2D.Double(x + width / 2, y + height - 10, x + width / 2, y + 10); // vertical
  790. g.draw(line);
  791. g.setStroke(orginalStroke);
  792. }
  793. }
  794. public void drawExclusiveGateway(GraphicInfo graphicInfo, double scaleFactor) {
  795. // rhombus
  796. drawGateway(graphicInfo);
  797. int x = (int) graphicInfo.getX();
  798. int y = (int) graphicInfo.getY();
  799. int width = (int) graphicInfo.getWidth();
  800. int height = (int) graphicInfo.getHeight();
  801. int quarterWidth = width / 4;
  802. int quarterHeight = height / 4;
  803. if (scaleFactor == 1.0) {
  804. // X inside rhombus
  805. Stroke orginalStroke = g.getStroke();
  806. g.setStroke(GATEWAY_TYPE_STROKE);
  807. Line2D.Double line = new Line2D.Double(x + quarterWidth + 3, y + quarterHeight + 3, x + 3 * quarterWidth - 3, y + 3 * quarterHeight - 3);
  808. g.draw(line);
  809. line = new Line2D.Double(x + quarterWidth + 3, y + 3 * quarterHeight - 3, x + 3 * quarterWidth - 3, y + quarterHeight + 3);
  810. g.draw(line);
  811. g.setStroke(orginalStroke);
  812. }
  813. }
  814. public void drawInclusiveGateway(GraphicInfo graphicInfo, double scaleFactor) {
  815. // rhombus
  816. drawGateway(graphicInfo);
  817. int x = (int) graphicInfo.getX();
  818. int y = (int) graphicInfo.getY();
  819. int width = (int) graphicInfo.getWidth();
  820. int height = (int) graphicInfo.getHeight();
  821. int diameter = width / 2;
  822. if (scaleFactor == 1.0) {
  823. // circle inside rhombus
  824. Stroke orginalStroke = g.getStroke();
  825. g.setStroke(GATEWAY_TYPE_STROKE);
  826. Ellipse2D.Double circle = new Ellipse2D.Double(((width - diameter) / 2) + x, ((height - diameter) / 2) + y, diameter, diameter);
  827. g.draw(circle);
  828. g.setStroke(orginalStroke);
  829. }
  830. }
  831. public void drawEventBasedGateway(GraphicInfo graphicInfo, double scaleFactor) {
  832. // rhombus
  833. drawGateway(graphicInfo);
  834. if (scaleFactor == 1.0) {
  835. int x = (int) graphicInfo.getX();
  836. int y = (int) graphicInfo.getY();
  837. int width = (int) graphicInfo.getWidth();
  838. int height = (int) graphicInfo.getHeight();
  839. double scale = .6;
  840. GraphicInfo eventInfo = new GraphicInfo();
  841. eventInfo.setX(x + width * (1 - scale) / 2);
  842. eventInfo.setY(y + height * (1 - scale) / 2);
  843. eventInfo.setWidth(width * scale);
  844. eventInfo.setHeight(height * scale);
  845. drawCatchingEvent(eventInfo, true, null, "eventGateway", scaleFactor);
  846. double r = width / 6.;
  847. // create pentagon (coords with respect to center)
  848. int topX = (int) (.95 * r); // top right corner
  849. int topY = (int) (-.31 * r);
  850. int bottomX = (int) (.59 * r); // bottom right corner
  851. int bottomY = (int) (.81 * r);
  852. int[] xPoints = new int[] { 0, topX, bottomX, -bottomX, -topX };
  853. int[] yPoints = new int[] { -(int) r, topY, bottomY, bottomY, topY };
  854. Polygon pentagon = new Polygon(xPoints, yPoints, 5);
  855. pentagon.translate(x + width / 2, y + width / 2);
  856. // draw
  857. g.drawPolygon(pentagon);
  858. }
  859. }
  860. public void drawMultiInstanceMarker(boolean sequential, int x, int y, int width, int height) {
  861. int rectangleWidth = MARKER_WIDTH;
  862. int rectangleHeight = MARKER_WIDTH;
  863. int lineX = x + (width - rectangleWidth) / 2;
  864. int lineY = y + height - rectangleHeight - 3;
  865. Stroke orginalStroke = g.getStroke();
  866. g.setStroke(MULTI_INSTANCE_STROKE);
  867. if (sequential) {
  868. g.draw(new Line2D.Double(lineX, lineY, lineX + rectangleWidth, lineY));
  869. g.draw(new Line2D.Double(lineX, lineY + rectangleHeight / 2, lineX + rectangleWidth, lineY + rectangleHeight / 2));
  870. g.draw(new Line2D.Double(lineX, lineY + rectangleHeight, lineX + rectangleWidth, lineY + rectangleHeight));
  871. } else {
  872. g.draw(new Line2D.Double(lineX, lineY, lineX, lineY + rectangleHeight));
  873. g.draw(new Line2D.Double(lineX + rectangleWidth / 2, lineY, lineX + rectangleWidth / 2, lineY + rectangleHeight));
  874. g.draw(new Line2D.Double(lineX + rectangleWidth, lineY, lineX + rectangleWidth, lineY + rectangleHeight));
  875. }
  876. g.setStroke(orginalStroke);
  877. }
  878. public void drawHighLight(int x, int y, int width, int height) {
  879. Paint originalPaint = g.getPaint();
  880. Stroke originalStroke = g.getStroke();
  881. g.setPaint(HIGHLIGHT_COLOR);
  882. g.setStroke(THICK_TASK_BORDER_STROKE);
  883. RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, height, 20, 20);
  884. g.draw(rect);
  885. g.setPaint(originalPaint);
  886. g.setStroke(originalStroke);
  887. }
  888. public void drawTextAnnotation(String text, GraphicInfo graphicInfo) {
  889. int x = (int) graphicInfo.getX();
  890. int y = (int) graphicInfo.getY();
  891. int width = (int) graphicInfo.getWidth();
  892. int height = (int) graphicInfo.getHeight();
  893. Font originalFont = g.getFont();
  894. Stroke originalStroke = g.getStroke();
  895. g.setFont(ANNOTATION_FONT);
  896. Path2D path = new Path2D.Double();
  897. x += .5;
  898. int lineLength = 18;
  899. path.moveTo(x + lineLength, y);
  900. path.lineTo(x, y);
  901. path.lineTo(x, y + height);
  902. path.lineTo(x + lineLength, y + height);
  903. path.lineTo(x + lineLength, y + height - 1);
  904. path.lineTo(x + 1, y + height - 1);
  905. path.lineTo(x + 1, y + 1);
  906. path.lineTo(x + lineLength, y + 1);
  907. path.closePath();
  908. g.draw(path);
  909. int boxWidth = width - (2 * ANNOTATION_TEXT_PADDING);
  910. int boxHeight = height - (2 * ANNOTATION_TEXT_PADDING);
  911. int boxX = x + width / 2 - boxWidth / 2;
  912. int boxY = y + height / 2 - boxHeight / 2;
  913. if (text != null && text.isEmpty() == false) {
  914. drawMultilineAnnotationText(text, boxX, boxY, boxWidth, boxHeight);
  915. }
  916. // restore originals
  917. g.setFont(originalFont);
  918. g.setStroke(originalStroke);
  919. }
  920. public void drawLabel(String text, GraphicInfo graphicInfo) {
  921. drawLabel(text, graphicInfo, true);
  922. }
  923. public void drawLabel(String text, GraphicInfo graphicInfo, boolean centered) {
  924. float interline = 1.0f;
  925. // text
  926. if (text != null && text.length() > 0) {
  927. Paint originalPaint = g.getPaint();
  928. Font originalFont = g.getFont();
  929. g.setPaint(LABEL_COLOR);
  930. g.setFont(LABEL_FONT);
  931. int wrapWidth = 100;
  932. int textY = (int) (graphicInfo.getY() + graphicInfo.getHeight());
  933. // TODO: use drawMultilineText()
  934. AttributedString as = new AttributedString(text);
  935. as.addAttribute(TextAttribute.FOREGROUND, g.getPaint());
  936. as.addAttribute(TextAttribute.FONT, g.getFont());
  937. AttributedCharacterIterator aci = as.getIterator();
  938. FontRenderContext frc = new FontRenderContext(null, true, false);
  939. LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
  940. while (lbm.getPosition() < text.length()) {
  941. TextLayout tl = lbm.nextLayout(wrapWidth);
  942. textY += tl.getAscent();
  943. Rectangle2D bb = tl.getBounds();
  944. double tX = graphicInfo.getX();
  945. if (centered) {
  946. tX += (int) (graphicInfo.getWidth() / 2 - bb.getWidth() / 2);
  947. }
  948. tl.draw(g, (float) tX, textY);
  949. textY += tl.getDescent() + tl.getLeading() + (interline - 1.0f) * tl.getAscent();
  950. }
  951. // restore originals
  952. g.setFont(originalFont);
  953. g.setPaint(originalPaint);
  954. }
  955. }
  956. /**
  957. * This method makes coordinates of connection flow better.
  958. *
  959. * @param sourceShapeType
  960. * @param targetShapeType
  961. * @param sourceGraphicInfo
  962. * @param targetGraphicInfo
  963. * @param graphicInfoList
  964. */
  965. public List<GraphicInfo> connectionPerfectionizer(SHAPE_TYPE sourceShapeType, SHAPE_TYPE targetShapeType, GraphicInfo sourceGraphicInfo, GraphicInfo targetGraphicInfo,
  966. List<GraphicInfo> graphicInfoList) {
  967. Shape shapeFirst = createShape(sourceShapeType, sourceGraphicInfo);
  968. Shape shapeLast = createShape(targetShapeType, targetGraphicInfo);
  969. if (graphicInfoList != null && graphicInfoList.size() > 0) {
  970. GraphicInfo graphicInfoFirst = graphicInfoList.get(0);
  971. GraphicInfo graphicInfoLast = graphicInfoList.get(graphicInfoList.size() - 1);
  972. if (shapeFirst != null) {
  973. graphicInfoFirst.setX(shapeFirst.getBounds2D().getCenterX());
  974. graphicInfoFirst.setY(shapeFirst.getBounds2D().getCenterY());
  975. }
  976. if (shapeLast != null) {
  977. graphicInfoLast.setX(shapeLast.getBounds2D().getCenterX());
  978. graphicInfoLast.setY(shapeLast.getBounds2D().getCenterY());
  979. }
  980. Point p = null;
  981. if (shapeFirst != null) {
  982. Line2D.Double lineFirst = new Line2D.Double(graphicInfoFirst.getX(), graphicInfoFirst.getY(), graphicInfoList.get(1).getX(), graphicInfoList.get(1).getY());
  983. p = getIntersection(shapeFirst, lineFirst);
  984. if (p != null) {
  985. graphicInfoFirst.setX(p.getX());
  986. graphicInfoFirst.setY(p.getY());
  987. }
  988. }
  989. if (shapeLast != null) {
  990. Line2D.Double lineLast = new Line2D.Double(graphicInfoLast.getX(), graphicInfoLast.getY(), graphicInfoList.get(graphicInfoList.size() - 2).getX(),
  991. graphicInfoList.get(graphicInfoList.size() - 2).getY());
  992. p = getIntersection(shapeLast, lineLast);
  993. if (p != null) {
  994. graphicInfoLast.setX(p.getX());
  995. graphicInfoLast.setY(p.getY());
  996. }
  997. }
  998. }
  999. return graphicInfoList;
  1000. }
  1001. /**
  1002. * This method creates shape by type and coordinates.
  1003. *
  1004. * @param shapeType
  1005. * @param graphicInfo
  1006. * @return Shape
  1007. */
  1008. private static Shape createShape(SHAPE_TYPE shapeType, GraphicInfo graphicInfo) {
  1009. if (SHAPE_TYPE.Rectangle.equals(shapeType)) {
  1010. // source is rectangle
  1011. return new Rectangle2D.Double(graphicInfo.getX(), graphicInfo.getY(), graphicInfo.getWidth(), graphicInfo.getHeight());
  1012. } else if (SHAPE_TYPE.Rhombus.equals(shapeType)) {
  1013. // source is rhombus
  1014. Path2D.Double rhombus = new Path2D.Double();
  1015. rhombus.moveTo(graphicInfo.getX(), graphicInfo.getY() + graphicInfo.getHeight() / 2);
  1016. rhombus.lineTo(graphicInfo.getX() + graphicInfo.getWidth() / 2, graphicInfo.getY() + graphicInfo.getHeight());
  1017. rhombus.lineTo(graphicInfo.getX() + graphicInfo.getWidth(), graphicInfo.getY() + graphicInfo.getHeight() / 2);
  1018. rhombus.lineTo(graphicInfo.getX() + graphicInfo.getWidth() / 2, graphicInfo.getY());
  1019. rhombus.lineTo(graphicInfo.getX(), graphicInfo.getY() + graphicInfo.getHeight() / 2);
  1020. rhombus.closePath();
  1021. return rhombus;
  1022. } else if (SHAPE_TYPE.Ellipse.equals(shapeType)) {
  1023. // source is ellipse
  1024. return new Ellipse2D.Double(graphicInfo.getX(), graphicInfo.getY(), graphicInfo.getWidth(), graphicInfo.getHeight());
  1025. } else {
  1026. // unknown source element, just do not correct coordinates
  1027. }
  1028. return null;
  1029. }
  1030. /**
  1031. * This method returns intersection point of shape border and line.
  1032. *
  1033. * @param shape
  1034. * @param line
  1035. * @return Point
  1036. */
  1037. private static Point getIntersection(Shape shape, Line2D.Double line) {
  1038. if (shape instanceof Ellipse2D) {
  1039. return getEllipseIntersection(shape, line);
  1040. } else if (shape instanceof Rectangle2D || shape instanceof Path2D) {
  1041. return getShapeIntersection(shape, line);
  1042. } else {
  1043. // something strange
  1044. return null;
  1045. }
  1046. }
  1047. /**
  1048. * This method calculates ellipse intersection with line
  1049. *
  1050. * @param shape
  1051. * Bounds of this shape used to calculate parameters of inscribed into this bounds ellipse.
  1052. * @param line
  1053. * @return Intersection point
  1054. */
  1055. private static Point getEllipseIntersection(Shape shape, Line2D.Double line) {
  1056. double angle = Math.atan2(line.y2 - line.y1, line.x2 - line.x1);
  1057. double x = shape.getBounds2D().getWidth() / 2 * Math.cos(angle) + shape.getBounds2D().getCenterX();
  1058. double y = shape.getBounds2D().getHeight() / 2 * Math.sin(angle) + shape.getBounds2D().getCenterY();
  1059. Point p = new Point();
  1060. p.setLocation(x, y);
  1061. return p;
  1062. }
  1063. /**
  1064. * This method calculates shape intersection with line.
  1065. *
  1066. * @param shape
  1067. * @param line
  1068. * @return Intersection point
  1069. */
  1070. private static Point getShapeIntersection(Shape shape, Line2D.Double line) {
  1071. PathIterator it = shape.getPathIterator(null);
  1072. double[] coords = new double[6];
  1073. double[] pos = new double[2];
  1074. Line2D.Double l = new Line2D.Double();
  1075. while (!it.isDone()) {
  1076. int type = it.currentSegment(coords);
  1077. switch (type) {
  1078. case PathIterator.SEG_MOVETO:
  1079. pos[0] = coords[0];
  1080. pos[1] = coords[1];
  1081. break;
  1082. case PathIterator.SEG_LINETO:
  1083. l = new Line2D.Double(pos[0], pos[1], coords[0], coords[1]);
  1084. if (line.intersectsLine(l)) {
  1085. return getLinesIntersection(line, l);
  1086. }
  1087. pos[0] = coords[0];
  1088. pos[1] = coords[1];
  1089. break;
  1090. case PathIterator.SEG_CLOSE:
  1091. break;
  1092. default:
  1093. // whatever
  1094. }
  1095. it.next();
  1096. }
  1097. return null;
  1098. }
  1099. /**
  1100. * This method calculates intersections of two lines.
  1101. *
  1102. * @param a
  1103. * Line 1
  1104. * @param b
  1105. * Line 2
  1106. * @return Intersection point
  1107. */
  1108. private static Point getLinesIntersection(Line2D a, Line2D b) {
  1109. double d = (a.getX1() - a.getX2()) * (b.getY2() - b.getY1()) - (a.getY1() - a.getY2()) * (b.getX2() - b.getX1());
  1110. double da = (a.getX1() - b.getX1()) * (b.getY2() - b.getY1()) - (a.getY1() - b.getY1()) * (b.getX2() - b.getX1());
  1111. // double db = (a.getX1()-a.getX2())*(a.getY1()-b.getY1()) - (a.getY1()-a.getY2())*(a.getX1()-b.getX1());
  1112. double ta = da / d;
  1113. // double tb = db/d;
  1114. Point p = new Point();
  1115. p.setLocation(a.getX1() + ta * (a.getX2() - a.getX1()), a.getY1() + ta * (a.getY2() - a.getY1()));
  1116. return p;
  1117. }
  1118. }

CustomProcessDiagramGenerator.java

  1. package com.ztesoft.wfm.util.activiti;
  2. /* Licensed under the Apache License, Version 2.0 (the "License");
  3. * you may not use this file except in compliance with the License.
  4. * You may obtain a copy of the License at
  5. *
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. *
  8. * Unless required by applicable law or agreed to in writing, software
  9. * distributed under the License is distributed on an "AS IS" BASIS,
  10. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. * See the License for the specific language governing permissions and
  12. * limitations under the License.
  13. */
  14. import java.awt.image.BufferedImage;
  15. import java.io.InputStream;
  16. import java.util.ArrayList;
  17. import java.util.Collections;
  18. import java.util.HashMap;
  19. import java.util.List;
  20. import java.util.Map;
  21. import org.activiti.bpmn.model.Activity;
  22. import org.activiti.bpmn.model.Artifact;
  23. import org.activiti.bpmn.model.Association;
  24. import org.activiti.bpmn.model.AssociationDirection;
  25. import org.activiti.bpmn.model.BaseElement;
  26. import org.activiti.bpmn.model.BoundaryEvent;
  27. import org.activiti.bpmn.model.BpmnModel;
  28. import org.activiti.bpmn.model.BusinessRuleTask;
  29. import org.activiti.bpmn.model.CallActivity;
  30. import org.activiti.bpmn.model.CompensateEventDefinition;
  31. import org.activiti.bpmn.model.EndEvent;
  32. import org.activiti.bpmn.model.ErrorEventDefinition;
  33. import org.activiti.bpmn.model.Event;
  34. import org.activiti.bpmn.model.EventDefinition;
  35. import org.activiti.bpmn.model.EventGateway;
  36. import org.activiti.bpmn.model.EventSubProcess;
  37. import org.activiti.bpmn.model.ExclusiveGateway;
  38. import org.activiti.bpmn.model.FlowElement;
  39. import org.activiti.bpmn.model.FlowElementsContainer;
  40. import org.activiti.bpmn.model.FlowNode;
  41. import org.activiti.bpmn.model.Gateway;
  42. import org.activiti.bpmn.model.GraphicInfo;
  43. import org.activiti.bpmn.model.InclusiveGateway;
  44. import org.activiti.bpmn.model.IntermediateCatchEvent;
  45. import org.activiti.bpmn.model.Lane;
  46. import org.activiti.bpmn.model.ManualTask;
  47. import org.activiti.bpmn.model.MessageEventDefinition;
  48. import org.activiti.bpmn.model.MultiInstanceLoopCharacteristics;
  49. import org.activiti.bpmn.model.ParallelGateway;
  50. import org.activiti.bpmn.model.Pool;
  51. import org.activiti.bpmn.model.Process;
  52. import org.activiti.bpmn.model.ReceiveTask;
  53. import org.activiti.bpmn.model.ScriptTask;
  54. import org.activiti.bpmn.model.SendTask;
  55. import org.activiti.bpmn.model.SequenceFlow;
  56. import org.activiti.bpmn.model.ServiceTask;
  57. import org.activiti.bpmn.model.SignalEventDefinition;
  58. import org.activiti.bpmn.model.StartEvent;
  59. import org.activiti.bpmn.model.SubProcess;
  60. import org.activiti.bpmn.model.Task;
  61. import org.activiti.bpmn.model.TextAnnotation;
  62. import org.activiti.bpmn.model.ThrowEvent;
  63. import org.activiti.bpmn.model.TimerEventDefinition;
  64. import org.activiti.bpmn.model.UserTask;
  65. import org.activiti.image.ProcessDiagramGenerator;
  66. /**
  67. * Class to generate an image based the diagram interchange information in a BPMN 2.0 process.
  68. *
  69. * @author Joram Barrez
  70. * @author Tijs Rademakers
  71. */
  72. public class CustomProcessDiagramGenerator implements ProcessDiagramGenerator {
  73. protected Map<Class<? extends BaseElement>, ActivityDrawInstruction> activityDrawInstructions = new HashMap<Class<? extends BaseElement>, ActivityDrawInstruction>();
  74. protected Map<Class<? extends BaseElement>, ArtifactDrawInstruction> artifactDrawInstructions = new HashMap<Class<? extends BaseElement>, ArtifactDrawInstruction>();
  75. public CustomProcessDiagramGenerator() {
  76. this(1.0);
  77. }
  78. // The instructions on how to draw a certain construct is
  79. // created statically and stored in a map for performance.
  80. public CustomProcessDiagramGenerator(final double scaleFactor) {
  81. // start event
  82. activityDrawInstructions.put(StartEvent.class, new ActivityDrawInstruction() {
  83. @Override
  84. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  85. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  86. StartEvent startEvent = (StartEvent) flowNode;
  87. if (startEvent.getEventDefinitions() != null && !startEvent.getEventDefinitions().isEmpty()) {
  88. EventDefinition eventDefinition = startEvent.getEventDefinitions().get(0);
  89. if (eventDefinition instanceof TimerEventDefinition) {
  90. processDiagramCanvas.drawTimerStartEvent(graphicInfo, scaleFactor);
  91. } else if (eventDefinition instanceof ErrorEventDefinition) {
  92. processDiagramCanvas.drawErrorStartEvent(graphicInfo, scaleFactor);
  93. } else if (eventDefinition instanceof SignalEventDefinition) {
  94. processDiagramCanvas.drawSignalStartEvent(graphicInfo, scaleFactor);
  95. } else if (eventDefinition instanceof MessageEventDefinition) {
  96. processDiagramCanvas.drawMessageStartEvent(graphicInfo, scaleFactor);
  97. } else {
  98. processDiagramCanvas.drawNoneStartEvent(graphicInfo);
  99. }
  100. } else {
  101. processDiagramCanvas.drawNoneStartEvent(graphicInfo);
  102. }
  103. }
  104. });
  105. // signal catch
  106. activityDrawInstructions.put(IntermediateCatchEvent.class, new ActivityDrawInstruction() {
  107. @Override
  108. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  109. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  110. IntermediateCatchEvent intermediateCatchEvent = (IntermediateCatchEvent) flowNode;
  111. if (intermediateCatchEvent.getEventDefinitions() != null && !intermediateCatchEvent.getEventDefinitions().isEmpty()) {
  112. if (intermediateCatchEvent.getEventDefinitions().get(0) instanceof SignalEventDefinition) {
  113. processDiagramCanvas.drawCatchingSignalEvent(flowNode.getName(), graphicInfo, true, scaleFactor);
  114. } else if (intermediateCatchEvent.getEventDefinitions().get(0) instanceof TimerEventDefinition) {
  115. processDiagramCanvas.drawCatchingTimerEvent(flowNode.getName(), graphicInfo, true, scaleFactor);
  116. } else if (intermediateCatchEvent.getEventDefinitions().get(0) instanceof MessageEventDefinition) {
  117. processDiagramCanvas.drawCatchingMessageEvent(flowNode.getName(), graphicInfo, true, scaleFactor);
  118. }
  119. }
  120. }
  121. });
  122. // signal throw
  123. activityDrawInstructions.put(ThrowEvent.class, new ActivityDrawInstruction() {
  124. @Override
  125. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  126. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  127. ThrowEvent throwEvent = (ThrowEvent) flowNode;
  128. if (throwEvent.getEventDefinitions() != null && !throwEvent.getEventDefinitions().isEmpty()) {
  129. if (throwEvent.getEventDefinitions().get(0) instanceof SignalEventDefinition) {
  130. processDiagramCanvas.drawThrowingSignalEvent(graphicInfo, scaleFactor);
  131. } else if (throwEvent.getEventDefinitions().get(0) instanceof CompensateEventDefinition) {
  132. processDiagramCanvas.drawThrowingCompensateEvent(graphicInfo, scaleFactor);
  133. } else {
  134. processDiagramCanvas.drawThrowingNoneEvent(graphicInfo, scaleFactor);
  135. }
  136. } else {
  137. processDiagramCanvas.drawThrowingNoneEvent(graphicInfo, scaleFactor);
  138. }
  139. }
  140. });
  141. // end event
  142. activityDrawInstructions.put(EndEvent.class, new ActivityDrawInstruction() {
  143. @Override
  144. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  145. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  146. EndEvent endEvent = (EndEvent) flowNode;
  147. if (endEvent.getEventDefinitions() != null && !endEvent.getEventDefinitions().isEmpty()) {
  148. if (endEvent.getEventDefinitions().get(0) instanceof ErrorEventDefinition) {
  149. processDiagramCanvas.drawErrorEndEvent(flowNode.getName(), graphicInfo, scaleFactor);
  150. } else {
  151. processDiagramCanvas.drawNoneEndEvent(graphicInfo, scaleFactor);
  152. }
  153. } else {
  154. processDiagramCanvas.drawNoneEndEvent(graphicInfo, scaleFactor);
  155. }
  156. }
  157. });
  158. // task
  159. activityDrawInstructions.put(Task.class, new ActivityDrawInstruction() {
  160. @Override
  161. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  162. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  163. processDiagramCanvas.drawTask(flowNode.getName(), graphicInfo);
  164. }
  165. });
  166. // user task
  167. activityDrawInstructions.put(UserTask.class, new ActivityDrawInstruction() {
  168. @Override
  169. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  170. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  171. processDiagramCanvas.drawUserTask(flowNode.getName(), graphicInfo, scaleFactor);
  172. }
  173. });
  174. // script task
  175. activityDrawInstructions.put(ScriptTask.class, new ActivityDrawInstruction() {
  176. @Override
  177. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  178. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  179. processDiagramCanvas.drawScriptTask(flowNode.getName(), graphicInfo, scaleFactor);
  180. }
  181. });
  182. // service task
  183. activityDrawInstructions.put(ServiceTask.class, new ActivityDrawInstruction() {
  184. @Override
  185. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  186. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  187. ServiceTask serviceTask = (ServiceTask) flowNode;
  188. if ("camel".equalsIgnoreCase(serviceTask.getType())) {
  189. processDiagramCanvas.drawCamelTask(serviceTask.getName(), graphicInfo, scaleFactor);
  190. } else if ("mule".equalsIgnoreCase(serviceTask.getType())) {
  191. processDiagramCanvas.drawMuleTask(serviceTask.getName(), graphicInfo, scaleFactor);
  192. } else {
  193. processDiagramCanvas.drawServiceTask(serviceTask.getName(), graphicInfo, scaleFactor);
  194. }
  195. }
  196. });
  197. // receive task
  198. activityDrawInstructions.put(ReceiveTask.class, new ActivityDrawInstruction() {
  199. @Override
  200. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  201. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  202. processDiagramCanvas.drawReceiveTask(flowNode.getName(), graphicInfo, scaleFactor);
  203. }
  204. });
  205. // send task
  206. activityDrawInstructions.put(SendTask.class, new ActivityDrawInstruction() {
  207. @Override
  208. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  209. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  210. processDiagramCanvas.drawSendTask(flowNode.getName(), graphicInfo, scaleFactor);
  211. }
  212. });
  213. // manual task
  214. activityDrawInstructions.put(ManualTask.class, new ActivityDrawInstruction() {
  215. @Override
  216. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  217. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  218. processDiagramCanvas.drawManualTask(flowNode.getName(), graphicInfo, scaleFactor);
  219. }
  220. });
  221. // businessRuleTask task
  222. activityDrawInstructions.put(BusinessRuleTask.class, new ActivityDrawInstruction() {
  223. @Override
  224. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  225. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  226. processDiagramCanvas.drawBusinessRuleTask(flowNode.getName(), graphicInfo, scaleFactor);
  227. }
  228. });
  229. // exclusive gateway
  230. activityDrawInstructions.put(ExclusiveGateway.class, new ActivityDrawInstruction() {
  231. @Override
  232. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  233. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  234. processDiagramCanvas.drawExclusiveGateway(graphicInfo, scaleFactor);
  235. }
  236. });
  237. // inclusive gateway
  238. activityDrawInstructions.put(InclusiveGateway.class, new ActivityDrawInstruction() {
  239. @Override
  240. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  241. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  242. processDiagramCanvas.drawInclusiveGateway(graphicInfo, scaleFactor);
  243. }
  244. });
  245. // parallel gateway
  246. activityDrawInstructions.put(ParallelGateway.class, new ActivityDrawInstruction() {
  247. @Override
  248. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  249. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  250. processDiagramCanvas.drawParallelGateway(graphicInfo, scaleFactor);
  251. }
  252. });
  253. // event based gateway
  254. activityDrawInstructions.put(EventGateway.class, new ActivityDrawInstruction() {
  255. @Override
  256. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  257. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  258. processDiagramCanvas.drawEventBasedGateway(graphicInfo, scaleFactor);
  259. }
  260. });
  261. // Boundary timer
  262. activityDrawInstructions.put(BoundaryEvent.class, new ActivityDrawInstruction() {
  263. @Override
  264. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  265. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  266. BoundaryEvent boundaryEvent = (BoundaryEvent) flowNode;
  267. if (boundaryEvent.getEventDefinitions() != null && !boundaryEvent.getEventDefinitions().isEmpty()) {
  268. if (boundaryEvent.getEventDefinitions().get(0) instanceof TimerEventDefinition) {
  269. processDiagramCanvas.drawCatchingTimerEvent(flowNode.getName(), graphicInfo, boundaryEvent.isCancelActivity(), scaleFactor);
  270. } else if (boundaryEvent.getEventDefinitions().get(0) instanceof ErrorEventDefinition) {
  271. processDiagramCanvas.drawCatchingErrorEvent(graphicInfo, boundaryEvent.isCancelActivity(), scaleFactor);
  272. } else if (boundaryEvent.getEventDefinitions().get(0) instanceof SignalEventDefinition) {
  273. processDiagramCanvas.drawCatchingSignalEvent(flowNode.getName(), graphicInfo, boundaryEvent.isCancelActivity(), scaleFactor);
  274. } else if (boundaryEvent.getEventDefinitions().get(0) instanceof MessageEventDefinition) {
  275. processDiagramCanvas.drawCatchingMessageEvent(flowNode.getName(), graphicInfo, boundaryEvent.isCancelActivity(), scaleFactor);
  276. } else if (boundaryEvent.getEventDefinitions().get(0) instanceof CompensateEventDefinition) {
  277. processDiagramCanvas.drawCatchingCompensateEvent(graphicInfo, boundaryEvent.isCancelActivity(), scaleFactor);
  278. }
  279. }
  280. }
  281. });
  282. // subprocess
  283. activityDrawInstructions.put(SubProcess.class, new ActivityDrawInstruction() {
  284. @Override
  285. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  286. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  287. if (graphicInfo.getExpanded() != null && !graphicInfo.getExpanded()) {
  288. processDiagramCanvas.drawCollapsedSubProcess(flowNode.getName(), graphicInfo, false);
  289. } else {
  290. processDiagramCanvas.drawExpandedSubProcess(flowNode.getName(), graphicInfo, false, scaleFactor);
  291. }
  292. }
  293. });
  294. // Event subprocess
  295. activityDrawInstructions.put(EventSubProcess.class, new ActivityDrawInstruction() {
  296. @Override
  297. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  298. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  299. if (graphicInfo.getExpanded() != null && !graphicInfo.getExpanded()) {
  300. processDiagramCanvas.drawCollapsedSubProcess(flowNode.getName(), graphicInfo, true);
  301. } else {
  302. processDiagramCanvas.drawExpandedSubProcess(flowNode.getName(), graphicInfo, true, scaleFactor);
  303. }
  304. }
  305. });
  306. // call activity
  307. activityDrawInstructions.put(CallActivity.class, new ActivityDrawInstruction() {
  308. @Override
  309. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode) {
  310. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  311. processDiagramCanvas.drawCollapsedCallActivity(flowNode.getName(), graphicInfo);
  312. }
  313. });
  314. // text annotation
  315. artifactDrawInstructions.put(TextAnnotation.class, new ArtifactDrawInstruction() {
  316. @Override
  317. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, Artifact artifact) {
  318. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(artifact.getId());
  319. TextAnnotation textAnnotation = (TextAnnotation) artifact;
  320. processDiagramCanvas.drawTextAnnotation(textAnnotation.getText(), graphicInfo);
  321. }
  322. });
  323. // association
  324. artifactDrawInstructions.put(Association.class, new ArtifactDrawInstruction() {
  325. @Override
  326. public void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, Artifact artifact) {
  327. Association association = (Association) artifact;
  328. String sourceRef = association.getSourceRef();
  329. String targetRef = association.getTargetRef();
  330. // source and target can be instance of FlowElement or Artifact
  331. BaseElement sourceElement = bpmnModel.getFlowElement(sourceRef);
  332. BaseElement targetElement = bpmnModel.getFlowElement(targetRef);
  333. if (sourceElement == null) {
  334. sourceElement = bpmnModel.getArtifact(sourceRef);
  335. }
  336. if (targetElement == null) {
  337. targetElement = bpmnModel.getArtifact(targetRef);
  338. }
  339. List<GraphicInfo> graphicInfoList = bpmnModel.getFlowLocationGraphicInfo(artifact.getId());
  340. graphicInfoList = connectionPerfectionizer(processDiagramCanvas, bpmnModel, sourceElement, targetElement, graphicInfoList);
  341. int xPoints[] = new int[graphicInfoList.size()];
  342. int yPoints[] = new int[graphicInfoList.size()];
  343. for (int i = 1; i < graphicInfoList.size(); i++) {
  344. GraphicInfo graphicInfo = graphicInfoList.get(i);
  345. GraphicInfo previousGraphicInfo = graphicInfoList.get(i - 1);
  346. if (i == 1) {
  347. xPoints[0] = (int) previousGraphicInfo.getX();
  348. yPoints[0] = (int) previousGraphicInfo.getY();
  349. }
  350. xPoints[i] = (int) graphicInfo.getX();
  351. yPoints[i] = (int) graphicInfo.getY();
  352. }
  353. AssociationDirection associationDirection = association.getAssociationDirection();
  354. processDiagramCanvas.drawAssociation(xPoints, yPoints, associationDirection, false, scaleFactor);
  355. }
  356. });
  357. }
  358. public InputStream generateDiagram(BpmnModel bpmnModel, String imageType, List<String> highLightedActivities, List<String> highLightedFlows, String activityFontName,
  359. String labelFontName, ClassLoader customClassLoader, double scaleFactor) {
  360. return generateProcessDiagram(bpmnModel, imageType, highLightedActivities, highLightedFlows, activityFontName, labelFontName, customClassLoader, scaleFactor)
  361. .generateImage(imageType);
  362. }
  363. @Override
  364. public InputStream generateDiagram(BpmnModel bpmnModel, String imageType, List<String> highLightedActivities, List<String> highLightedFlows) {
  365. return generateDiagram(bpmnModel, imageType, highLightedActivities, highLightedFlows, null, null, null, 1.0);
  366. }
  367. @Override
  368. public InputStream generateDiagram(BpmnModel bpmnModel, String imageType, List<String> highLightedActivities, List<String> highLightedFlows, double scaleFactor) {
  369. return generateDiagram(bpmnModel, imageType, highLightedActivities, highLightedFlows, null, null, null, scaleFactor);
  370. }
  371. @Override
  372. public InputStream generateDiagram(BpmnModel bpmnModel, String imageType, List<String> highLightedActivities) {
  373. return generateDiagram(bpmnModel, imageType, highLightedActivities, Collections.<String> emptyList());
  374. }
  375. @Override
  376. public InputStream generateDiagram(BpmnModel bpmnModel, String imageType, List<String> highLightedActivities, double scaleFactor) {
  377. return generateDiagram(bpmnModel, imageType, highLightedActivities, Collections.<String> emptyList(), scaleFactor);
  378. }
  379. public InputStream generateDiagram(BpmnModel bpmnModel, String imageType, String activityFontName, String labelFontName, ClassLoader customClassLoader) {
  380. return generateDiagram(bpmnModel, imageType, Collections.<String> emptyList(), Collections.<String> emptyList(), activityFontName, labelFontName, customClassLoader, 1.0);
  381. }
  382. public InputStream generateDiagram(BpmnModel bpmnModel, String imageType, String activityFontName, String labelFontName, ClassLoader customClassLoader, double scaleFactor) {
  383. return generateDiagram(bpmnModel, imageType, Collections.<String> emptyList(), Collections.<String> emptyList(), activityFontName, labelFontName, customClassLoader,
  384. scaleFactor);
  385. }
  386. @Override
  387. public InputStream generatePngDiagram(BpmnModel bpmnModel) {
  388. return generatePngDiagram(bpmnModel, 1.0);
  389. }
  390. @Override
  391. public InputStream generatePngDiagram(BpmnModel bpmnModel, double scaleFactor) {
  392. return generateDiagram(bpmnModel, "png", Collections.<String> emptyList(), Collections.<String> emptyList(), scaleFactor);
  393. }
  394. @Override
  395. public InputStream generateJpgDiagram(BpmnModel bpmnModel) {
  396. return generateJpgDiagram(bpmnModel, 1.0);
  397. }
  398. @Override
  399. public InputStream generateJpgDiagram(BpmnModel bpmnModel, double scaleFactor) {
  400. return generateDiagram(bpmnModel, "jpg", Collections.<String> emptyList(), Collections.<String> emptyList());
  401. }
  402. public BufferedImage generateImage(BpmnModel bpmnModel, String imageType, List<String> highLightedActivities, List<String> highLightedFlows, String activityFontName,
  403. String labelFontName, ClassLoader customClassLoader, double scaleFactor) {
  404. return generateProcessDiagram(bpmnModel, imageType, highLightedActivities, highLightedFlows, activityFontName, labelFontName, customClassLoader, scaleFactor)
  405. .generateBufferedImage(imageType);
  406. }
  407. public BufferedImage generateImage(BpmnModel bpmnModel, String imageType, List<String> highLightedActivities, List<String> highLightedFlows, double scaleFactor) {
  408. return generateImage(bpmnModel, imageType, highLightedActivities, highLightedFlows, null, null, null, scaleFactor);
  409. }
  410. @Override
  411. public BufferedImage generatePngImage(BpmnModel bpmnModel, double scaleFactor) {
  412. return generateImage(bpmnModel, "png", Collections.<String> emptyList(), Collections.<String> emptyList(), scaleFactor);
  413. }
  414. protected CustomProcessDiagramCanvas generateProcessDiagram(BpmnModel bpmnModel, String imageType, List<String> highLightedActivities, List<String> highLightedFlows,
  415. String activityFontName, String labelFontName, ClassLoader customClassLoader, double scaleFactor) {
  416. CustomProcessDiagramCanvas processDiagramCanvas = initProcessDiagramCanvas(bpmnModel, imageType, activityFontName, labelFontName, customClassLoader);
  417. // Draw pool shape, if process is participant in collaboration
  418. for (Pool pool : bpmnModel.getPools()) {
  419. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(pool.getId());
  420. processDiagramCanvas.drawPoolOrLane(pool.getName(), graphicInfo);
  421. }
  422. // Draw lanes
  423. for (Process process : bpmnModel.getProcesses()) {
  424. for (Lane lane : process.getLanes()) {
  425. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(lane.getId());
  426. processDiagramCanvas.drawPoolOrLane(lane.getName(), graphicInfo);
  427. }
  428. }
  429. // Draw activities and their sequence-flows
  430. for (FlowNode flowNode : bpmnModel.getProcesses().get(0).findFlowElementsOfType(FlowNode.class)) {
  431. drawActivity(processDiagramCanvas, bpmnModel, flowNode, highLightedActivities, highLightedFlows, scaleFactor);
  432. }
  433. // Draw artifacts
  434. for (Process process : bpmnModel.getProcesses()) {
  435. for (Artifact artifact : process.getArtifacts()) {
  436. drawArtifact(processDiagramCanvas, bpmnModel, artifact);
  437. }
  438. }
  439. return processDiagramCanvas;
  440. }
  441. protected void drawActivity(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode, List<String> highLightedActivities,
  442. List<String> highLightedFlows, double scaleFactor) {
  443. ActivityDrawInstruction drawInstruction = activityDrawInstructions.get(flowNode.getClass());
  444. if (drawInstruction != null) {
  445. drawInstruction.draw(processDiagramCanvas, bpmnModel, flowNode);
  446. // Gather info on the multi instance marker
  447. boolean multiInstanceSequential = false, multiInstanceParallel = false, collapsed = false;
  448. if (flowNode instanceof Activity) {
  449. Activity activity = (Activity) flowNode;
  450. MultiInstanceLoopCharacteristics multiInstanceLoopCharacteristics = activity.getLoopCharacteristics();
  451. if (multiInstanceLoopCharacteristics != null) {
  452. multiInstanceSequential = multiInstanceLoopCharacteristics.isSequential();
  453. multiInstanceParallel = !multiInstanceSequential;
  454. }
  455. }
  456. // Gather info on the collapsed marker
  457. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  458. if (flowNode instanceof SubProcess) {
  459. collapsed = graphicInfo.getExpanded() != null && !graphicInfo.getExpanded();
  460. } else if (flowNode instanceof CallActivity) {
  461. collapsed = true;
  462. }
  463. if (scaleFactor == 1.0) {
  464. // Actually draw the markers
  465. processDiagramCanvas.drawActivityMarkers((int) graphicInfo.getX(), (int) graphicInfo.getY(), (int) graphicInfo.getWidth(), (int) graphicInfo.getHeight(),
  466. multiInstanceSequential, multiInstanceParallel, collapsed);
  467. }
  468. // Draw highlighted activities
  469. if (highLightedActivities.contains(flowNode.getId())) {
  470. drawHighLight(processDiagramCanvas, bpmnModel.getGraphicInfo(flowNode.getId()));
  471. }
  472. }
  473. // Outgoing transitions of activity
  474. for (SequenceFlow sequenceFlow : flowNode.getOutgoingFlows()) {
  475. boolean highLighted = (highLightedFlows.contains(sequenceFlow.getId()));
  476. String defaultFlow = null;
  477. if (flowNode instanceof Activity) {
  478. defaultFlow = ((Activity) flowNode).getDefaultFlow();
  479. } else if (flowNode instanceof Gateway) {
  480. defaultFlow = ((Gateway) flowNode).getDefaultFlow();
  481. }
  482. boolean isDefault = false;
  483. if (defaultFlow != null && defaultFlow.equalsIgnoreCase(sequenceFlow.getId())) {
  484. isDefault = true;
  485. }
  486. boolean drawConditionalIndicator = sequenceFlow.getConditionExpression() != null && !(flowNode instanceof Gateway);
  487. String sourceRef = sequenceFlow.getSourceRef();
  488. String targetRef = sequenceFlow.getTargetRef();
  489. FlowElement sourceElement = bpmnModel.getFlowElement(sourceRef);
  490. FlowElement targetElement = bpmnModel.getFlowElement(targetRef);
  491. List<GraphicInfo> graphicInfoList = bpmnModel.getFlowLocationGraphicInfo(sequenceFlow.getId());
  492. if (graphicInfoList != null && graphicInfoList.size() > 0) {
  493. graphicInfoList = connectionPerfectionizer(processDiagramCanvas, bpmnModel, sourceElement, targetElement, graphicInfoList);
  494. int xPoints[] = new int[graphicInfoList.size()];
  495. int yPoints[] = new int[graphicInfoList.size()];
  496. for (int i = 1; i < graphicInfoList.size(); i++) {
  497. GraphicInfo graphicInfo = graphicInfoList.get(i);
  498. GraphicInfo previousGraphicInfo = graphicInfoList.get(i - 1);
  499. if (i == 1) {
  500. xPoints[0] = (int) previousGraphicInfo.getX();
  501. yPoints[0] = (int) previousGraphicInfo.getY();
  502. }
  503. xPoints[i] = (int) graphicInfo.getX();
  504. yPoints[i] = (int) graphicInfo.getY();
  505. }
  506. processDiagramCanvas.drawSequenceflow(xPoints, yPoints, drawConditionalIndicator, isDefault, highLighted, scaleFactor);
  507. // Draw sequenceflow label
  508. GraphicInfo labelGraphicInfo = bpmnModel.getLabelGraphicInfo(sequenceFlow.getId());
  509. if (labelGraphicInfo != null) {
  510. GraphicInfo lineCenter = getLineCenter(graphicInfoList);
  511. processDiagramCanvas.drawLabel(sequenceFlow.getName(), lineCenter, false);
  512. }
  513. }
  514. }
  515. // Nested elements
  516. if (flowNode instanceof FlowElementsContainer) {
  517. for (FlowElement nestedFlowElement : ((FlowElementsContainer) flowNode).getFlowElements()) {
  518. if (nestedFlowElement instanceof FlowNode) {
  519. drawActivity(processDiagramCanvas, bpmnModel, (FlowNode) nestedFlowElement, highLightedActivities, highLightedFlows, scaleFactor);
  520. }
  521. }
  522. }
  523. }
  524. /**
  525. * This method makes coordinates of connection flow better.
  526. *
  527. * @param processDiagramCanvas
  528. * @param bpmnModel
  529. * @param sourceElement
  530. * @param targetElement
  531. * @param graphicInfoList
  532. * @return
  533. */
  534. protected static List<GraphicInfo> connectionPerfectionizer(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, BaseElement sourceElement,
  535. BaseElement targetElement, List<GraphicInfo> graphicInfoList) {
  536. GraphicInfo sourceGraphicInfo = bpmnModel.getGraphicInfo(sourceElement.getId());
  537. GraphicInfo targetGraphicInfo = bpmnModel.getGraphicInfo(targetElement.getId());
  538. CustomProcessDiagramCanvas.SHAPE_TYPE sourceShapeType = getShapeType(sourceElement);
  539. CustomProcessDiagramCanvas.SHAPE_TYPE targetShapeType = getShapeType(targetElement);
  540. return processDiagramCanvas.connectionPerfectionizer(sourceShapeType, targetShapeType, sourceGraphicInfo, targetGraphicInfo, graphicInfoList);
  541. }
  542. /**
  543. * This method returns shape type of base element.<br>
  544. * Each element can be presented as rectangle, rhombus, or ellipse.
  545. *
  546. * @param baseElement
  547. * @return CustomProcessDiagramCanvas.SHAPE_TYPE
  548. */
  549. protected static CustomProcessDiagramCanvas.SHAPE_TYPE getShapeType(BaseElement baseElement) {
  550. if (baseElement instanceof Task || baseElement instanceof Activity || baseElement instanceof TextAnnotation) {
  551. return CustomProcessDiagramCanvas.SHAPE_TYPE.Rectangle;
  552. } else if (baseElement instanceof Gateway) {
  553. return CustomProcessDiagramCanvas.SHAPE_TYPE.Rhombus;
  554. } else if (baseElement instanceof Event) {
  555. return CustomProcessDiagramCanvas.SHAPE_TYPE.Ellipse;
  556. } else {
  557. // unknown source element, just do not correct coordinates
  558. }
  559. return null;
  560. }
  561. protected static GraphicInfo getLineCenter(List<GraphicInfo> graphicInfoList) {
  562. GraphicInfo gi = new GraphicInfo();
  563. int xPoints[] = new int[graphicInfoList.size()];
  564. int yPoints[] = new int[graphicInfoList.size()];
  565. double length = 0;
  566. double[] lengths = new double[graphicInfoList.size()];
  567. lengths[0] = 0;
  568. double m;
  569. for (int i = 1; i < graphicInfoList.size(); i++) {
  570. GraphicInfo graphicInfo = graphicInfoList.get(i);
  571. GraphicInfo previousGraphicInfo = graphicInfoList.get(i - 1);
  572. if (i == 1) {
  573. xPoints[0] = (int) previousGraphicInfo.getX();
  574. yPoints[0] = (int) previousGraphicInfo.getY();
  575. }
  576. xPoints[i] = (int) graphicInfo.getX();
  577. yPoints[i] = (int) graphicInfo.getY();
  578. length += Math
  579. .sqrt(Math.pow((int) graphicInfo.getX() - (int) previousGraphicInfo.getX(), 2) + Math.pow((int) graphicInfo.getY() - (int) previousGraphicInfo.getY(), 2));
  580. lengths[i] = length;
  581. }
  582. m = length / 2;
  583. int p1 = 0, p2 = 1;
  584. for (int i = 1; i < lengths.length; i++) {
  585. double len = lengths[i];
  586. p1 = i - 1;
  587. p2 = i;
  588. if (len > m) {
  589. break;
  590. }
  591. }
  592. GraphicInfo graphicInfo1 = graphicInfoList.get(p1);
  593. GraphicInfo graphicInfo2 = graphicInfoList.get(p2);
  594. double AB = (int) graphicInfo2.getX() - (int) graphicInfo1.getX();
  595. double OA = (int) graphicInfo2.getY() - (int) graphicInfo1.getY();
  596. double OB = lengths[p2] - lengths[p1];
  597. double ob = m - lengths[p1];
  598. double ab = AB * ob / OB;
  599. double oa = OA * ob / OB;
  600. double mx = graphicInfo1.getX() + ab;
  601. double my = graphicInfo1.getY() + oa;
  602. gi.setX(mx);
  603. gi.setY(my);
  604. return gi;
  605. }
  606. protected void drawArtifact(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, Artifact artifact) {
  607. ArtifactDrawInstruction drawInstruction = artifactDrawInstructions.get(artifact.getClass());
  608. if (drawInstruction != null) {
  609. drawInstruction.draw(processDiagramCanvas, bpmnModel, artifact);
  610. }
  611. }
  612. private static void drawHighLight(CustomProcessDiagramCanvas processDiagramCanvas, GraphicInfo graphicInfo) {
  613. processDiagramCanvas.drawHighLight((int) graphicInfo.getX(), (int) graphicInfo.getY(), (int) graphicInfo.getWidth(), (int) graphicInfo.getHeight());
  614. }
  615. protected static CustomProcessDiagramCanvas initProcessDiagramCanvas(BpmnModel bpmnModel, String imageType, String activityFontName, String labelFontName,
  616. ClassLoader customClassLoader) {
  617. // We need to calculate maximum values to know how big the image will be in its entirety
  618. double minX = Double.MAX_VALUE;
  619. double maxX = 0;
  620. double minY = Double.MAX_VALUE;
  621. double maxY = 0;
  622. for (Pool pool : bpmnModel.getPools()) {
  623. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(pool.getId());
  624. minX = graphicInfo.getX();
  625. maxX = graphicInfo.getX() + graphicInfo.getWidth();
  626. minY = graphicInfo.getY();
  627. maxY = graphicInfo.getY() + graphicInfo.getHeight();
  628. }
  629. List<FlowNode> flowNodes = gatherAllFlowNodes(bpmnModel);
  630. for (FlowNode flowNode : flowNodes) {
  631. GraphicInfo flowNodeGraphicInfo = bpmnModel.getGraphicInfo(flowNode.getId());
  632. // width
  633. if (flowNodeGraphicInfo.getX() + flowNodeGraphicInfo.getWidth() > maxX) {
  634. maxX = flowNodeGraphicInfo.getX() + flowNodeGraphicInfo.getWidth();
  635. }
  636. if (flowNodeGraphicInfo.getX() < minX) {
  637. minX = flowNodeGraphicInfo.getX();
  638. }
  639. // height
  640. if (flowNodeGraphicInfo.getY() + flowNodeGraphicInfo.getHeight() > maxY) {
  641. maxY = flowNodeGraphicInfo.getY() + flowNodeGraphicInfo.getHeight();
  642. }
  643. if (flowNodeGraphicInfo.getY() < minY) {
  644. minY = flowNodeGraphicInfo.getY();
  645. }
  646. for (SequenceFlow sequenceFlow : flowNode.getOutgoingFlows()) {
  647. List<GraphicInfo> graphicInfoList = bpmnModel.getFlowLocationGraphicInfo(sequenceFlow.getId());
  648. if (graphicInfoList != null) {
  649. for (GraphicInfo graphicInfo : graphicInfoList) {
  650. // width
  651. if (graphicInfo.getX() > maxX) {
  652. maxX = graphicInfo.getX();
  653. }
  654. if (graphicInfo.getX() < minX) {
  655. minX = graphicInfo.getX();
  656. }
  657. // height
  658. if (graphicInfo.getY() > maxY) {
  659. maxY = graphicInfo.getY();
  660. }
  661. if (graphicInfo.getY() < minY) {
  662. minY = graphicInfo.getY();
  663. }
  664. }
  665. }
  666. }
  667. }
  668. List<Artifact> artifacts = gatherAllArtifacts(bpmnModel);
  669. for (Artifact artifact : artifacts) {
  670. GraphicInfo artifactGraphicInfo = bpmnModel.getGraphicInfo(artifact.getId());
  671. if (artifactGraphicInfo != null) {
  672. // width
  673. if (artifactGraphicInfo.getX() + artifactGraphicInfo.getWidth() > maxX) {
  674. maxX = artifactGraphicInfo.getX() + artifactGraphicInfo.getWidth();
  675. }
  676. if (artifactGraphicInfo.getX() < minX) {
  677. minX = artifactGraphicInfo.getX();
  678. }
  679. // height
  680. if (artifactGraphicInfo.getY() + artifactGraphicInfo.getHeight() > maxY) {
  681. maxY = artifactGraphicInfo.getY() + artifactGraphicInfo.getHeight();
  682. }
  683. if (artifactGraphicInfo.getY() < minY) {
  684. minY = artifactGraphicInfo.getY();
  685. }
  686. }
  687. List<GraphicInfo> graphicInfoList = bpmnModel.getFlowLocationGraphicInfo(artifact.getId());
  688. if (graphicInfoList != null) {
  689. for (GraphicInfo graphicInfo : graphicInfoList) {
  690. // width
  691. if (graphicInfo.getX() > maxX) {
  692. maxX = graphicInfo.getX();
  693. }
  694. if (graphicInfo.getX() < minX) {
  695. minX = graphicInfo.getX();
  696. }
  697. // height
  698. if (graphicInfo.getY() > maxY) {
  699. maxY = graphicInfo.getY();
  700. }
  701. if (graphicInfo.getY() < minY) {
  702. minY = graphicInfo.getY();
  703. }
  704. }
  705. }
  706. }
  707. int nrOfLanes = 0;
  708. for (Process process : bpmnModel.getProcesses()) {
  709. for (Lane l : process.getLanes()) {
  710. nrOfLanes++;
  711. GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(l.getId());
  712. // // width
  713. if (graphicInfo.getX() + graphicInfo.getWidth() > maxX) {
  714. maxX = graphicInfo.getX() + graphicInfo.getWidth();
  715. }
  716. if (graphicInfo.getX() < minX) {
  717. minX = graphicInfo.getX();
  718. }
  719. // height
  720. if (graphicInfo.getY() + graphicInfo.getHeight() > maxY) {
  721. maxY = graphicInfo.getY() + graphicInfo.getHeight();
  722. }
  723. if (graphicInfo.getY() < minY) {
  724. minY = graphicInfo.getY();
  725. }
  726. }
  727. }
  728. // Special case, see http://jira.codehaus.org/browse/ACT-1431
  729. if (flowNodes.isEmpty() && bpmnModel.getPools().isEmpty() && nrOfLanes == 0) {
  730. // Nothing to show
  731. minX = 0;
  732. minY = 0;
  733. }
  734. return new CustomProcessDiagramCanvas((int) maxX + 10, (int) maxY + 10, (int) minX, (int) minY, imageType, activityFontName, labelFontName, customClassLoader);
  735. }
  736. protected static List<Artifact> gatherAllArtifacts(BpmnModel bpmnModel) {
  737. List<Artifact> artifacts = new ArrayList<Artifact>();
  738. for (Process process : bpmnModel.getProcesses()) {
  739. artifacts.addAll(process.getArtifacts());
  740. }
  741. return artifacts;
  742. }
  743. protected static List<FlowNode> gatherAllFlowNodes(BpmnModel bpmnModel) {
  744. List<FlowNode> flowNodes = new ArrayList<FlowNode>();
  745. for (Process process : bpmnModel.getProcesses()) {
  746. flowNodes.addAll(gatherAllFlowNodes(process));
  747. }
  748. return flowNodes;
  749. }
  750. protected static List<FlowNode> gatherAllFlowNodes(FlowElementsContainer flowElementsContainer) {
  751. List<FlowNode> flowNodes = new ArrayList<FlowNode>();
  752. for (FlowElement flowElement : flowElementsContainer.getFlowElements()) {
  753. if (flowElement instanceof FlowNode) {
  754. flowNodes.add((FlowNode) flowElement);
  755. }
  756. if (flowElement instanceof FlowElementsContainer) {
  757. flowNodes.addAll(gatherAllFlowNodes((FlowElementsContainer) flowElement));
  758. }
  759. }
  760. return flowNodes;
  761. }
  762. public Map<Class<? extends BaseElement>, ActivityDrawInstruction> getActivityDrawInstructions() {
  763. return activityDrawInstructions;
  764. }
  765. public void setActivityDrawInstructions(Map<Class<? extends BaseElement>, ActivityDrawInstruction> activityDrawInstructions) {
  766. this.activityDrawInstructions = activityDrawInstructions;
  767. }
  768. public Map<Class<? extends BaseElement>, ArtifactDrawInstruction> getArtifactDrawInstructions() {
  769. return artifactDrawInstructions;
  770. }
  771. public void setArtifactDrawInstructions(Map<Class<? extends BaseElement>, ArtifactDrawInstruction> artifactDrawInstructions) {
  772. this.artifactDrawInstructions = artifactDrawInstructions;
  773. }
  774. protected interface ActivityDrawInstruction {
  775. void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode);
  776. }
  777. protected interface ArtifactDrawInstruction {
  778. void draw(CustomProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, Artifact artifact);
  779. }
  780. @Override
  781. public InputStream generateDiagram(BpmnModel bpmnModel, String imageType, List<String> highLightedActivities, List<String> highLightedFlows, String activityFontName,
  782. String labelFontName, String annotationFontName, ClassLoader customClassLoader, double scaleFactor) {
  783. // TODO Auto-generated method stub
  784. return generateProcessDiagram(bpmnModel, imageType, highLightedActivities, highLightedFlows, activityFontName, labelFontName, customClassLoader, scaleFactor)
  785. .generateImage(imageType);
  786. }
  787. @Override
  788. public InputStream generateDiagram(BpmnModel bpmnModel, String imageType, String activityFontName, String labelFontName, String annotationFontName,
  789. ClassLoader customClassLoader) {
  790. return generateDiagram(bpmnModel, imageType, Collections.<String> emptyList(), Collections.<String> emptyList(), activityFontName, labelFontName, customClassLoader, 1.0);
  791. }
  792. @Override
  793. public InputStream generateDiagram(BpmnModel bpmnModel, String imageType, String activityFontName, String labelFontName, String annotationFontName,
  794. ClassLoader customClassLoader, double scaleFactor) {
  795. // TODO Auto-generated method stub
  796. return generateDiagram(bpmnModel, imageType, Collections.<String> emptyList(), Collections.<String> emptyList(), activityFontName, labelFontName, customClassLoader,
  797. scaleFactor);
  798. }
  799. }

image.png