package com.gzzn.omms.msgexchangeapi.msghandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.gzzn.omms.msgexchangeapi.entity.msg.Msg; import com.gzzn.omms.msgexchangeapi.service.IExchangeService; import com.gzzn.omms.msgexchangeapi.utils.JsonUtil; @Service public class MsgHandlerDispatcher { private Logger logger = LoggerFactory.getLogger(MsgHandlerDispatcher.class); @Autowired IExchangeService exchangeService; public HandlerResult dispatch(String xmlMsg) { Msg msg = exchangeService.xmlstrToObject(xmlMsg, Msg.class); String type = msg.getMeta().getType(); String subType = msg.getMeta().getStyp(); try { Class clazzHandler = Class.forName(getHandlerClassName(type,subType)); Object classObject = clazzHandler.newInstance(); Method runMethod = clazzHandler.getMethod("run", String.class); HandlerResult result = (HandlerResult) runMethod.invoke(classObject, xmlMsg); return result; } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) { //throw new RuntimeException(e); logger.error("消息处理失败:{}",e.getMessage()); return HandlerResult.failure(); } }//end function /** * 获取handler 类的名称 * @param type * @param subType * @return */ private String getHandlerClassName(String type , String subType) { StringBuffer buffer = new StringBuffer(); buffer.append("com.gzzn.omms.msgexchangeapi.msghandler" ); buffer.append("."); buffer.append(type.toLowerCase()); buffer.append("."); buffer.append(subType); buffer.append("Handler"); return buffer.toString(); } //end function }