关于FoxBPM连接器介绍

 

目前FoxBPM提供两种连接器:1:连接器,2:选择器,关于连接器,请参考gihub官方(https://github.com/FoxBPM)的foxbpm-connector工程

 

选择器如下图
  关于FoxBPM连接器介绍_第1张图片

  下面介绍以上每种选择器的功能:

    参考图(请假审批): 

   
     关于FoxBPM连接器介绍_第2张图片
 

 

    首先我们所有连接器都是直接实现FlowConnectorHandler的void execute(ConnectorExecutionContext executionContext) throws Exception;方法,

    连接器的调用时机是在org.foxbpm.engine.impl.connector.Connector类的execute方法:

   

public void execute(ListenerExecutionContext executionContext) throws Exception {
		try {
			String classNameObj = packageName + "." + className;
			Class<?> connectorHandlerClass = Class.forName(classNameObj);
			FlowConnectorHandler connectorInstance = (FlowConnectorHandler) connectorHandlerClass
					.newInstance();

			FlowNodeExecutionContext flowNodeExecutionContext = (FlowNodeExecutionContext) executionContext;
			for (ConnectorInputParam connectorParameterInputs : this.getConnectorInputsParam()) {
				Class<?> ptypes[] = new Class[1];
				ptypes[0] = Class.forName(connectorParameterInputs.getDataType());
				String parameterInputsId = connectorParameterInputs.getId();
				String methodString = SETFUNCTION_PREFFIX
						+ parameterInputsId.substring(0, 1).toUpperCase()
						+ parameterInputsId.substring(1, parameterInputsId.length());
				Method m = connectorHandlerClass.getMethod(methodString, ptypes);
				if (connectorParameterInputs.getExpression() != null) {
					Object arg[] = new Object[1];
					if (!connectorParameterInputs.getExpression().isNullText()
							&& connectorParameterInputs.isExecute()) {
						arg[0] = connectorParameterInputs.getExpression().getValue(
								flowNodeExecutionContext);
					} else {
						arg[0] = connectorParameterInputs.getExpression().getExpressionText();
					}
					m.invoke(connectorInstance, arg);
				}

			}

			connectorInstance.execute((ConnectorExecutionContext) executionContext);
			for (ConnectorOutputParam connectorParameterOutputs : this.getConnectorOutputsParam()) {
				if (!StringUtil.isEmpty(connectorParameterOutputs.getOutputId())) {
					String parameterOutputsId = connectorParameterOutputs.getOutputId();
					String methodString = GETFUNCTION_PREFFIX
							+ parameterOutputsId.substring(0, 1).toUpperCase()
							+ parameterOutputsId.substring(1, parameterOutputsId.length());
					Method m = connectorHandlerClass.getMethod(methodString);
					String variableTarget = connectorParameterOutputs.getVariableTarget();
					// Object arg[] = new Object[1];
					// arg[0] =Context.getBshInterpreter().eval(scriptString);

					Object objectValue = m.invoke(connectorInstance);
					ExpressionMgmt.setVariable(variableTarget, objectValue,
							flowNodeExecutionContext);
				}

			}

		} catch (Exception e) {
			throw new FoxBPMConnectorException(e.getMessage(), e);
		}
	}

    1、连接器的触发时机:

          1、活动节点的“进入”,“执行”,“分配”,“离开”等事件,其中“分配”是针对人工任务。   

          2、整个流程的“启动”,“终止”,“结束”。

          3、从代码层次上看:
          关于FoxBPM连接器介绍_第3张图片
      通过以上事件的public void execute(InterpretableExecutionContext executionContext) 方法来触发连接器,

public void execute(InterpretableExecutionContext executionContext) {
	        KernelFlowElementsContainerImpl container = getContainer(executionContext);		
		String eventName = getEventName();
		List<KernelListener> kernelListeners = container.getKernelListeners(eventName);
		int kernelListenerIndex = executionContext.getKernelListenerIndex();
		if (kernelListeners.size() > kernelListenerIndex) {
			executionContext.setEventName(eventName);
			executionContext.setEventSource(container);
			KernelListener listener = kernelListeners.get(kernelListenerIndex);
			try {
				listener.notify(executionContext);
			} catch (RuntimeException e) {
				throw e;
			} catch (Exception e) {
				throw new KernelException("不能执行事件监听 : " + e.getMessage(), e);
			}

     对于连接器如果出现异常情况,一般从以上调用入口排查。

 

  下面介绍以上每种连接器的功能:

    1、Messaging

          1)发送邮件

               功能描述:根据配置的“主题”,“收件人”,“抄送人”,“正文”发送邮件。
               实现参考:

public class SendMail implements FlowConnectorHandler {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7217470393022025648L;

	private java.lang.String to;

	private java.lang.String title;

	private java.lang.String cc;

	private java.lang.String content;

	public void execute(ConnectorExecutionContext executionContext) throws Exception {
		// 获取邮件配置
		SysMailConfig sysMailConfig = Context.getProcessEngineConfiguration().getSysMailConfig();
		MailInfo mailInfoObj = null;
		for (MailInfo mailInfo : sysMailConfig.getMailInfo()) {
			if (mailInfo.getMailName().equals(sysMailConfig.getSelected())) {
				mailInfoObj = mailInfo;
			}
		}
		// 判断邮件配置信息是否为空
		if (null == mailInfoObj) {
			throw new FoxBPMException("系统邮件配置错误请检查流程邮件配置!");
		}
		MailEntity mailEntity = new MailEntity();
		mailEntity.setMailName(title);
		mailEntity.setMailSubject(title);
		mailEntity.setMailTo(to);
		mailEntity.setMailCc(cc);
		mailEntity.setMailBody(content);
		mailEntity.setCreateTime(new Date());
		mailEntity.setCreateUser(Authentication.getAuthenticatedUserId());
		MailEngine.getInstance().saveMail(mailEntity);
	}

	public void setTo(java.lang.String to) {
		this.to = to;
	}

	public void setTitle(java.lang.String title) {
		this.title = title;
	}

	public void setCc(java.lang.String cc) {
		this.cc = cc;
	}

	public void setContent(java.lang.String content) {
		this.content = content;
	}
}

 
               实例说明:例如任务分配时需要提示任务处理,这时候可以配置“发送邮件“连接器来通知。
               注意:

                1、该发送邮件不是立即发送,而是将邮件信息存入数据库foxbpm_mail中,有系统定时任务根据foxbpm_mail表内容来处理发送邮件。

                2、该发送邮件是根据foxbpm.cfg.xml中<sysMailConfig selected="FoxBPM邮箱">
                     <mailInfo mailAddress="[email protected]" mailName="FoxBPM邮箱"
                          smtpHost="mail.widedu.com.cn" smtpPort="25" userName="kenshin"                                   password="kenshin" />
                    </sysMailConfig>配置的信息来发送邮件。

                3、其中“发件人”,“抄送人”可以使多个(以分号分隔)。

          2)自动邮件发送

                功能描述:根据配置的“主题”,“正文”自动实现邮件发送(该连接器针对任务分配有效)连接器触发时机选择“分配”。

                实现参考:

public class AutoSendMail implements FlowConnectorHandler {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4576139954014666005L;
	private java.lang.String title;
	private java.lang.String content;
	public void execute(ConnectorExecutionContext executionContext) throws Exception {
	// 从上下文拿引擎
	ProcessEngineConfigurationImpl peconfig = Context.getProcessEngineConfiguration();
	// 获取邮件配置
	SysMailConfig sysMailConfig = peconfig.getSysMailConfig();
		MailInfo mailInfoObj = null;
		for (MailInfo mailInfo : sysMailConfig.getMailInfo()) {
			if (mailInfo.getMailName().equals(sysMailConfig.getSelected())) {
				mailInfoObj = mailInfo;
			}
		}
		// 判断邮件配置信息是否为空
		if (null == mailInfoObj) {
			throw new FoxBPMException("系统邮件配置错误请检查流程邮件配置!");
		}
		TaskEntity taskEntity = executionContext.getAssignTask();
		if (null != taskEntity) {
			StringBuffer mailTitle = new StringBuffer();
			// 如果主题为空
			if (StringUtil.isEmpty(StringUtil.trim(title))) {
				mailTitle.append('[').append(taskEntity.getProcessDefinitionName()).append(']').append(taskEntity.getDescription()).append(" is pending for your approval or handle");
			}

			String taskUrl = "http://www.baidu.com";
			if (StringUtil.isEmpty(content)) {
				content = "<br>Hello,<br>你好,<br><br> " + mailTitle + "<br><br>" + "Please click url to deal with job: <br>请访问此链接地址进入任务:<br> <a href=" + taskUrl + ">" + taskUrl + "</a><br><br>"
						+ "Best Regards!<br>诚挚问候!<br>Note: Please do not reply to this email , This mailbox does not allow incoming messages." + "<br>注意: 本邮件为工作流系统发送,请勿回复。 ";
			}
			// 获取用户
			IdentityService identityService = peconfig.getIdentityService();
			// 判断是否独占任务
			UserEntity user = null;
			if (StringUtil.isNotEmpty(taskEntity.getAssignee())) {
				user = identityService.getUser(taskEntity.getAssignee());
				// 判断用户是否为空
				if (null != user) {
					// 如果用户存在邮件地址即发生邮件
					if (StringUtil.isNotEmpty(user.getEmail())) {
						// 保存邮件实体
						saveMail(user.getEmail(), title, content, taskEntity.getId());
					}
				}
			} else {
				// 处理共享任务
				StringBuffer to = new StringBuffer();
				String userId = null;
				for (IdentityLinkEntity identityLink : taskEntity.getTaskIdentityLinks()) {
					userId = identityLink.getUserId();
					if (StringUtil.isNotEmpty(userId)) {
						if (!Constant.FOXBPM_ALL_USER.equals(userId)) {
							user = Authentication.selectUserByUserId(userId);
							if (null != user) {
								if (StringUtil.isNotEmpty(user.getEmail())) {
									to.append(user.getEmail()).append(Constants.COMMA);
								}
							}
						} else {
							// 处理所有者
							List<UserEntity> users = identityService.getUsers(null, null);
							if (null != users) {
								for (UserEntity u : users) {
									if (StringUtil.isNotEmpty(u.getEmail())) {
										to.append(u.getEmail()).append(Constants.COMMA);
									}
								}
							}
						}
					} else {
						// 获取组下面所有用户
						List<UserEntity> users = Authentication.selectUserByGroupIdAndType(identityLink.getGroupId(), identityLink.getGroupType());
						if (null != users) {
							for (UserEntity u : users) {
								if (StringUtil.isNotEmpty(u.getEmail())) {
									to.append(u.getEmail()).append(Constants.COMMA);
								}
							}
						}
					}
				}
				if (to.length() > 0) {
					// 删除最后一个','
					to.deleteCharAt(to.length() - 1);
					// 保存邮件实体
					saveMail(to.toString(), title, content, taskEntity.getId());
				}
			}
		}
	}
	/**
	 * 保存邮件
	 * 
	 * @param to
	 *            发给人
	 * @param title
	 *            主题
	 * @param mailContent
	 *            邮件内容
	 * @param taskId
	 *            任务id
	 */
	private void saveMail(String to, String mailtitle, String mailContent, String taskId) {
		// 创建邮件实体
		MailEntity mailEntity = new MailEntity();
		mailEntity.setMailName(mailtitle);
		mailEntity.setMailSubject(mailtitle);
		mailEntity.setMailTo(to);
		mailEntity.setMailBody(mailContent);
		mailEntity.setCreateTime(new Date());
		mailEntity.setCreateUser(Authentication.getAuthenticatedUserId());
		// 调用引擎保存邮件
		MailEngine.getInstance().saveMail(mailEntity);
	}
	public void setTitle(java.lang.String title) {
		this.title = title;
	}
	public void setContent(java.lang.String content) {
		this.content = content;
	}
}

                实例说明:例如:某用户填写请假申请(2天假期)---》项目主管,这时候就会自动发送邮件通知“项目主管”这个角色下的所有用户来处理。

                注意:

                1、该自动发邮件,根据任务特性自动获取收件人,任务特性有两种(独占、共享),如果是“独占”那么“收件人”任务处理人,如果是“共享”,那么“收件人”所有共享者,这里可包括(个人,所有人,角色)。

                2、只有选择连接事件为“分配”该连接器才有效。

     2、WebServices

          1)执行一个Web服务

                功能描述:根据配置webservice信息,调用webservice接口返回响应结果。

                实现参考:

public class WebServiceCall implements FlowConnectorHandler {

	/**
	 * 
	 */
	private static final long serialVersionUID = -748190599446833382L;

	private java.lang.String namespaceURI;

	private java.lang.String serviceName;

	private java.lang.String portName;

	private java.lang.String endpointAddress;

	private java.lang.String request;

	private java.lang.String response;

	public void execute(ConnectorExecutionContext executionContext) throws Exception {
		if (StringUtil.isEmpty(namespaceURI)) {
			throw new FoxBPMConnectorException("namespaceURI is null!");
		}
		if (StringUtil.isEmpty(portName)) {
			throw new FoxBPMConnectorException("portName is null!");
		}
		if (StringUtil.isEmpty(serviceName)) {
			throw new FoxBPMConnectorException("serviceName is null!");
		}

		if (StringUtil.isEmpty(endpointAddress)) {
			throw new FoxBPMConnectorException("endpointAddress is null!");
		}
		if (StringUtil.isEmpty(request)) {
			throw new FoxBPMConnectorException("request is null!");
		}

		QName portQName = new QName(namespaceURI, portName);
		Service service = Service.create(new QName(namespaceURI, serviceName));
		service.addPort(portQName, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
		StreamSource xmlSource = new StreamSource(new StringReader(request));
		Dispatch<Source> dispatchSource = service.createDispatch(portQName, Source.class, Service.Mode.MESSAGE);
		Source source = dispatchSource.invoke(xmlSource);
		StreamResult result = new StreamResult(new ByteArrayOutputStream());
		Transformer trans = TransformerFactory.newInstance().newTransformer();
		trans.transform(source, result);
		ByteArrayOutputStream baos = (ByteArrayOutputStream) result.getOutputStream();
		response = new String(baos.toByteArray());
	}

	public void setNamespaceURI(java.lang.String namespaceURI) {
		this.namespaceURI = namespaceURI;
	}

	public void setServiceName(java.lang.String serviceName) {
		this.serviceName = serviceName;
	}

	public void setPortName(java.lang.String portName) {
		this.portName = portName;
	}

	public void setEndpointAddress(java.lang.String endpointAddress) {
		this.endpointAddress = endpointAddress;
	}

	public void setRequest(java.lang.String request) {
		this.request = request;
	}

	public java.lang.String getResponse() {
		return response;
	}
}

                注意:

                1、该连接器需要输入参数,而且相关参数必须有值。

                2、该链接存在返回值

     3、Script

           1)Groovy

                  功能描述:执行Groovy脚本

                  实现参考:

                 

public class RunGroovyExpression implements FlowConnectorHandler {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1923171231930850489L;

	private java.lang.String expressionText;

	private java.lang.Object outputObj;

	public void execute(ConnectorExecutionContext executionContext) throws Exception {
		if (StringUtil.isNotEmpty(expressionText)) {
			outputObj = ExpressionMgmt.execute(expressionText, executionContext);
		}
	}

	public void setExpressionText(java.lang.String expressionText) {
		this.expressionText = expressionText;
	}

	public java.lang.Object getOutputObj() {
		return outputObj;
	}
}

                  注意:

                  1、该连接器需要输入参数且存在返回值。

     4、Database

          1、Generic

                1)DatasourceDatabaseQuery

                      功能描述:执行查询sql并返回结果。

                      实现参考:

                      

public class DatasourceDatabaseQuery implements FlowConnectorHandler {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8595980483313031237L;

	private java.lang.String sqlText;

	private java.util.List<java.util.Map<String, Object>> outputObj;

	public void execute(ConnectorExecutionContext executionContext) throws Exception {

		if (StringUtil.isEmpty(sqlText)) {
			throw new FoxBPMConnectorException("sqlText is null!");
		}
		// 只处理查询sql
		if (StringUtil.trim(sqlText).toLowerCase().startsWith(Constants.SQL_SELECT)) {
			SqlCommand sqlCommand = new SqlCommand(DBUtils.getConnection());
			outputObj = sqlCommand.queryForList(sqlText);
		} else {
			// 如果不是select 查询语句
			throw new FoxBPMConnectorException("执行无效的查询sql错误,请检查sql语句:" + sqlText);
		}
	}

	public void setSqlText(java.lang.String sqlText) {
		this.sqlText = sqlText;
	}

	public java.util.List<java.util.Map<String, Object>> getOutputObj() {
		return outputObj;
	}

}

                      注意:

                       1、输入的sql语句必须是select的,否则执行会出现异常。

                2)JDBCDatabaseQuery

                      功能描述:根据输入的数据库驱动、url、用户名、密码,执行查询sql并返回结果。

                      实现参考:

                     

public class JDBCDatabaseQuery implements FlowConnectorHandler {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3120408358341797232L;

	private java.lang.String driverClassName;

	private java.lang.String url;

	private java.lang.String username;

	private java.lang.String password;

	private java.lang.String sqlText;

	private java.util.List<java.util.Map<String, Object>> outputObj;

	public void execute(ConnectorExecutionContext executionContext) throws Exception {

		if (StringUtil.isEmpty(driverClassName)) {
			throw new FoxBPMConnectorException("driverClassName is null!");
		}
		if (StringUtil.isEmpty(url)) {
			throw new FoxBPMConnectorException("url is null!");
		}
		if (StringUtil.isEmpty(username)) {
			throw new FoxBPMConnectorException("username is null!");
		}
		if (StringUtil.isEmpty(password)) {
			throw new FoxBPMConnectorException("password is null!");
		}
		if (StringUtil.isEmpty(sqlText)) {
			throw new FoxBPMConnectorException("sqlText is null!");
		}
		// 只处理查询sql
		if (StringUtil.trim(sqlText).toLowerCase().startsWith(Constants.SQL_SELECT)) {
			// 加载驱动
			Class.forName(driverClassName);
			Connection connection = null;
			try {
				// 打开一个数据库连接
				connection = DriverManager.getConnection(url, username, password);
				SqlCommand sqlCommand = new SqlCommand(connection);
				outputObj = sqlCommand.queryForList(sqlText);
			} finally {
				if (null != connection) {
					// 释放连接
					connection.close();
				}
			}
		} else {
			// 如果不是select 查询语句
			throw new FoxBPMConnectorException("执行无效的查询sql错误,请检查sql语句:" + sqlText);
		}
	}

	public void setDriverClassName(java.lang.String driverClassName) {
		this.driverClassName = driverClassName;
	}

	public void setUrl(java.lang.String url) {
		this.url = url;
	}

	public void setUsername(java.lang.String username) {
		this.username = username;
	}

	public void setPassword(java.lang.String password) {
		this.password = password;
	}

	public void setSqlText(java.lang.String sqlText) {
		this.sqlText = sqlText;
	}

	public java.util.List<java.util.Map<String, Object>> getOutputObj() {
		return outputObj;
	}

}

                      注意:

                      1、这里输入驱动必须是系统存在的。

    总结:

        1、根据以上选择器特性,可以分为两种,无返回值、有返回值,两大类

          无返回值:1、2

          有返回值:3、4

        2、连接器执行时机是有事件触发的,其中对于“自动发送邮件”只有在连接器事件为“分配”才有效      

   最后,更多关于连接的使用以及配置,具体使用请大家到gihub官方(https://github.com/FoxBPM)下载相关FoxBPM的项目运行。

你可能感兴趣的:(BPM)