Commit 15db6f25 authored by 吴江's avatar 吴江

规则修改

parent f56dffa2
package com.yeejoin.amos.fas.business.action;
public interface CustomerAction {
}
package com.yeejoin.amos.fas.business.action.result;
import com.yeejoin.amos.fas.business.service.model.ToipResponse;
import com.yeejoin.amos.fas.dao.entity.BusinessEntity;
public abstract class AbstractActionResult implements ActionResult{
public ToipResponse toipResponse;
/**
* 智能体业务对象
*/
private BusinessEntity bizObj;
public ToipResponse getToipResponse() {
return toipResponse;
}
public void setToipResponse(ToipResponse toipResponse) {
this.toipResponse = toipResponse;
}
public BusinessEntity getBizObj() {
return bizObj;
}
public void setBizObj(BusinessEntity bizObj) {
this.bizObj = bizObj;
}
}
package com.yeejoin.amos.fas.business.action.result;
import java.util.List;
import com.alibaba.fastjson.JSON;
public interface ActionResult
{
public JSON toJson();
public void addAll(List<Object> data);
public void add(Object data);
public List<?> getData();
}
package com.yeejoin.amos.fas.business.action.result;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
public class BubbleTipResult extends SimpleResult{
@Override
public JSON toJson() {
// TODO Auto-generated method stub
Map<String, Object> results = new HashMap<>();
for (Map<String, Object> tempMap : data)
{
for (Map.Entry<String, Object> entry : tempMap.entrySet())
{
results.put(entry.getKey(), entry.getValue());
}
}
return (JSON) JSON.toJSON(results);
}
}
package com.yeejoin.amos.fas.business.action.result;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
public class RiskSituationResult extends SimpleResult{
@Override
public JSON toJson() {
// TODO Auto-generated method stub
Map<String, Object> results = new HashMap<>();
for (Map<String, Object> tempMap : data)
{
for (Map.Entry<String, Object> entry : tempMap.entrySet())
{
results.put(entry.getKey(), entry.getValue());
}
}
return (JSON) JSON.toJSON(results);
}
}
package com.yeejoin.amos.fas.business.action.result;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.yeejoin.amos.fas.business.util.JSONUtil;
public class SimpleResult extends AbstractActionResult implements ActionResult
{
List<Map<String, Object>> data = new ArrayList<>();
@Override
public JSON toJson()
{
List<Map<String, Object>> results = new ArrayList<>();
for (Map<String, Object> tempMap : data)
{
for (Map.Entry<String, Object> entry : tempMap.entrySet())
{
Map<String,Object> result = new HashMap<>();
result.put("label", entry.getKey());
result.put("value", entry.getValue());
results.add(result);
}
}
return (JSON) JSON.toJSON(results);
}
@Override
public void addAll(List<Object> data)
{
// this.data.addAll((Collection<? extends Map<String, Object>>) data);
}
@Override
public void add(Object data)
{
this.data.add(JSONUtil.toMap(JSONUtil.toJson(data)));
}
public void add(String key,Object value)
{
Map<String, Object> map = new HashMap<>();
map.put(key, value);
this.data.add(map);
}
@Override
public List<Map<String, Object>> getData() {
// TODO Auto-generated method stub
return data;
}
}
package com.yeejoin.amos.fas.business.action.result;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
public class TipResult extends SimpleResult{
@Override
public JSON toJson() {
// TODO Auto-generated method stub
Map<String, Object> results = new HashMap<>();
for (Map<String, Object> tempMap : data)
{
for (Map.Entry<String, Object> entry : tempMap.entrySet())
{
results.put(entry.getKey(), entry.getValue());
}
}
return (JSON) JSON.toJSON(results);
}
}
package com.yeejoin.amos.fas.business.action.result.message;
import java.io.IOException;
import com.yeejoin.amos.fas.business.action.result.AbstractActionResult;
import com.yeejoin.amos.fas.business.action.result.ActionResult;
import com.yeejoin.amos.fas.business.action.websocket.RuleWebSocket;
import com.yeejoin.amos.fas.business.service.model.ToipResponse;
import com.yeejoin.amos.fas.business.util.Constants;
import com.yeejoin.amos.fas.core.util.CommonResponse;
public abstract class AbstractActionResultMessage<R extends ToipResponse>
implements ActionResultMessage<ToipResponse>
{
protected ActionResult actionResult;
@Override
public ToipResponse execute(String firstStr, String secondStr,
String thirdStr) throws IOException, Exception
{
ToipResponse response = buildResponse(firstStr, secondStr, thirdStr,
getActionResultByDataFormat() == null ? actionResult.getData(): getActionResultByDataFormat(),
actionResult);
if (!actionResult.getData().isEmpty())
{
sendResponse(response);
}
return response;
}
protected abstract Object getActionResultByDataFormat();
/**
*
* <pre>
* 构建对象
* </pre>
*
* @param viewTemp
* @param obj
* @return
*/
public ToipResponse buildResponse(String firstIfDomain,
String secondIfDomain, String thirdIfDomain, Object obj,
ActionResult actionResult)
{
ToipResponse toipResponse = new ToipResponse();
toipResponse.setIFDomain(firstIfDomain);
toipResponse.setTemplate(secondIfDomain + "_" + thirdIfDomain);
toipResponse.setGroup("");// group值暂填充至temolate中
// toipResponse.setActionId(ruleAction.getId());
// toipResponse.setBizId(
// ((AbstractActionResult) actionResult).getBizObj().getId());
toipResponse
.setBizObj(((AbstractActionResult) actionResult).getBizObj());
toipResponse.setResult(Constants.RESULT_SUCCESS);
toipResponse.setDataList(obj);
return toipResponse;
}
/**
*
* <pre>
* 发送数据
* </pre>
*
* @param response
* @throws IOException
* @throws Exception
*/
protected void sendResponse(CommonResponse response)
throws IOException, Exception
{
RuleWebSocket.sendInfo(response.toJsonStr());
System.out.println("数据发送成功>>>>>>>>" + response.toJsonStr());
}
}
package com.yeejoin.amos.fas.business.action.result.message;
import java.io.IOException;
public interface ActionResultMessage<T> {
/**
*
* <pre>
*
* </pre>
*
* @param firstStr 一级界面域
* @param secondStr 二级界面域
* @param thirdStr 三级界面域
* @return
* @throws IOException
* @throws Exception
*/
T execute(String firstStr, String secondStr, String thirdStr) throws IOException, Exception ;
}
package com.yeejoin.amos.fas.business.action.result.message;
import com.yeejoin.amos.fas.business.action.result.ActionResult;
/**
*
* <pre>
* 气泡消息提示
* </pre>
*
* @author amos
* @version $Id: BubbleTipResultMessage.java, v 0.1 2019年5月16日 下午1:52:36 amos Exp $
*/
public class BubbleTipResultMessage extends SimpleResultMessage{
public BubbleTipResultMessage(ActionResult actionResult) {
super(actionResult);
// TODO Auto-generated constructor stub
}
}
package com.yeejoin.amos.fas.business.action.result.message;
import com.yeejoin.amos.fas.business.action.result.ActionResult;
/**
*
* <pre>
* 气泡消息提示
* </pre>
*
* @author amos
* @version $Id: BubbleTipResultMessage.java, v 0.1 2019年5月16日 下午1:52:36 amos Exp $
*/
public class RiskSituationResultMessage extends SimpleResultMessage{
public RiskSituationResultMessage(ActionResult actionResult) {
super(actionResult);
// TODO Auto-generated constructor stub
}
}
package com.yeejoin.amos.fas.business.action.result.message;
import com.yeejoin.amos.fas.business.action.result.ActionResult;
import com.yeejoin.amos.fas.business.service.model.ToipResponse;
/**
*
* <pre>
* 简单文本输入
* </pre>
*
* @author amos
* @version $Id: SimpleResultMessage.java, v 0.1 2019年4月25日 下午1:57:33 amos Exp $
*/
public class SimpleResultMessage extends AbstractActionResultMessage<ToipResponse>
{
public SimpleResultMessage(ActionResult actionResult) {
this.actionResult = actionResult;
}
@Override
protected Object getActionResultByDataFormat() {
return actionResult.toJson();
}
}
package com.yeejoin.amos.fas.business.action.result.message;
import com.yeejoin.amos.fas.business.action.result.ActionResult;
/**
*
* <pre>
* 消息提示
* </pre>
*
* @author amos
* @version $Id: TipResultMessage.java, v 0.1 2019年4月25日 上午11:47:13 amos Exp $
*/
public class TipResultMessage extends SimpleResultMessage{
public TipResultMessage(ActionResult actionResult) {
super(actionResult);
// TODO Auto-generated constructor stub
}
}
package com.yeejoin.amos.fas.business.action.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* <pre>
* 反射工具类
* </pre>
*
* @author HK
* @version $Id: ReflectUtil.java, v 0.1 2017年12月25日 下午8:05:45 HK Exp $
*/
public class ReflectUtil
{
private final static Logger logger = LoggerFactory
.getLogger(ReflectUtil.class);
/**
*
* <pre>
* 设置属性值
* </pre>
*
* @param target
* 目标对象
* @param fname
* 字段名称
* @param ftype
* 字典类型
* @param fvalue
* 字段值
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void setFieldValue(Object target, String fname, Class ftype,
Object fvalue)
{ // 设置字段值 如:username 字段,setUsername(String username)
if (target == null || fname == null || "".equals(fname)
|| (fvalue != null
&& !ftype.isAssignableFrom(fvalue.getClass())))
{// 如果类型不匹配,直接退出
return;
}
Class clazz = target.getClass();
try
{ // 先通过setXxx()方法设置类属性值
String methodname = "set" + Character.toUpperCase(fname.charAt(0))
+ fname.substring(1);
// System.out.println(methodname);
Method method = clazz.getDeclaredMethod(methodname, ftype); // 获取定义的方法
if (!Modifier.isPublic(method.getModifiers()))
{ // 设置非共有方法权限
method.setAccessible(true);
}
method.invoke(target, fvalue); // 执行方法回调
}
catch (Exception me)
{// 如果set方法不存在,则直接设置类属性值
try
{
Field field = clazz.getDeclaredField(fname); // 获取定义的类属性
if (!Modifier.isPublic(field.getModifiers()))
{ // 设置非共有类属性权限
field.setAccessible(true);
}
field.set(target, fvalue); // 设置类属性值
}
catch (Exception fe)
{
if (logger.isDebugEnabled())
{
logger.debug(fe.getMessage());
}
}
}
}
/**
*
* <pre>
* 获取属性值
* </pre>
*
* @param target
* 目标对象
* @param fname
* 字段名称
* @param ftype
* 字段类型
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object getFieldValue(Object target, String fname, Class ftype)
{// 获取字段值 如:username 字段,getUsername()
if (target == null || fname == null || "".equals(fname))
{
return null;
}
Class clazz = target.getClass();
try
{ // 先通过getXxx()方法获取类属性值
String methodname = "get" + Character.toUpperCase(fname.charAt(0))
+ fname.substring(1);
// System.out.println(methodname);
Method method = clazz.getDeclaredMethod(methodname); // 获取定义的方法
if (!Modifier.isPublic(method.getModifiers()))
{ // 设置非共有方法权限
method.setAccessible(true);
}
return method.invoke(target); // 方法回调,返回值
}
catch (Exception me)
{// 如果get方法不存在,则直接获取类属性值
if (logger.isDebugEnabled())
{
logger.debug(me.getMessage());
}
try
{
Field field = clazz.getDeclaredField(fname); // 获取定义的类属性
if (!Modifier.isPublic(field.getModifiers()))
{ // 设置非共有类属性权限
field.setAccessible(true);
}
return field.get(target);// 返回类属性值
}
catch (Exception fe)
{
if (logger.isDebugEnabled())
{
logger.debug(fe.getMessage());
}
}
}
return null;
}
public static <E> E newInstance(final Class<? extends E> clazz)
{
try
{
return clazz.newInstance();
}
catch (final Exception e)
{
logger.warn("Could not instantiate {}: {}", clazz, e);
if (e instanceof RuntimeException)
{
throw (RuntimeException) e;
}
throw new IllegalStateException(e);
}
}
public static <A extends Annotation> A getAnnotation(
final Enum<?> enumConstant, final Class<A> annotationClass)
{
try
{
final Field field = enumConstant.getClass()
.getDeclaredField(enumConstant.name());
return getAnnotation(field, annotationClass);
}
catch (final Exception e)
{
throw new IllegalStateException(e);
}
}
public static <A extends Annotation> A getAnnotation(
final AnnotatedElement element, final Class<A> annotationClass)
{
final A annotation = element.getAnnotation(annotationClass);
if (annotation == null && element instanceof Method)
{
// check for annotations on overridden methods. Since Java 8
// those are not returned by .getAnnotation(...)
final Method m = (Method) element;
final Class<?> declaringClass = m.getDeclaringClass();
final Class<?> superClass = declaringClass.getSuperclass();
final String methodName = m.getName();
final Class<?>[] methodParameterTypes = m.getParameterTypes();
if (superClass != null)
{
try
{
final Method overriddenMethod = superClass
.getMethod(methodName, methodParameterTypes);
return getAnnotation(overriddenMethod, annotationClass);
}
catch (final NoSuchMethodException e)
{
logger.debug("Failed to get overridden method '{}' from {}",
methodName, superClass);
}
}
// check for annotations on interface methods too.
final Class<?>[] interfaces = declaringClass.getInterfaces();
for (final Class<?> interfaceClass : interfaces)
{
try
{
final Method overriddenMethod = interfaceClass
.getMethod(methodName, methodParameterTypes);
return getAnnotation(overriddenMethod, annotationClass);
}
catch (final NoSuchMethodException e)
{
logger.debug("Failed to get overridden method '{}' from {}",
methodName, interfaceClass);
}
}
}
if(annotation == null && element instanceof Class<?>){
final Class<?> clazz = (Class<?>) element;
// final Class<?> declaringClass = clazz.getDeclaringClass();
final Class<?> superClass = clazz.getSuperclass();
if (superClass != null)
{
return getAnnotation(superClass, annotationClass);
}
}
return annotation;
}
public static boolean isAnnotationPresent(final Enum<?> enumConstant,
final Class<? extends Annotation> annotationClass)
{
try
{
final Field field = enumConstant.getClass()
.getDeclaredField(enumConstant.name());
return isAnnotationPresent(field, annotationClass);
}
catch (final Exception e)
{
throw new IllegalStateException(e);
}
}
public static boolean isAnnotationPresent(final AnnotatedElement element,
final Class<? extends Annotation> annotationClass)
{
return getAnnotation(element, annotationClass) != null;
}
public static Field[] getAllFields(String clazzName,
final Class<? extends Annotation> withAnnotation) throws ClassNotFoundException
{
final List<Field> result = new ArrayList<>();
final Field[] fields = getAllFields(Class.forName(clazzName));
for (final Field field : fields)
{
if (isAnnotationPresent(field, withAnnotation))
{
result.add(field);
}
}
return result.toArray(new Field[result.size()]);
}
public static Field[] getAllFields(final Class<?> clazz,
final Class<? extends Annotation> withAnnotation)
{
final List<Field> result = new ArrayList<>();
final Field[] fields = getAllFields(clazz);
for (final Field field : fields)
{
if (isAnnotationPresent(field, withAnnotation))
{
result.add(field);
}
}
return result.toArray(new Field[result.size()]);
}
public static Field[] getAllFields(final Class<?> clazz)
{
final List<Field> allFields = new ArrayList<>();
addFields(allFields, clazz);
return allFields.toArray(new Field[allFields.size()]);
}
private static void addFields(final List<Field> allFields,
final Class<?> clazz)
{
addFields(allFields, clazz, false);
}
private static void addFields(final List<Field> allFields,
final Class<?> clazz, final boolean excludeSynthetic)
{
if (clazz == Object.class)
{
return;
}
final Field[] f = clazz.getDeclaredFields();
for (final Field field : f)
{
if (excludeSynthetic && field.isSynthetic())
{
continue;
}
allFields.add(field);
}
final Class<?> superclass = clazz.getSuperclass();
addFields(allFields, superclass, excludeSynthetic);
}
public static Method[] getMethods(final Class<?> clazz, final Class<? extends Annotation> withAnnotation) {
final List<Method> result = new ArrayList<>();
final Method[] methods = getMethods(clazz);
for (final Method method : methods) {
if (isAnnotationPresent(method, withAnnotation)) {
result.add(method);
}
}
return result.toArray(new Method[result.size()]);
}
public static Method[] getMethods(final Class<?> clazz) {
final List<Method> allMethods = new ArrayList<>();
addMethods(allMethods, clazz);
return allMethods.toArray(new Method[allMethods.size()]);
}
private static void addMethods(final List<Method> allMethods, final Class<?> clazz) {
if (clazz == Object.class || clazz == null) {
return;
}
final Method[] methods = clazz.getMethods();
for (final Method method : methods) {
final Class<?> declaringClass = method.getDeclaringClass();
if (declaringClass != Object.class) {
allMethods.add(method);
}
}
}
}
package com.yeejoin.amos.fas.business.action.websocket;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
*
* <pre>
* rule webSocket定义
* </pre>
*
* @author amos
* @version $Id: RuleWebSocket.java, v 0.1 2019年5月20日 下午4:59:50 amos Exp $
*/
@Component
@ServerEndpoint(value = "/rule.ws")
public class RuleWebSocket implements Observer
{
private final static Logger log = LoggerFactory.getLogger(RuleWebSocket.class);
// 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
// concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<RuleWebSocket> webSocketSet = new CopyOnWriteArraySet<RuleWebSocket>();
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private Observable ob;
private String name;
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session)
{
this.session = session;
webSocketSet.add(this); // 加入set中
addOnlineCount(); // 在线数加1
log.debug("有新连接加入!当前在线人数为" + getOnlineCount());
subscribeTopics(session);
}
/**
*
* <pre>
* 订阅指挥
* </pre>
*
*/
public void subscribeTopics(Session session)
{
// this.ob = GlobalDispatch.getInstance();
// GlobalDispatch.getInstance().addObserver(this);
log.info("成功加入规则主题");
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose()
{
webSocketSet.remove(this); // 从set中删除
subOnlineCount(); // 在线数减1
log.debug("有一连接关闭!当前在线人数为" + getOnlineCount());
if (ob != null)
{
ob.deleteObserver(this);
}
}
/**
* 收到客户端消息后调用的方法
*
* @param message
* 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session)
{
log.info("来自客户端的消息:" + message);
}
@OnError
public void onError(Session session, Throwable error)
{
log.error("发生错误", error);
}
public void sendMessage(String message) throws IOException
{
this.session.getBasicRemote().sendText(message);
// this.session.getAsyncRemote().sendText(message);
}
/**
* 群发自定义消息
*/
public static void sendInfo(String message) throws IOException
{
log.debug("——----RuleWebSocket开始群发消息------");
log.debug("消息内容为:" + message);
for (RuleWebSocket item : webSocketSet)
{
try
{
item.sendMessage(message);
}
catch (IOException e)
{
log.error(item.session.getId() + "消息发送失败", e);
continue;
}
}
log.debug("——----RuleWebSocket结束群发消息------");
}
public static synchronized int getOnlineCount()
{
return onlineCount;
}
public static synchronized void addOnlineCount()
{
RuleWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount()
{
RuleWebSocket.onlineCount--;
}
@Override
public void update(Observable o, Object arg)
{
try
{
if (session.isOpen())
{
sendMessage(arg.toString());
log.debug("session" + name + "消息发送成功");
}
else
{
o.deleteObserver(this);
log.debug("session" + name + "消息发送失败:" + "session已经失去连接");
}
}
catch (Exception e)
{
log.error("session" + name + "消息发送失败:" + e.getMessage());
}
}
}
package com.yeejoin.amos.fas.business.dao.mapper;
import java.util.List;
import com.yeejoin.amos.fas.business.service.model.RuleRuningSnapshot;
public interface RuleRuningSnapshotMapper extends BaseMapper{
RuleRuningSnapshot querForObject(String batchNo);
List<RuleRuningSnapshot> querForObjectList(String batchNo);
}
...@@ -258,4 +258,9 @@ public class ContingencyInstanceImpl /*extends GenericManagerImpl<ContingencyPla ...@@ -258,4 +258,9 @@ public class ContingencyInstanceImpl /*extends GenericManagerImpl<ContingencyPla
} }
@Override
public void updateStep(String step, String batchNo) {
// TODO Auto-generated method stub
}
} }
...@@ -44,6 +44,8 @@ import com.google.common.base.Joiner; ...@@ -44,6 +44,8 @@ import com.google.common.base.Joiner;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.yeejoin.amos.component.rule.RuleTrigger;
import com.yeejoin.amos.component.rule.action.ActionHandler;
import com.yeejoin.amos.fas.business.bo.BindRegionBo; import com.yeejoin.amos.fas.business.bo.BindRegionBo;
import com.yeejoin.amos.fas.business.bo.JpushMsgBo; import com.yeejoin.amos.fas.business.bo.JpushMsgBo;
import com.yeejoin.amos.fas.business.bo.JpushMsgContentBo; import com.yeejoin.amos.fas.business.bo.JpushMsgContentBo;
...@@ -231,6 +233,9 @@ public class RiskSourceServiceImpl implements IRiskSourceService { ...@@ -231,6 +233,9 @@ public class RiskSourceServiceImpl implements IRiskSourceService {
@Autowired @Autowired
private IDataRefreshService iDataRefreshService; private IDataRefreshService iDataRefreshService;
@Autowired
private RuleTrigger ruleTrigger;
@Override @Override
public RiskSource editRiskSource(HashMap<String, Object> map) throws Exception { public RiskSource editRiskSource(HashMap<String, Object> map) throws Exception {
...@@ -545,7 +550,9 @@ public class RiskSourceServiceImpl implements IRiskSourceService { ...@@ -545,7 +550,9 @@ public class RiskSourceServiceImpl implements IRiskSourceService {
} }
} }
} }
Object result = remoteRuleServer.fireRuleFlow(contingencyRo, equipment.getReservePlan(), equipment.getName());
//Object result = remoteRuleServer.fireRuleFlow(contingencyRo, equipment.getReservePlan(), equipment.getName());
ruleTrigger.publish(contingencyRo, equipment.getReservePlan());
ContingencyOriginalData contingencyOriginalData = new ContingencyOriginalData(); ContingencyOriginalData contingencyOriginalData = new ContingencyOriginalData();
BeanUtils.copyProperties(contingencyRo, contingencyOriginalData); BeanUtils.copyProperties(contingencyRo, contingencyOriginalData);
iContingencyOriginalDataDao.save(contingencyOriginalData); iContingencyOriginalDataDao.save(contingencyOriginalData);
......
package com.yeejoin.amos.fas.business.service.impl;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.core.foundation.context.SpringContextHelper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.fas.business.action.CustomerAction;
import com.yeejoin.amos.fas.business.dao.mapper.RuleRuningSnapshotMapper;
import com.yeejoin.amos.fas.business.service.intfc.IRuleRunningSnapshotService;
import com.yeejoin.amos.fas.business.service.model.BasicsRo;
import com.yeejoin.amos.fas.business.service.model.RuleRuningSnapshot;
/**
*
* <pre>
* 三维节点与规则消息实体视图service实现
* </pre>
*
* @author amos
* @version $Id: NodeMsgViewServiceImpl.java, v 0.1 2018年11月28日 下午6:14:51 amos Exp
* $
*/
@Service("ruleRunningSnapshotService")
public class RuleRunigSnapshotServiceImpl
implements IRuleRunningSnapshotService
//,ExecuteMethodHook
{
//IRuleRuningSnapshotRepository repository;
private RuleRuningSnapshotMapper ruleRuningSnapshotMapper;
private static String replayBatchNo = null;
static ObjectMapper objectMapper;
private final Logger logger = LoggerFactory.getLogger(RuleRunigSnapshotServiceImpl.class);
static {
objectMapper = new ObjectMapper();
}
// public RuleRunigSnapshotServiceImpl(IRuleRuningSnapshotRepository repository)
// {
// super(repository);
// // TODO Auto-generated constructor stub
// this.repository = repository;
// ExecuteMethodHook.hook.add(this);
// }
//
//
// /**
// * 保存动作记录
// * @param methodName
// * @param paramsAndTypes
// * @param matchedObj
// */
// public void process(Object bean,String methodName,String paramsAndTypes,Object matchedObj)
// {
//
// if(bean instanceof CustomerAction)
// {
// Set set = (Set) matchedObj;
// BasicsRo fireEquimentDataRo = (BasicsRo) set.iterator().next();
//
// RuleRuningSnapshot ruleRuningSnapshot = new RuleRuningSnapshot();
// ruleRuningSnapshot.setId(UUID.randomUUID().toString());
// ruleRuningSnapshot.setMethodClass(bean.getClass().getName());
// ruleRuningSnapshot.setMethodName(methodName);
// ruleRuningSnapshot.setMethodParam(paramsAndTypes);
//
// ruleRuningSnapshot.setBatchNo(fireEquimentDataRo.getBatchNo());
// ruleRuningSnapshot.setPackageId(fireEquimentDataRo.getPackageId());
// ruleRuningSnapshot.setEquipmentId(String.valueOf(fireEquimentDataRo.getId()));
//
// Date now = new Date();
// ruleRuningSnapshot.setCreateTime(now);
// ruleRuningSnapshot.setCreateMillisecond(String.valueOf(now.getTime()));
// ruleRuningSnapshot.setPreviousInterval(0L);
// RuleRuningSnapshot oldEntity = repository.querForObject(fireEquimentDataRo.getBatchNo());
// if(oldEntity != null)
// ruleRuningSnapshot.setPreviousInterval(now.getTime() - Long.parseLong(oldEntity.getCreateMillisecond()));
// this.repository.save(ruleRuningSnapshot);
// }
// }
@Async
public void replay(String batchNo) throws Exception
{
if(replayBatchNo != null)
throw new Exception("一次只能回放一个预案记录.");
try
{
replayBatchNo = batchNo;
List<RuleRuningSnapshot> oldEntityList=ruleRuningSnapshotMapper.querForObjectList(batchNo);
// List<RuleRuningSnapshot> oldEntityList = repository.querForObjectList(batchNo);
if(!CollectionUtils.isEmpty(oldEntityList))
{
logger.info("开始回放:batchNo="+batchNo);
logger.info("获取到动作记录个数:"+oldEntityList.size());
int count = 0;
for(RuleRuningSnapshot snapshot : oldEntityList)
{
if(replayBatchNo == null)
return ;
//延迟
logger.info("开始执行第"+(++count)+"个动作.");
logger.info("方法名:"+snapshot.getMethodClass()+"."+snapshot.getMethodName());
logger.info("需要延迟"+snapshot.getPreviousInterval()+"毫秒.......");
Thread.sleep(snapshot.getPreviousInterval());
try
{
Class clzz = Class.forName(snapshot.getMethodClass());
Object obj = SpringContextHelper.getBean(clzz);
Method[] methods=clzz.getMethods();
if(!StringUtils.isEmpty(snapshot.getMethodParam()))
{
for(Method method:methods)
{
if(replayBatchNo == null)
return ;
String name=method.getName();
if(!name.equals(snapshot.getMethodName())){
continue;
}
Map paramsMap = objectMapper.readValue(snapshot.getMethodParam(), Map.class);
List<String> datatypes = (List<String>)paramsMap.get("datatypes");
List<Object> values = (List<Object>)paramsMap.get("values");
Object[] params = new Object[values.size()];
for(int i = 0;i<datatypes.size();i++)
{
if(replayBatchNo == null)
return ;
String typeStr = datatypes.get(i);
Object value = values.get(i);
String valueStr = objectMapper.writeValueAsString(value);
Class valueClzz = Class.forName(typeStr);
params[i] = objectMapper.readValue(valueStr,valueClzz);
}
method.invoke(obj,params);
}
}else{
Method method = clzz.getMethod(snapshot.getMethodName(),new Class[]{});
method.invoke(obj);
}
logger.info("第"+(count)+"个动作执行成功.");
}catch (Exception e)
{
logger.info("第"+(count)+"个动作执行失败.");
e.printStackTrace();
logger.error(e.getMessage(),e);
}
}
}
}catch (Exception e)
{
logger.info("回放失败.");
logger.error(e.getMessage(),e);
}finally {
replayBatchNo = null;
}
}
public static String getReplayBatchNo() {
return replayBatchNo;
}
public static void setReplayBatchNoToNull() {
RuleRunigSnapshotServiceImpl.replayBatchNo = null;
}
}
\ No newline at end of file
...@@ -20,5 +20,5 @@ public interface IContingencyInstance { ...@@ -20,5 +20,5 @@ public interface IContingencyInstance {
void fire(String batchNo,String stepCode, String contingencyPlanId, String buttonCode,String buttonState,String stepStateOnbutton) throws Exception; void fire(String batchNo,String stepCode, String contingencyPlanId, String buttonCode,String buttonState,String stepStateOnbutton) throws Exception;
void updateStep(String step, String batchNo);
} }
package com.yeejoin.amos.fas.business.service.intfc;
/**
*
* <pre>
* 三维节点与规则消息实体视图service
* </pre>
*
* @version $Id: INodeMsgViewService.java, v 0.1 2019年1月2日 下午2:48:40 amos Exp $
*/
public interface IRuleRunningSnapshotService
{
void replay(String batchNo) throws Exception;
}
package com.yeejoin.amos.fas.business.service.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
@Entity
@Table(name = "toip_rm_snapshot")
public class RuleRuningSnapshot implements Serializable {
private static final long serialVersionUID = 292329658525267887L;
@Id
private String id ;
@Column(name = "batch_no")
private String batchNo ;// '规则执行的批次号',
@Column(name = "package_id")
private String packageId ;// '规则包id',
@Column(name = "method_class")
private String methodClass ;// 'bean方法的类名',
@Column(name = "method_name")
private String methodName ;// 'bean方法名',
@Column(name = "equipment_id")
private String equipmentId ;// '设备类型',
@Column(name = "method_param")
private String methodParam ;// 方法参数',
@Column(name = "create_time")
private Date createTime ;// 创建时间',
@Column(name = "create_millisecond")
private String createMillisecond ;// 当前动作执行时的毫秒数',
@Column(name = "previous_interval")
private Long previousInterval ;// 与上一次的动作执行的时间差',
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBatchNo() {
return batchNo;
}
public void setBatchNo(String batchNo) {
this.batchNo = batchNo;
}
public String getPackageId() {
return packageId;
}
public void setPackageId(String packageId) {
this.packageId = packageId;
}
public String getMethodClass() {
return methodClass;
}
public void setMethodClass(String methodClass) {
this.methodClass = methodClass;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getEquipmentId() {
return equipmentId;
}
public void setEquipmentId(String equipmentId) {
this.equipmentId = equipmentId;
}
public String getMethodParam() {
return methodParam;
}
public void setMethodParam(String methodParam) {
this.methodParam = methodParam;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreateMillisecond() {
return createMillisecond;
}
public void setCreateMillisecond(String createMillisecond) {
this.createMillisecond = createMillisecond;
}
public Long getPreviousInterval() {
return previousInterval;
}
public void setPreviousInterval(Long previousInterval) {
this.previousInterval = previousInterval;
}
}
package com.yeejoin.amos.fas.business.service.model;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.dao.entity.BusinessEntity;
/**
*
* <pre>
*
* </pre>
*
* @author HK
* @version $Id: ToipResponse.java, v 0.1 2018年1月26日 下午5:02:12 HK Exp $
*/
public class ToipResponse extends CommonResponse
{
// 具体界面域由三部分组成: [IFDomain].[group].[template], 其中 group可选 [IFDomain].[template]
// dispatch.map.marker.basic
/**
* <pre>
*
* </pre>
*/
private static final long serialVersionUID = 1L;
/**
* 界面域
* 例如
* dispatch.map
*/
private String IFDomain;
/**
* 模板类型
* 例如
* basic
*/
private String template;
/**
* 模板组
* 例如
* marker
*/
private String group;
/**
* 智能体业务对象
*/
private BusinessEntity bizObj;
/**
* 动作ID
*/
private String actionId;
/**
* 火灾id
*/
private String fireId;
private String domainView;
public String getIFDomain()
{
return IFDomain;
}
public void setIFDomain(String iFDomain)
{
IFDomain = iFDomain;
}
public String getTemplate()
{
return template;
}
public void setTemplate(String template)
{
this.template = template;
}
public String getGroup()
{
return group;
}
public void setGroup(String group)
{
this.group = group;
}
public BusinessEntity getBizObj() {
return bizObj;
}
public void setBizObj(BusinessEntity bizObj) {
this.bizObj = bizObj;
}
public String getActionId() {
return actionId;
}
public void setActionId(String actionId) {
this.actionId = actionId;
}
public String getDomainView() {
return domainView;
}
public void setDomainView(String domainView) {
this.domainView = domainView;
}
public String getFireId() {
return fireId;
}
public void setFireId(String fireId) {
this.fireId = fireId;
}
}
...@@ -46,5 +46,14 @@ file.uploadUrl=D:\\upload\\files\\ ...@@ -46,5 +46,14 @@ file.uploadUrl=D:\\upload\\files\\
file.readUrl=http://172.16.3.89:8083/file/getFile?in= file.readUrl=http://172.16.3.89:8083/file/getFile?in=
params.isPush=true params.isPush=true
## emqx
emqx.clean-session=true
emqx.client-id=${spring.application.name}-${random.int[1024,65536]}
emqx.broker=tcp://172.16.10.85:1883
emqx.user-name=super
emqx.password=a123456
Push.fegin.name=PPMESSAGEPUSHSERVICE15 Push.fegin.name=PPMESSAGEPUSHSERVICE15
dutyMode.fegin.name=AMOS-DUTY dutyMode.fegin.name=AMOS-DUTY
\ No newline at end of file
bussunis.domain=http://172.16.10.183:8083
\ No newline at end of file
...@@ -45,5 +45,15 @@ file.uploadUrl=D:\\upload\\files\\ ...@@ -45,5 +45,15 @@ file.uploadUrl=D:\\upload\\files\\
#picture read #picture read
file.readUrl=http://station-fireautosys:8083/file/getFile?in= file.readUrl=http://station-fireautosys:8083/file/getFile?in=
params.isPush=true params.isPush=true
## emqx
emqx.clean-session=true
emqx.client-id=${spring.application.name}-${random.int[1024,65536]}
emqx.broker=tcp://172.16.10.85:1883
emqx.user-name=super
emqx.password=a123456
Push.fegin.name=AMOS-PUSH Push.fegin.name=AMOS-PUSH
dutyMode.fegin.name=AMOS-DUTY dutyMode.fegin.name=AMOS-DUTY
\ No newline at end of file
bussunis.domain=http://172.16.10.183:8083
\ No newline at end of file
...@@ -46,5 +46,14 @@ file.uploadUrl=D:\\upload\\files\\ ...@@ -46,5 +46,14 @@ file.uploadUrl=D:\\upload\\files\\
file.readUrl=http://172.16.3.89:8083/file/getFile?in= file.readUrl=http://172.16.3.89:8083/file/getFile?in=
params.isPush=true params.isPush=true
## emqx
emqx.clean-session=true
emqx.client-id=${spring.application.name}-${random.int[1024,65536]}
emqx.broker=tcp://172.16.10.85:1883
emqx.user-name=super
emqx.password=a123456
Push.fegin.name=PPMESSAGEPUSHSERVICE15 Push.fegin.name=PPMESSAGEPUSHSERVICE15
dutyMode.fegin.name=AMOS-DUTY dutyMode.fegin.name=AMOS-DUTY
\ No newline at end of file
bussunis.domain=http://172.16.10.183:8083
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yeejoin.amos.fas.business.dao.mapper.RuleRuningSnapshotMapper">
<select id="querForObject" resultType="com.yeejoin.amos.fas.business.service.model.RuleRuningSnapshot">
SELECT * FROM toip_rm_snapshot t WHERE t.batch_no = #{batchNo} ORDER BY t.create_millisecond DESC limit 0,1
</select>
<select id="querForObjectList" resultType="com.yeejoin.amos.fas.business.service.model.RuleRuningSnapshot">
SELECT * FROM toip_rm_snapshot t WHERE t.batch_no = #{batchNo} ORDER BY t.create_millisecond
</select>
</mapper>
\ No newline at end of file
...@@ -31,6 +31,11 @@ ...@@ -31,6 +31,11 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>com.yeejoin</groupId>
<artifactId>amos-component-rule</artifactId>
<version>1.1.0-SNAPSHOT</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment