Explorar o código

添加从终端mongo数据采集至中心mongo

zhenglingfeng %!s(int64=8) %!d(string=hai) anos
pai
achega
184a83e653

+ 73 - 0
hos-broker/src/main/java/com/yihu/hos/broker/common/camelrouter/CenterMongoRouter.java

@ -0,0 +1,73 @@
package com.yihu.hos.broker.common.camelrouter;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.bson.types.ObjectId;
import org.json.JSONArray;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class CenterMongoRouter extends RouteBuilder {
    static public final String DESTINATION_NAME = "business-log";
    @Override
    public void configure() throws Exception {
        from("quartz://myGroup/myTimerName?cron=0 0 0 1 /1 * ?")
            .setBody().constant("{ \"flowType\": \"class\" }")
            .to("mongodb:mongo?database=runtime&collection=serviceFlow&operation=findOneByQuery")
            .split(simple("${body}"))
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    addMongoInfo(exchange, "runtime", "serviceFlow");
                }
            }).to("bean:centerMongoService?method=log")
            .setBody().constant("{ \"tenant\": \"yichang\" }")
            .to("mongodb:mongo?database=runtime&collection=arbiterServer&operation=findOneByQuery")
            .split(simple("${body}"))
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    addMongoInfo(exchange, "runtime", "arbiterServer");
                }
            }).to("bean:centerMongoService?method=log");
//
//            .setBody().constant("{ \"flowType\": \"class\" }")
//            .to("mongodb:mongo?database=runtime&collection=brokerServer&operation=findOneByQuery")
//            .split(simple("${body}"))
//            .process(new Processor() {
//                @Override
//                public void process(Exchange exchange) throws Exception {
//                    addMongoInfo(exchange, "runtime", "serviceFlow");
//                }
//            }).to("bean:centerMongoService?method=log")
//
//            .setBody().constant("{ \"flowType\": \"class\" }")
//            .to("mongodb:mongo?database=runtime&collection=serviceFlow&operation=findOneByQuery")
//            .split(simple("${body}"))
//            .process(new Processor() {
//                @Override
//                public void process(Exchange exchange) throws Exception {
//                    addMongoInfo(exchange, "runtime", "serviceFlow");
//                }
//            }).to("bean:centerMongoService?method=log");
    }
    public void addMongoInfo(Exchange exchange, String database, String collection) {
        Map record = exchange.getIn().getBody(Map.class);
        Map info = new HashMap();
        info.put("database", database);
        info.put("collection", collection);
        ObjectId objectId = (ObjectId) record.get("_id");
        record.put("_id", objectId.toString());
        JSONArray jsonArray = new JSONArray();
        jsonArray.put(info);
        jsonArray.put(record);
        exchange.getIn().setBody(jsonArray);
    }
}

+ 2 - 0
hos-broker/src/main/java/com/yihu/hos/broker/common/constants/MonitorConstant.java

@ -8,6 +8,8 @@ package com.yihu.hos.broker.common.constants;
public class MonitorConstant {
    public static String MONITOR_DATABASE = "log";
    public static String SERVER = "server";
    public static String SERVICE = "service";
    public static String BUSSINESS_LOG = "businessLog";
    public static String HOST = "host";     //这个是否需要,可以在runtime库中使用brokerServer?

+ 9 - 114
hos-broker/src/main/java/com/yihu/hos/broker/common/scheduler/MonitorScheduler.java

@ -1,29 +1,13 @@
package com.yihu.hos.broker.common.scheduler;
import com.mongodb.*;
import com.yihu.hos.broker.common.constants.MonitorConstant;
import com.yihu.hos.broker.daos.BrokerDao;
import com.yihu.hos.broker.models.SystemServiceEndpoint;
import com.yihu.hos.broker.models.SystemServiceFlow;
import com.yihu.hos.broker.services.ServerMonitorService;
import com.yihu.hos.broker.services.ServiceMonitorService;
import com.yihu.hos.broker.util.SigarUtil;
import com.yihu.hos.core.datatype.DateUtil;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * 服务器性能数据采集定时器
@ -36,28 +20,17 @@ import java.util.List;
public class MonitorScheduler {
    static private final Logger logger = LoggerFactory.getLogger(MonitorScheduler.class);
    private static String host = SigarUtil.getHost();
    @Value("${hos.tenant.name}")
    private String tenant;
    @Autowired
    private MongoOperations mongoOperations;
    @Autowired
    private Mongo mongo;
    @Resource(name = ServiceMonitorService.BEAN_ID)
    private ServiceMonitorService serviceMonitorService;
    @Autowired
    private BrokerDao brokerDao;
    @Resource(name = ServerMonitorService.BEAN_ID)
    private ServerMonitorService serverMonitorService;
    @Scheduled(cron = "0 0/1 * * * ?") //每分钟执行一次
    public void statusCheck() {
        System.out.println("每分钟执行一次。开始============================================");
        //TODO 采集服务器健康监控指标数据 statusTask.healthCheck();
        collectEnvHealth();
        try {
            collectServiceHealth();
        } catch (Exception e) {
            e.printStackTrace();
        }
        collectServiceHealth();
        System.out.println("每分钟执行一次。结束。");
    }
@ -66,69 +39,12 @@ public class MonitorScheduler {
     *
     * @return
     */
    public String collectEnvHealth() {
        try {
            mongoOperations = new MongoTemplate(mongo, MonitorConstant.MONITOR_DATABASE);
            Document result = null;
            result = new Document();
            result.put("tenant", tenant);
            result.put("create_date", DateUtil.getCurrentString(DateUtil.DEFAULT_YMDHMSDATE_FORMAT));
            result.put("create_time", new Date());
            result.put("host", host);
            //cpu
            JSONObject cpu = JSONObject.fromObject(SigarUtil.cpu());
            result.put("data", cpu);
            result.put("type", MonitorConstant.CPU);
            mongoOperations.insert(result, MonitorConstant.SERVER);
            //内存
            JSONObject memory = JSONObject.fromObject(SigarUtil.memory());
            result.put("data", memory);
            result.put("type", MonitorConstant.MEMORY);
            result.remove("_id");
            mongoOperations.insert(result, MonitorConstant.SERVER);
            //硬盘
            List<JSONObject> files = JSONArray.fromObject(SigarUtil.file());
            result.put("data", files);
            result.put("type", MonitorConstant.FILES);
            result.remove("_id");
            mongoOperations.insert(result, MonitorConstant.SERVER);
            //网络
            JSONObject net = JSONObject.fromObject(SigarUtil.net());
            result.put("data", net);
            result.put("type", MonitorConstant.NET);
            result.remove("_id");
            mongoOperations.insert(result, MonitorConstant.SERVER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    public void collectEnvHealth() {
        serverMonitorService.collectEnvHealth();
    }
    public void collectServiceHealth() throws Exception {
        Date now = new Date();
        Date beforeDate = new Date(now.getTime() - 60000);
        String beginTime = DateUtil.toString(beforeDate, DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
        String endTime = DateUtil.toString(now, DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
        List<SystemServiceFlow> flowList = brokerDao.getSystemServiceFlowList();
        List<SystemServiceEndpoint> endpointList = brokerDao.getSystemServiceEndpointList();
        List<String> codeList = new ArrayList<>();
        for (SystemServiceFlow systemServiceFlow : flowList) {
            codeList.add(systemServiceFlow.getCode());
        }
        for (SystemServiceEndpoint systemServiceEndpoint : endpointList) {
            codeList.add(systemServiceEndpoint.getCode());
        }
        serviceMonitorService.bandwidth(beginTime, endTime, codeList);
        serviceMonitorService.qps(beginTime, endTime, codeList);
        serviceMonitorService.delay(beginTime, endTime, codeList);
        serviceMonitorService.usage(beginTime, endTime, codeList);
    public void collectServiceHealth() {
        serviceMonitorService.collectServiceHealth();
    }
    /**
@ -137,28 +53,7 @@ public class MonitorScheduler {
//    @Scheduled(cron = "0 0 12 * * ?") //每天中午12点触发
    @Scheduled(fixedDelay = 3600 * 24 * 1000, initialDelay = 3000) //每天中午12点触发
    public void checkHost() {
        mongoOperations = new MongoTemplate(mongo, MonitorConstant.MONITOR_DATABASE);
        DBCollection envCollection = mongoOperations.getCollection(MonitorConstant.HOST);
        BasicDBObject queryObject = new BasicDBObject().append(QueryOperators.AND,
                new BasicDBObject[]{
                        new BasicDBObject().append("host", host),
                        new BasicDBObject().append("tenant", tenant)});
        DBCursor cursor = envCollection.find(queryObject);
        if (cursor.size() < 1) {
            try {
                Document result = new Document();
                String host = SigarUtil.getHost();
                String hostName = SigarUtil.getHostName();
                result.put("tenant", tenant);
                result.put("name", hostName);
                result.put("host", host);
                mongoOperations.insert(result, MonitorConstant.HOST);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        serverMonitorService.checkHost();
    }
}

+ 10 - 4
hos-broker/src/main/java/com/yihu/hos/broker/configurations/MongoConfiguration.java

@ -21,6 +21,8 @@ public class MongoConfiguration extends AbstractMongoConfiguration {
    @Value("${spring.data.mongodb.host}")
    private String host;
    @Value("${spring.data.centerdb.host}")
    private String centerHost;
    @Value("${spring.data.mongodb.port}")
    private int port;
    @Value("${spring.data.mongodb.username}")
@ -31,27 +33,31 @@ public class MongoConfiguration extends AbstractMongoConfiguration {
    private String authenticationDatabase;
    @Value("${spring.data.mongodb.database}")
    private String database;
    private static MongoClient mongoclient;
    @Override
    public String getDatabaseName() {
        return database;
    }
    @Override
    @Bean
    public Mongo mongo() throws Exception {
        return new MongoClient(singletonList(new ServerAddress(host, port)),
                singletonList(MongoCredential.createCredential(username, authenticationDatabase, password.toCharArray())));
    }
    private static MongoClient mongo;
    @Bean
    public Mongo centerMongo() throws Exception {
        return new MongoClient(singletonList(new ServerAddress(centerHost, port)),
                singletonList(MongoCredential.createCredential(username, authenticationDatabase, password.toCharArray())));
    }
    public MongoClient mongoClient() throws Exception {
        if(mongo == null) {
        if(mongoclient == null) {
            return new MongoClient(singletonList(new ServerAddress(host, port)),
                    singletonList(MongoCredential.createCredential(username, authenticationDatabase, password.toCharArray())));
        }
        return mongo;
        return mongoclient;
    }
}

+ 0 - 66
hos-broker/src/main/java/com/yihu/hos/broker/models/ServiceMetrics.java

@ -1,66 +0,0 @@
package com.yihu.hos.broker.models;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/**
 * @created Airhead 2016/8/8.
 */
@Document(collection = "serviceMetrics")
public class ServiceMetrics {
    @Id
    private String id;
    private String type;
    private String name;
    private String value;
    private String createTime;
    private String tenant;
    public String getTenant() {
        return tenant;
    }
    public void setTenant(String tenant) {
        this.tenant = tenant;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public String getCreateTime() {
        return createTime;
    }
    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
}

+ 39 - 0
hos-broker/src/main/java/com/yihu/hos/broker/services/CenterMongoService.java

@ -0,0 +1,39 @@
package com.yihu.hos.broker.services;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component("centerMongoService")
public class CenterMongoService {
    private static final Logger logger = LoggerFactory.getLogger(CenterMongoService.class);
    @Autowired
    private Mongo centerMongo;
    public void log(String msg) {
        JSONArray jsonArray = new JSONArray(msg);
        JSONObject info = (JSONObject) jsonArray.get(0);
        String database = info.getString("database");
        String collection = info.getString("collection");
        DBCollection center = centerMongo.getDB(database).getCollection(collection);
        JSONObject record = (JSONObject) jsonArray.get(1);
        BasicDBObject dbObject = new BasicDBObject();
        for (Object key : record.keySet()) {
            dbObject.put((String) key, record.get((String) key).toString());
        }
        try {
            center.save(dbObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(info);
        System.out.println(record);
    }
}

+ 107 - 0
hos-broker/src/main/java/com/yihu/hos/broker/services/ServerMonitorService.java

@ -0,0 +1,107 @@
package com.yihu.hos.broker.services;
import com.mongodb.*;
import com.yihu.hos.broker.common.constants.MonitorConstant;
import com.yihu.hos.broker.util.SigarUtil;
import com.yihu.hos.core.datatype.DateUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
 * Created by chenweida on 2016/1/27.
 */
@Service("ServerMonitorService")
public class ServerMonitorService {
    public static final String BEAN_ID = "ServerMonitorService";
    @Value("${hos.tenant.name}")
    private String tenant;
    private static String host = SigarUtil.getHost();
    @Autowired
    private Mongo mongo;
    @Autowired
    private Mongo centerMongo;
    /**
     * 服务器健康指标采集
     *
     * @return
     */
    public void collectEnvHealth() {
        try {
            BasicDBObject result = new BasicDBObject();
            DBCollection terminal = mongo.getDB(MonitorConstant.MONITOR_DATABASE).getCollection(MonitorConstant.SERVER);
            DBCollection center = centerMongo.getDB(MonitorConstant.MONITOR_DATABASE).getCollection(MonitorConstant.SERVER);
            result.put("tenant", tenant);
            result.put("create_date", DateUtil.getCurrentString(DateUtil.DEFAULT_YMDHMSDATE_FORMAT));
            result.put("create_time", new Date());
            result.put("host", host);
            //cpu
            net.sf.json.JSONObject cpu = net.sf.json.JSONObject.fromObject(SigarUtil.cpu());
            result.put("data", cpu);
            result.put("type", MonitorConstant.CPU);
            terminal.insert(result);
            center.insert(result);
            //内存
            net.sf.json.JSONObject memory = net.sf.json.JSONObject.fromObject(SigarUtil.memory());
            result.put("data", memory);
            result.put("type", MonitorConstant.MEMORY);
            result.remove("_id");
            terminal.insert(result);
            center.insert(result);
            //硬盘
            List<net.sf.json.JSONObject> files = JSONArray.fromObject(SigarUtil.file());
            result.put("data", files);
            result.put("type", MonitorConstant.FILES);
            result.remove("_id");
            terminal.insert(result);
            center.insert(result);
            //网络
            JSONObject net = JSONObject.fromObject(SigarUtil.net());
            result.put("data", net);
            result.put("type", MonitorConstant.NET);
            result.remove("_id");
            terminal.insert(result);
            center.insert(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void checkHost() {
        DBCollection terminal = mongo.getDB(MonitorConstant.MONITOR_DATABASE).getCollection(MonitorConstant.HOST);
        DBCollection center = centerMongo.getDB(MonitorConstant.MONITOR_DATABASE).getCollection(MonitorConstant.HOST);
        BasicDBObject queryObject = new BasicDBObject().append(QueryOperators.AND,
                new BasicDBObject[]{
                        new BasicDBObject().append("host", host),
                        new BasicDBObject().append("tenant", tenant)});
        DBCursor cursor = terminal.find(queryObject);
        if (cursor.size() < 1) {
            try {
                BasicDBObject result = new BasicDBObject();
                String host = SigarUtil.getHost();
                String hostName = SigarUtil.getHostName();
                result.put("tenant", tenant);
                result.put("name", hostName);
                result.put("host", host);
                terminal.insert(result);
                center.insert(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

+ 46 - 18
hos-broker/src/main/java/com/yihu/hos/broker/services/ServiceMonitorService.java

@ -3,22 +3,20 @@ package com.yihu.hos.broker.services;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.*;
import com.yihu.hos.broker.models.BusinessLog;
import com.yihu.hos.broker.models.ServiceMetrics;
import com.yihu.hos.broker.common.constants.MonitorConstant;
import com.yihu.hos.broker.daos.BrokerDao;
import com.yihu.hos.broker.models.SystemServiceEndpoint;
import com.yihu.hos.broker.models.SystemServiceFlow;
import com.yihu.hos.core.datatype.DateUtil;
import com.yihu.hos.core.datatype.NumberUtil;
import com.yihu.hos.core.datatype.StringUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
 * Created by chenweida on 2016/1/27.
@ -29,19 +27,46 @@ public class ServiceMonitorService {
    @Value("${hos.tenant.name}")
    private String tenant;
    @Autowired
    private MongoOperations mongoOperations;
    private Mongo mongo;
    @Autowired
    private Mongo centerMongo;
    @Autowired
    private BrokerDao brokerDao;
    private DBCollection businessLog;
    public DBCollection getBusinessLog() {
        if (businessLog == null) {
            businessLog = mongoOperations.getCollection(mongoOperations
                    .getCollectionName(BusinessLog.class));
            businessLog = mongo.getDB(MonitorConstant.MONITOR_DATABASE).getCollection(MonitorConstant.BUSSINESS_LOG);
        }
        return businessLog;
    }
    public void collectServiceHealth() {
        try {
            Date now = new Date();
            Date beforeDate = new Date(now.getTime() - 60000);
            String beginTime = DateUtil.toString(beforeDate, DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
            String endTime = DateUtil.toString(now, DateUtil.DEFAULT_YMDHMSDATE_FORMAT);
            List<SystemServiceFlow> flowList = brokerDao.getSystemServiceFlowList();
            List<SystemServiceEndpoint> endpointList = brokerDao.getSystemServiceEndpointList();
            List<String> codeList = new ArrayList<>();
            for (SystemServiceFlow systemServiceFlow : flowList) {
                codeList.add(systemServiceFlow.getCode());
            }
            for (SystemServiceEndpoint systemServiceEndpoint : endpointList) {
                codeList.add(systemServiceEndpoint.getCode());
            }
            bandwidth(beginTime, endTime, codeList);
            qps(beginTime, endTime, codeList);
            delay(beginTime, endTime, codeList);
            usage(beginTime, endTime, codeList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void bandwidth(String beginTime, String endTime, List<String> codeList) {
@ -356,13 +381,16 @@ public class ServiceMonitorService {
    }
    public void saveServiceMetrics(String name, String type, String value, String createTime) {
        ServiceMetrics serviceMetrics = new ServiceMetrics();
        serviceMetrics.setTenant(tenant);
        serviceMetrics.setName(name);
        serviceMetrics.setType(type);
        serviceMetrics.setValue(value);
        serviceMetrics.setCreateTime(createTime);
        mongoOperations.save(serviceMetrics);
        BasicDBObject document = new BasicDBObject();
        document.put("tenant", tenant);
        document.put("name", name);
        document.put("type", type);
        document.put("value", value);
        document.put("createTime", createTime);
        DBCollection terminal = mongo.getDB(MonitorConstant.MONITOR_DATABASE).getCollection(MonitorConstant.SERVICE);
        terminal.save(document);
        DBCollection center = centerMongo.getDB(MonitorConstant.MONITOR_DATABASE).getCollection(MonitorConstant.SERVICE);
        center.save(document);
    }
    public Integer isNull(Integer count) {

+ 3 - 1
hos-broker/src/main/resources/application.yml

@ -35,8 +35,10 @@ spring:
      user: admin
      password: admin
  data:
    mongodb:
    centerdb:
      host: 172.19.103.57
    mongodb:
      host: 172.19.103.58
      port: 27017
      username: esb
      password: esb

+ 1 - 1
src/main/java/com/yihu/hos/monitor/service/ServiceMonitorService.java

@ -33,7 +33,7 @@ import java.util.Map;
public class ServiceMonitorService {
    public static final String BEAN_ID = "ServiceMonitorService";
    public static final String dbName = "log";
    public static final String tableName = "serviceMetrics";
    public static final String tableName = "service";
    public static final String serviceFlow = "serviceFlow";
    public static final String configuration = "configuration";

+ 9 - 0
src/main/java/com/yihu/hos/system/controller/ProcessController.java

@ -60,6 +60,15 @@ public class ProcessController  extends BaseController {
        }
    }
    @RequestMapping(value = "/getAllProcessor", method = RequestMethod.GET)
    public Result getAllProcessor() {
        try {
            return processManager.getAllProcessor();
        } catch (Exception e) {
            return Result.error("查找所有转换器失败");
        }
    }
    @RequestMapping(value = "/json", method = RequestMethod.POST)
    public Result formatJson(String code, String name, String positionJson, String flowJson) {
        try {

+ 66 - 30
src/main/java/com/yihu/hos/system/service/ProcessManager.java

@ -8,8 +8,11 @@ import com.yihu.hos.core.encrypt.DES;
import com.yihu.hos.system.dao.AppDao;
import com.yihu.hos.system.dao.AppServiceDao;
import com.yihu.hos.system.dao.FlowProcessDao;
import com.yihu.hos.system.dao.ProcessorDao;
import com.yihu.hos.system.model.SystemApp;
import com.yihu.hos.system.model.SystemServiceEndpoint;
import com.yihu.hos.system.model.SystemServiceFlowProcess;
import com.yihu.hos.system.model.SystemServiceFlowProcessor;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.GridFSUtil;
import org.springframework.beans.factory.annotation.Autowired;
@ -18,6 +21,7 @@ import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
@Service("ProcessManager")
@ -29,15 +33,17 @@ public class ProcessManager {
    private AppDao appDao;
    @Resource(name = AppServiceDao.BEAN_ID)
    private AppServiceDao appServiceDao;
    @Resource(name = ProcessorDao.BEAN_ID)
    private ProcessorDao processorDao;
    @Resource(name = FlowProcessDao.BEAN_ID)
    private FlowProcessDao processDao;
    private ObjectMapper objectMapper = new ObjectMapper();
    public Result getAllApp() throws Exception {
        String hql = "select * from SystemServiceEndpoint";
        List<SystemServiceEndpoint> serviceEndpointList = appServiceDao.getEntityList(SystemServiceEndpoint.class, hql);
        String result = objectMapper.writeValueAsString(serviceEndpointList);
        String hql = "select * from SystemApp";
        List<SystemApp> appList = appDao.getEntityList(SystemApp.class, hql);
        String result = objectMapper.writeValueAsString(appList);
        return Result.success(result);
    }
@ -55,6 +61,13 @@ public class ProcessManager {
        return Result.success(result);
    }
    public Result getAllProcessor() throws Exception {
        String hql = "select * from SystemServiceFlowProcessor";
        List<SystemServiceFlowProcessor> processorList = processorDao.getEntityList(SystemServiceFlowProcessor.class, hql);
        String result = objectMapper.writeValueAsString(processorList);
        return Result.success(result);
    }
    public void saveProcess(String code, String name, String fileName, String positionJsonStr) throws Exception {
        SystemServiceFlowProcess process = new SystemServiceFlowProcess();
        process.setCode(code);
@ -98,7 +111,6 @@ public class ProcessManager {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode flowJson = objectMapper.readValue(flowJsonStr, JsonNode.class);
        String code = flowJson.get("code").asText();
        String javaName = toUpperCaseFirstOne(code)+"Route";
        //sort flow by lines
        JsonNode lines = flowJson.get("lines");
        Iterator<JsonNode> lineIterator = lines.iterator();
@ -145,9 +157,14 @@ public class ProcessManager {
        }
        //mosaic the java code
        //generate the java code
        return generate(code, processorImport, nodeMap, nodeNameArray);
    }
    public String generate(String code, List<String> processorImport, Map<String, JsonNode> nodeMap, String[] nodeNameArray) throws IOException {
        Boolean isFirstNodeFlg = true;
        StringBuilder javaBuilder = new StringBuilder();
        String javaName = toUpperCaseFirstOne(code)+"Route";
        javaBuilder.append("package "+code+".route;\n\n");
        javaBuilder.append("import org.apache.camel.Exchange;\n");
@ -158,7 +175,8 @@ public class ProcessManager {
        javaBuilder.append("public class "+javaName+" extends RouteBuilder {\n");
        javaBuilder.append("public void configure() throws Exception {\n");
        for (String nodeName : nodeNameArray) {
        for (int i=0;i<nodeNameArray.length;i++) {
            String nodeName = nodeNameArray[i];
            JsonNode node = nodeMap.get(nodeName);
            String type = node.get("type").asText();
            String value = node.get("value").asText();
@ -171,6 +189,27 @@ public class ProcessManager {
            } else {
                if (type.equals("processor")) {
                    javaBuilder.append("\n.process(\"new "+name+"())");
                } else if (type.equals("judgement")) {
                    String correctNodeName = value.split(",")[1];
                    value = value.split(",")[0];
                    javaBuilder.append("\n.when("+value+")");
                    String nodeName1 = nodeNameArray[++i];
                    JsonNode node1 = nodeMap.get(nodeName1);
                    String nodeName2 = nodeNameArray[++i];
                    JsonNode node2 = nodeMap.get(nodeName2);
                    String firstValue = node1.get("value").asText();
                    String secondValue =  node2.get("value").asText();
                    if (!correctNodeName.equals(nodeName1)) {
                        secondValue = node1.get("value").asText();
                        firstValue =  node2.get("value").asText();
                    }
                    javaBuilder.append("\n.setHeader(Exchange.HTTP_METHOD, constant(\"POST\"))");
                    javaBuilder.append("\n.to(\"");
                    javaBuilder.append(firstValue + "\")");
                    javaBuilder.append(".otherwise()");
                    javaBuilder.append("\n.setHeader(Exchange.HTTP_METHOD, constant(\"POST\"))");
                    javaBuilder.append("\n.to(\"");
                    javaBuilder.append(secondValue + "\")");
                } else {
                    javaBuilder.append("\n.setHeader(Exchange.HTTP_METHOD, constant(\"POST\"))");
                    javaBuilder.append("\n.to(\"");
@ -181,27 +220,26 @@ public class ProcessManager {
        javaBuilder.append("\n}\n}");
        System.out.println(javaBuilder.toString());
        String packageFilePath = System.getProperty("user.dir");
        String filePath = packageFilePath + "/" + javaName + ".java";
        File file = new File(filePath);
        FileWriter fw = new FileWriter(file);
        fw.write(javaBuilder.toString());
        fw.flush();
        fw.close();//这里只是产生一个JAVA文件,简单的IO操作
        //upload to mongo
        String dbName = "upload";
        String newFileName;
        try {
            newFileName = GridFSUtil.uploadFile(filePath, file.getName(), null);
            if (!StringUtil.isEmpty(newFileName)) {
                return newFileName;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        String packageFilePath = System.getProperty("user.dir");
//
//        String filePath = packageFilePath + "/" + javaName + ".java";
//        File file = new File(filePath);
//
//        FileWriter fw = new FileWriter(file);
//        fw.write(javaBuilder.toString());
//        fw.flush();
//        fw.close();//这里只是产生一个JAVA文件,简单的IO操作
//
//        //upload to mongo
//        String newFileName;
//        try {
//            newFileName = GridFSUtil.uploadFile(filePath, file.getName(), null);
//            if (!StringUtil.isEmpty(newFileName)) {
//                return newFileName;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return "";
    }
@ -214,12 +252,10 @@ public class ProcessManager {
    }
    //首字母转大写
    public String toUpperCaseFirstOne(String s)
    {
    public String toUpperCaseFirstOne(String s) {
        if(Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }
}