huangzhiyong пре 6 година
родитељ
комит
92dce8be02
100 измењених фајлова са 10749 додато и 0 уклоњено
  1. 3 0
      .gitignore
  2. 56 0
      src/main/java/com/yihu/hos/HosAdminApplication.java
  3. 111 0
      src/main/java/com/yihu/hos/app/controller/AppServiceController.java
  4. 44 0
      src/main/java/com/yihu/hos/app/dao/AppApiDao.java
  5. 10 0
      src/main/java/com/yihu/hos/app/dao/AppApiParameterDao.java
  6. 10 0
      src/main/java/com/yihu/hos/app/dao/AppApiResponseDao.java
  7. 76 0
      src/main/java/com/yihu/hos/app/dao/AppDao.java
  8. 62 0
      src/main/java/com/yihu/hos/app/dao/AppFeatureDao.java
  9. 53 0
      src/main/java/com/yihu/hos/app/dao/AppServiceDao.java
  10. 238 0
      src/main/java/com/yihu/hos/app/ehr/model/AppDetailModel.java
  11. 230 0
      src/main/java/com/yihu/hos/app/model/App.java
  12. 243 0
      src/main/java/com/yihu/hos/app/model/AppApi.java
  13. 150 0
      src/main/java/com/yihu/hos/app/model/AppApiParameter.java
  14. 89 0
      src/main/java/com/yihu/hos/app/model/AppApiResponse.java
  15. 179 0
      src/main/java/com/yihu/hos/app/model/AppFeature.java
  16. 105 0
      src/main/java/com/yihu/hos/app/model/AppFeatureTree.java
  17. 201 0
      src/main/java/com/yihu/hos/app/model/SystemServiceEndpoint.java
  18. 46 0
      src/main/java/com/yihu/hos/app/service/AppApiParameterService.java
  19. 46 0
      src/main/java/com/yihu/hos/app/service/AppApiResponseService.java
  20. 127 0
      src/main/java/com/yihu/hos/app/service/AppApiService.java
  21. 82 0
      src/main/java/com/yihu/hos/app/service/AppFeatureService.java
  22. 84 0
      src/main/java/com/yihu/hos/app/service/AppManager.java
  23. 99 0
      src/main/java/com/yihu/hos/app/service/AppServiceManage.java
  24. 38 0
      src/main/java/com/yihu/hos/common/HosAdminLogger.java
  25. 349 0
      src/main/java/com/yihu/hos/common/JXLUtil.java
  26. 150 0
      src/main/java/com/yihu/hos/common/ReflectUtil.java
  27. 119 0
      src/main/java/com/yihu/hos/common/Services.java
  28. 194 0
      src/main/java/com/yihu/hos/common/controller/BaseRestEndPoint.java
  29. 308 0
      src/main/java/com/yihu/hos/common/controller/CommonPageController.java
  30. 57 0
      src/main/java/com/yihu/hos/common/controller/EnvelopRestEndPoint.java
  31. 97 0
      src/main/java/com/yihu/hos/common/controller/ExtendEndPoint.java
  32. 353 0
      src/main/java/com/yihu/hos/common/graph/DGraphImpl.java
  33. 56 0
      src/main/java/com/yihu/hos/common/graph/Edge.java
  34. 75 0
      src/main/java/com/yihu/hos/common/graph/IDGraph.java
  35. 219 0
      src/main/java/com/yihu/hos/config/BeanConfig.java
  36. 42 0
      src/main/java/com/yihu/hos/config/JsonDateValueProcessor.java
  37. 57 0
      src/main/java/com/yihu/hos/config/MongoConfig.java
  38. 39 0
      src/main/java/com/yihu/hos/config/RedisConfig.java
  39. 28 0
      src/main/java/com/yihu/hos/config/WebMvcConfig.java
  40. 113 0
      src/main/java/com/yihu/hos/config/WebSecurityConfig.java
  41. 241 0
      src/main/java/com/yihu/hos/crawler/controller/CrawlerController.java
  42. 40 0
      src/main/java/com/yihu/hos/crawler/dao/CrawlerDatasetDao.java
  43. 40 0
      src/main/java/com/yihu/hos/crawler/dao/CrawlerFlowDao.java
  44. 32 0
      src/main/java/com/yihu/hos/crawler/dao/CrawlerFlowHeadDao.java
  45. 95 0
      src/main/java/com/yihu/hos/crawler/format/AdapterBase.java
  46. 72 0
      src/main/java/com/yihu/hos/crawler/format/AdapterScheme.java
  47. 108 0
      src/main/java/com/yihu/hos/crawler/model/adapter/AdapterDataSet.java
  48. 46 0
      src/main/java/com/yihu/hos/crawler/model/adapter/AdapterDict.java
  49. 13 0
      src/main/java/com/yihu/hos/crawler/model/adapter/AdapterDictEntry.java
  50. 62 0
      src/main/java/com/yihu/hos/crawler/model/adapter/AdapterMetaData.java
  51. 63 0
      src/main/java/com/yihu/hos/crawler/model/flow/CrawlerDataSetModel.java
  52. 53 0
      src/main/java/com/yihu/hos/crawler/model/flow/CrawlerFlowHeadModel.java
  53. 93 0
      src/main/java/com/yihu/hos/crawler/model/flow/CrawlerFlowModel.java
  54. 21 0
      src/main/java/com/yihu/hos/crawler/model/flow/resultModel/CrawlerDatasetResultDetailModel.java
  55. 21 0
      src/main/java/com/yihu/hos/crawler/model/flow/resultModel/CrawlerDatasetResultModel.java
  56. 30 0
      src/main/java/com/yihu/hos/crawler/model/flow/resultModel/FlowEntrance.java
  57. 48 0
      src/main/java/com/yihu/hos/crawler/model/flow/resultModel/FlowLines.java
  58. 41 0
      src/main/java/com/yihu/hos/crawler/model/flow/resultModel/FlowMapping.java
  59. 47 0
      src/main/java/com/yihu/hos/crawler/model/flow/resultModel/MappingDataset.java
  60. 36 0
      src/main/java/com/yihu/hos/crawler/model/flow/resultModel/MappingMetadata.java
  61. 103 0
      src/main/java/com/yihu/hos/crawler/model/patient/Patient.java
  62. 59 0
      src/main/java/com/yihu/hos/crawler/model/patient/PatientIdentity.java
  63. 110 0
      src/main/java/com/yihu/hos/crawler/model/patient/PatientIndex.java
  64. 41 0
      src/main/java/com/yihu/hos/crawler/model/standard/StdDict.java
  65. 37 0
      src/main/java/com/yihu/hos/crawler/model/standard/StdMetaData.java
  66. 9 0
      src/main/java/com/yihu/hos/crawler/model/transform/DictDataType.java
  67. 65 0
      src/main/java/com/yihu/hos/crawler/model/transform/EhrCondition.java
  68. 15 0
      src/main/java/com/yihu/hos/crawler/model/transform/IVerifier.java
  69. 12 0
      src/main/java/com/yihu/hos/crawler/model/transform/LogicValues.java
  70. 45 0
      src/main/java/com/yihu/hos/crawler/model/transform/MetaDataType.java
  71. 37 0
      src/main/java/com/yihu/hos/crawler/model/transform/MetaDataVerify.java
  72. 21 0
      src/main/java/com/yihu/hos/crawler/model/transform/TransformType.java
  73. 515 0
      src/main/java/com/yihu/hos/crawler/service/CrawlerService.java
  74. 411 0
      src/main/java/com/yihu/hos/datacollect/controller/DataCollectController.java
  75. 26 0
      src/main/java/com/yihu/hos/datacollect/controller/JobConfigController.java
  76. 26 0
      src/main/java/com/yihu/hos/datacollect/controller/JobDataSetController.java
  77. 281 0
      src/main/java/com/yihu/hos/datacollect/dao/DatacollectDao.java
  78. 78 0
      src/main/java/com/yihu/hos/datacollect/dao/DatacollectLogDao.java
  79. 19 0
      src/main/java/com/yihu/hos/datacollect/dao/JobConfigDao.java
  80. 19 0
      src/main/java/com/yihu/hos/datacollect/dao/JobDataSetDao.java
  81. 48 0
      src/main/java/com/yihu/hos/datacollect/model/DtoDatasetCol.java
  82. 48 0
      src/main/java/com/yihu/hos/datacollect/model/DtoDictCol.java
  83. 37 0
      src/main/java/com/yihu/hos/datacollect/model/DtoJobConfig.java
  84. 103 0
      src/main/java/com/yihu/hos/datacollect/model/DtoJobDataset.java
  85. 36 0
      src/main/java/com/yihu/hos/datacollect/model/DtoJobLog.java
  86. 58 0
      src/main/java/com/yihu/hos/datacollect/model/RsDatapushLog.java
  87. 193 0
      src/main/java/com/yihu/hos/datacollect/model/RsJobConfig.java
  88. 117 0
      src/main/java/com/yihu/hos/datacollect/model/RsJobDataset.java
  89. 87 0
      src/main/java/com/yihu/hos/datacollect/model/RsJobLog.java
  90. 191 0
      src/main/java/com/yihu/hos/datacollect/model/RsJobLogDetail.java
  91. 586 0
      src/main/java/com/yihu/hos/datacollect/service/DatacollectManager.java
  92. 21 0
      src/main/java/com/yihu/hos/datacollect/service/JobConfigService.java
  93. 21 0
      src/main/java/com/yihu/hos/datacollect/service/JobDataSetService.java
  94. 233 0
      src/main/java/com/yihu/hos/ehr/standard/cdatype/controller/CdaTypeEndPoint.java
  95. 229 0
      src/main/java/com/yihu/hos/ehr/standard/cdaversion/controller/VersionEndPoint.java
  96. 208 0
      src/main/java/com/yihu/hos/ehr/standard/datasets/controller/DataSetEndPoint.java
  97. 324 0
      src/main/java/com/yihu/hos/ehr/standard/datasets/controller/MetaDataEndPoint.java
  98. 265 0
      src/main/java/com/yihu/hos/ehr/standard/dict/controller/DictEndPoint.java
  99. 175 0
      src/main/java/com/yihu/hos/ehr/standard/dict/controller/DictEntryEndPoint.java
  100. 0 0
      src/main/java/com/yihu/hos/ehr/standard/dict/model/Dict.java

+ 3 - 0
.gitignore

@ -12,3 +12,6 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# idea
*.iml

+ 56 - 0
src/main/java/com/yihu/hos/HosAdminApplication.java

@ -0,0 +1,56 @@
package com.yihu.hos;
import com.yihu.hos.interceptor.WebMvcInterceptor;
import com.yihu.hos.web.framework.util.springutil.SpringBeanUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@EnableAsync
//@EnableCaching
@EnableDiscoveryClient
@EnableFeignClients
@EnableEurekaClient
@EnableZuulProxy
@EnableSpringDataWebSupport
@SpringBootApplication(scanBasePackages={"com.yihu.ehr","com.yihu.hos"})
@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class,
        SecurityAutoConfiguration.class})
public class HosAdminApplication extends WebMvcConfigurerAdapter {
    public static void main(String[] args) throws Exception {
        SpringApplication application = new SpringApplication(HosAdminApplication.class);
        ApplicationContext run = application.run(args);
//        SpringBeanUtil.setContext(run);
    }
    // 增加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(webMvcInterceptor());
    }
    @Bean
    public SpringBeanUtil springBeanUtil(){return new SpringBeanUtil();}
    @Bean
    public WebMvcInterceptor webMvcInterceptor() {
        return new WebMvcInterceptor();
    }
}

+ 111 - 0
src/main/java/com/yihu/hos/app/controller/AppServiceController.java

@ -0,0 +1,111 @@
package com.yihu.hos.app.controller;
import com.yihu.hos.app.model.SystemServiceEndpoint;
import com.yihu.hos.app.service.AppServiceManage;
import com.yihu.hos.core.constants.MicroServices;
import com.yihu.hos.core.constants.ServiceApi;
import com.yihu.hos.web.framework.model.Envelop;
import com.yihu.hos.web.framework.util.controller.BaseController;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
 * 应用管理/服务管理
 */
@RequestMapping(MicroServices.ApiVersion.Version1_0)
@Controller
public class AppServiceController extends BaseController {
    @Resource(name = AppServiceManage.BEAN_ID)
    private AppServiceManage appServiceManage;
    @RequestMapping(value = ServiceApi.AppService.GetById, method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取App服务")
    public SystemServiceEndpoint getAppService(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id") String id) throws Exception {
        SystemServiceEndpoint service = appServiceManage.getById(id);
        return service;
    }
    @RequestMapping(value = ServiceApi.AppService.Create, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @ApiOperation(value = "创建App服务")
    public SystemServiceEndpoint create(
            @ApiParam(name = "json", value = "对象JSON结构体", allowMultiple = true)
            @RequestBody String json) throws Exception {
        SystemServiceEndpoint service = toEntity(json, SystemServiceEndpoint.class);
        appServiceManage.create(service);
        return service;
    }
    @RequestMapping(value = ServiceApi.AppService.Update, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "更新App服务")
    @ResponseBody
    public SystemServiceEndpoint update(
            @ApiParam(name = "app", value = "对象JSON结构体", allowMultiple = true)
            @RequestBody String json) throws Exception {
        SystemServiceEndpoint service = toEntity(json, SystemServiceEndpoint.class);
        return appServiceManage.update(service);
    }
    @RequestMapping(value = ServiceApi.AppService.DeleteById, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除App服务")
    @ResponseBody
    public Envelop delete(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id") String id) throws Exception {
        appServiceManage.deleteById(id);
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(true);
        return envelop;
    }
    /**
     * 应用服务列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value =ServiceApi.AppService.List, method = RequestMethod.GET)
    @ApiOperation(value = "获取App服务列表")
    @ResponseBody
    public Envelop getAppList(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,secret,url,createTime,icon,releaseFlag")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size") Integer size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page") Integer page,
            HttpServletRequest request,
            HttpServletResponse response)throws Exception  {
        List<SystemServiceEndpoint> appServiceList =appServiceManage.search(fields,filters,sorts,page,size);
        List<SystemServiceEndpoint> appServices = (List)convertToModels(appServiceList, new ArrayList<>(appServiceList.size()), SystemServiceEndpoint.class, fields);
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(true);
        envelop.setDetailModelList(appServices);
        if(page!=null && size!=null){//都不为空,则为分页查询  -->>计算总页数,总条数等
            long count = appServiceManage.getCount(filters);
            int cou = (int)count;
            envelop.setTotalCount((int)count);//总条数
            envelop.setTotalPage((cou-1)/size+1);//计算总页数
        }
        return envelop;
    }
}

+ 44 - 0
src/main/java/com/yihu/hos/app/dao/AppApiDao.java

@ -0,0 +1,44 @@
package com.yihu.hos.app.dao;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.model.DataGridResult;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import java.util.Map;
@Repository("appApiDao")
public class AppApiDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "appApiDao";
    public DataGridResult getList(Map<String, Object> params, Integer page, Integer rows) throws Exception {
        StringBuilder sb = new StringBuilder("from AppApi t where 1=1 ");
        if (!StringUtils.isEmpty(params.get("id"))) {
            sb.append(" and t.id = " + params.get("id"));
        }
        if (!StringUtils.isEmpty(params.get("appId"))) {
            sb.append(" and t.appId = '" + params.get("appId") + "'");
        }
        Object name = params.get("name");
        if (!StringUtils.isEmpty(params.get("name"))) {
            sb.append(" and t.name = '" + params.get("name") + "'");
        }
        if (!StringUtils.isEmpty(params.get("type"))) {
            sb.append(" and t.type = '" + params.get("type") + "'");
        }
        if (!StringUtils.isEmpty(params.get("!type"))) {
            sb.append(" and t.type != '" + params.get("!type") + "'");
        }
        if (!StringUtils.isEmpty(params.get("parentId"))) {
            sb.append(" and t.parentId = " + params.get("parentId") );
        }
        if (!StringUtils.isEmpty(params.get("openLevel"))) {
            sb.append(" and t.openLevel = '" + params.get("openLevel")+"'" );
        }
        if (!StringUtils.isEmpty(params.get("auditLevel"))) {
            sb.append(" and t.auditLevel = '" + params.get("auditLevel")+"'" );
        }
        return super.getDataGridResult(sb.toString(), page, rows);
    }
}

+ 10 - 0
src/main/java/com/yihu/hos/app/dao/AppApiParameterDao.java

@ -0,0 +1,10 @@
package com.yihu.hos.app.dao;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import org.springframework.stereotype.Repository;
@Repository("appApiParmeterDao")
public class AppApiParameterDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "appApiParmeterDao";
}

+ 10 - 0
src/main/java/com/yihu/hos/app/dao/AppApiResponseDao.java

@ -0,0 +1,10 @@
package com.yihu.hos.app.dao;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import org.springframework.stereotype.Repository;
@Repository("appApiResponseDao")
public class AppApiResponseDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "appApiResponseDao";
}

+ 76 - 0
src/main/java/com/yihu/hos/app/dao/AppDao.java

@ -0,0 +1,76 @@
package com.yihu.hos.app.dao;
import com.yihu.hos.app.model.App;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.model.Result;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
 * Created by chenweida on 2016/1/21.
 */
@Repository("appDao")
public class AppDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "appDao";
    public Result getAppList(Map<String, Object> params) throws Exception {
        StringBuilder sb = new StringBuilder("from App t where 1=1 ");
        if (!StringUtils.isEmpty(params.get("status"))) //是否有效
        {
            sb.append(" and t.status = '" + params.get("status") + "'");
        }
        Object name = params.get("name");
        if (!StringUtils.isEmpty(name)) {
            sb.append(" and (t.name like '%" + name + "%' or t.code like '%" + name + "%')");
        }
        sb.append(" order by t.createDate desc");
        return super.getDataGridResult(sb.toString(), Integer.valueOf(params.get("page").toString()), Integer.valueOf(params.get("rows").toString()));
    }
    public List<App> getAllApplist() throws Exception {
        return (List<App>) super.hibernateTemplate.find("from App");
    }
    public List<App> findByCode(String code) throws Exception {
        List<App> apps = (List<App>) super.hibernateTemplate.find("from App where code=?", code);
        return apps;
    }
    public List<App> getAllByIdList(List<String> idList) {
        Session session = getCurrentSession();
        Criteria criteria = session.createCriteria(App.class);
        criteria.add(Restrictions.in("id", idList));
        return criteria.list();
    }
    public List<App> getListByCondition(String appIds, String catalog, String manageType) {
        List<App> apps = null;
        String hql = "FROM App WHERE 1=1";
        if(!StringUtils.isEmpty(catalog)){
            hql+=" and catalog = '"+catalog+"'";
        }
        if(!StringUtils.isEmpty(manageType)){
            hql+=" and manageType = '"+manageType+"'";
        }
        if(!StringUtils.isEmpty(appIds)){
            hql+=" and id in (:ids)";
            List<String> ids = Arrays.asList(appIds.split(","));
            Query query = getCurrentSession().createQuery(hql);
            query.setParameterList("ids",ids);
            apps = query.list();
            return apps;
        }
        Query query = getCurrentSession().createQuery(hql);
        apps = query.list();
        return apps;
    }
}

+ 62 - 0
src/main/java/com/yihu/hos/app/dao/AppFeatureDao.java

@ -0,0 +1,62 @@
package com.yihu.hos.app.dao;
import com.yihu.hos.app.model.AppFeature;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.model.DataGridResult;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Map;
/**
 * Created by chenweida on 2016/1/21.
 */
@Repository("appFeatureDao")
public class AppFeatureDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "appFeatureDao";
    public DataGridResult getAppFeatureList(Map<String, Object> params, Integer page, Integer rows) throws Exception {
        StringBuilder sb = new StringBuilder("from AppFeature t where 1=1 ");
        if (!StringUtils.isEmpty(params.get("id"))) {
            sb.append(" and t.id = '" + params.get("id") + "'");
        }
        Object name = params.get("name");
        if (!StringUtils.isEmpty(name)) {
            sb.append(" and (t.name like '%" + name + "%' or t.code like '%" + name + "%')");
        }
        if (!StringUtils.isEmpty(params.get("code"))) {
            sb.append(" and t.code = '" + params.get("code") + "'");
        }
        if (!StringUtils.isEmpty(params.get("type"))) {
            sb.append(" and t.type = '" + params.get("type") + "'");
        }
        if (!StringUtils.isEmpty(params.get("parentId"))) {
            sb.append(" and t.parentId = " + params.get("parentId") );
        }
        if (!StringUtils.isEmpty(params.get("appId"))) {
            sb.append(" and t.appId = '" + params.get("appId") + "'");
        }
        return super.getDataGridResult(sb.toString(), page, rows);
    }
    public List<AppFeature> getAllApplist() throws Exception {
        return (List<AppFeature>) super.hibernateTemplate.find("from AppFeature");
    }
    public List<AppFeature> findByCode(String code) throws Exception {
        List<AppFeature> appFeature = (List<AppFeature>) super.hibernateTemplate.find("from AppFeature where code=?", code);
        return appFeature;
    }
    public List<AppFeature> getAllByIdList(List<String> idList) {
        Session session = getCurrentSession();
        Criteria criteria = session.createCriteria(AppFeature.class);
        criteria.add(Restrictions.in("id", idList));
        return criteria.list();
    }
}

+ 53 - 0
src/main/java/com/yihu/hos/app/dao/AppServiceDao.java

@ -0,0 +1,53 @@
package com.yihu.hos.app.dao;
import com.yihu.hos.app.model.SystemServiceEndpoint;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.model.Result;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Map;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/8/16.
 */
@Repository("appServiceDao")
public class AppServiceDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "appServiceDao";
   
    public Result getAppServiceList(Map<String, Object> params) throws Exception {
        StringBuilder sb = new StringBuilder("from SystemServiceEndpoint t where 1=1 ");
        if (!StringUtils.isEmpty(params.get("valid"))) //是否有效
        {
            sb.append(" and t.valid = '" + params.get("valid") + "'");
        }
        Object name = params.get("name");
        Object appId = params.get("appId");
        if (!StringUtils.isEmpty(appId)) {
            sb.append(" and t.appId='"+ appId+ "'");
        }
        if (!StringUtils.isEmpty(name)) {
            sb.append(" and (t.name like '%" + name + "%' or t.code like '%" + name + "%')");
        }
        sb.append(" order by t.createDate desc");
        return super.getDataGridResult(sb.toString(), Integer.valueOf(params.get("page").toString()), Integer.valueOf(params.get("rows").toString()));
    }
    public List<SystemServiceEndpoint> getListByName(String serviceName) throws Exception {
        String hql = "from SystemServiceEndpoint";
        if (!StringUtil.isEmpty(serviceName)) {
            hql += " where name = "+serviceName+"";
        }
        return getEntityList(SystemServiceEndpoint.class, hql);
    }
    public List<SystemServiceEndpoint> findByCode(String code) throws Exception {
        List<SystemServiceEndpoint> services = (List<SystemServiceEndpoint>) super.hibernateTemplate.find("from SystemServiceEndpoint where code=?", code);
        return services;
    }
}

+ 238 - 0
src/main/java/com/yihu/hos/app/ehr/model/AppDetailModel.java

@ -0,0 +1,238 @@
package com.yihu.hos.app.ehr.model;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * Created by yww on 2016/2/23.
 */
public class AppDetailModel {
    private String id;
    private String name;
    private String secret;
    private String url;
    private String creator;
    private String auditor;
    private String createTime;
    private String auditTime;
    private String catalog;
    private String catalogName;
    private String status;
    private String statusName;
    private String description;
    private String tags;
    private String org;
    private String orgName;
    private String code;
    private int sourceType;
    private String sourceTypeName;
    private String role;
    private String roleJson;
//    应用图标及在线状态
    private String icon;
    private int releaseFlag;
//    应用图标及在线状态setter、getter
    public String getIcon() {
        return icon;
    }
    public void setIcon(String icon) {
        this.icon = icon;
    }
    public int getReleaseFlag() {
        return releaseFlag;
    }
    public void setReleaseFlag(int releaseFlag) {
        this.releaseFlag = releaseFlag;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public String getRoleJson() {
        return roleJson;
    }
    public void setRoleJson(String roleJson) {
        this.roleJson = roleJson;
    }
    public String getSourceTypeName() {
        return sourceTypeName;
    }
    public void setSourceTypeName(String sourceTypeName) {
        this.sourceTypeName = sourceTypeName;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public int getSourceType() {
        return sourceType;
    }
    public void setSourceType(int sourceType) {
        this.sourceType = sourceType;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSecret() {
        return secret;
    }
    public void setSecret(String secret) {
        this.secret = secret;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    public String getAuditor() {
        return auditor;
    }
    public void setAuditor(String auditor) {
        this.auditor = auditor;
    }
    public String getCreateTime() {
        return createTime;
    }
    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
    public String getAuditTime() {
        return auditTime;
    }
    public void setAuditTime(String auditTime) {
        this.auditTime = auditTime;
    }
    public String getCatalog() {
        return catalog;
    }
    public void setCatalog(String catalog) {
        this.catalog = catalog;
    }
    public String getCatalogName() {
        return catalogName;
    }
    public void setCatalogName(String catalogName) {
        this.catalogName = catalogName;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getStatusName() {
        return statusName;
    }
    public void setStatusName(String statusName) {
        this.statusName = statusName;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public List<String> getTags() {
        List<String> list = new ArrayList<>();
        if(StringUtils.isEmpty(tags)){
        }else {
            String[] arr = tags.split(";|;");
            list = Arrays.asList(arr);
        }
        return list;
    }
    public void setTags(List<String> tags) {
        if(tags.size()>0){
            this.tags = StringUtils.join(tags.toArray(),";");
        }else {
            this.tags = "";
        }
    }
    public String getOrg() {
        return org;
    }
    public void setOrg(String org) {
        this.org = org;
    }
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
}

+ 230 - 0
src/main/java/com/yihu/hos/app/model/App.java

@ -0,0 +1,230 @@
package com.yihu.hos.app.model;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
 * APP对象。
 *
 * @author Sand
 * @version 1.0
 * @created 03_8月_2015 16:53:21
 */
@Entity
@Table(name = "apps")
@Access(value = AccessType.FIELD)
public class App {
    @Id
    @GeneratedValue(generator = "Generator")
    @GenericGenerator(name = "Generator", strategy = "assigned")
    @Column(name = "id", unique = true, nullable = false)
    private String id;
    @Column(name = "name", nullable = true)
    private String name;
    @Column(name = "secret", nullable = true)
    private String secret;
    @Column(name = "url", nullable = true)
    private String url;
    @Column(name = "out_url", nullable = true)
    private String outUrl;
    @Column(name = "creator", nullable = true)
    private String creator;
    @Column(name = "auditor", nullable = true)
    private String auditor;
    @Column(name = "create_time", nullable = true)
    private Date createTime;
    @Column(name = "audit_time", nullable = true)
    private Date auditTime;
    @Column(name = "catalog", nullable = true)
    private String catalog;
    @Column(name = "status", nullable = true)
    private String status;
    @Column(name = "description", nullable = true)
    private String description;
    @Column(name = "tags", nullable = true)
    private String tags;
    @Column(name = "org", nullable = true)
    private String org;
    @Column(name = "code", nullable = true)
    private String code;
    @Column(name = "source_type", nullable = true)
    private int sourceType;
    @Column(name = "icon", nullable = true)
    private String icon;
    @Column(name = "release_flag", nullable = true)
    private int releaseFlag;
    @Column(name = "manage_type")
    private String manageType; // 管理类型,dictName=""
    public App() {
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSecret() {
        return secret;
    }
    public void setSecret(String secret) {
        this.secret = secret;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getOutUrl() {
        return outUrl;
    }
    public void setOutUrl(String outUrl) {
        this.outUrl = outUrl;
    }
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    public String getAuditor() {
        return auditor;
    }
    public void setAuditor(String auditor) {
        this.auditor = auditor;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getAuditTime() {
        return auditTime;
    }
    public void setAuditTime(Date auditTime) {
        this.auditTime = auditTime;
    }
    public String getCatalog() {
        return catalog;
    }
    public void setCatalog(String catalog) {
        this.catalog = catalog;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public List<String> getTags() {
        List<String> list = new ArrayList<>();
        if (StringUtils.isEmpty(tags)) {
        } else {
            String[] arr = tags.split(";|;");
            list = Arrays.asList(arr);
        }
        return list;
    }
    public void setTags(List<String> tags) {
        if (tags.size() > 0) {
            this.tags = StringUtils.join(tags.toArray(), ";");
        } else {
            this.tags = "";
        }
    }
    public String getOrg() {
        return org;
    }
    public void setOrg(String org) {
        this.org = org;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public int getSourceType() {
        return sourceType;
    }
    public void setSourceType(int sourceType) {
        this.sourceType = sourceType;
    }
    public String getIcon() {
        return icon;
    }
    public void setIcon(String icon) {
        this.icon = icon;
    }
    public int getReleaseFlag() {
        return releaseFlag;
    }
    public void setReleaseFlag(int releaseFlag) {
        this.releaseFlag = releaseFlag;
    }
    public String getManageType() {
        return manageType;
    }
    public void setManageType(String manageType) {
        this.manageType = manageType;
    }
}

+ 243 - 0
src/main/java/com/yihu/hos/app/model/AppApi.java

@ -0,0 +1,243 @@
package com.yihu.hos.app.model;
import javax.persistence.*;
/**
 * APP_api对象。
 *
 * @author linzhuo
 * @version 1.0
 * @created 2016年7月7日17:45:30
 */
@Entity
@Table(name = "apps_api")
public class AppApi {
    private Integer id;
    private String appId;
    private String name;
    private String description;
    private String type;
    private String typeName;
    private String method;
    private String protocol;
    private String version;
    private Integer parentId;
    private String parameterDemo;
    private String activityType;
    private String responseDemo;
    private String openLevel;
    private String openLevelName;
    private String auditLevel;
    private String auditLevelName;
    private String methodName;
    private String microServiceUri;
    private String msMethodName;
    private String microServiceName;
    private Integer healthReportType;//健康监控(0为拉取,1推送)
    private String healthEndpoint;//健康监控端点地址
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Column(name = "app_id", nullable = true)
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    @Column(name = "name", nullable = true)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "description", nullable = true)
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    @Column(name = "type", nullable = true)
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    @Column(name = "method", nullable = true)
    public String getMethod() {
        return method;
    }
    public void setMethod(String method) {
        this.method = method;
    }
    @Column(name = "protocol", nullable = true)
    public String getProtocol() {
        return protocol;
    }
    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }
    @Column(name = "version", nullable = true)
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
    @Column(name = "parent_id", nullable = true)
    public Integer getParentId() {
        return parentId;
    }
    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }
    @Column(name = "parameter_demo", nullable = true)
    public String getParameterDemo() {
        return parameterDemo;
    }
    public void setParameterDemo(String parameterDemo) {
        this.parameterDemo = parameterDemo;
    }
    @Column(name = "activity_type", nullable = true)
    public String getActivityType() {
        return activityType;
    }
    public void setActivityType(String activityType) {
        this.activityType = activityType;
    }
    @Column(name = "response_demo", nullable = true)
    public String getResponseDemo() {
        return responseDemo;
    }
    public void setResponseDemo(String responseDemo) {
        this.responseDemo = responseDemo;
    }
    @Column(name = "open_level", nullable = true)
    public String getOpenLevel() {
        return openLevel;
    }
    public void setOpenLevel(String openLevel) {
        this.openLevel = openLevel;
    }
    @Column(name = "audit_level", nullable = true)
    public String getAuditLevel() {
        return auditLevel;
    }
    public void setAuditLevel(String auditLevel) {
        this.auditLevel = auditLevel;
    }
    @Column(name = "method_name", nullable = true)
    public String getMethodName() {
        return methodName;
    }
    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }
    @Column(name = "micro_service_url", nullable = true)
    public String getMicroServiceUri() {
        return microServiceUri;
    }
    public void setMicroServiceUri(String microServiceUri) {
        this.microServiceUri = microServiceUri;
    }
    @Column(name = "ms_method_name", nullable = true)
    public String getMsMethodName() {
        return msMethodName;
    }
    public void setMsMethodName(String msMethodName) {
        this.msMethodName = msMethodName;
    }
    @Column(name = "micro_service_name", nullable = true)
    public String getMicroServiceName() {
        return microServiceName;
    }
    public void setMicroServiceName(String microServiceName) {
        this.microServiceName = microServiceName;
    }
    @Transient
    public String getOpenLevelName() {
        return openLevelName;
    }
    public void setOpenLevelName(String openLevelName) {
        this.openLevelName = openLevelName;
    }
    @Transient
    public String getTypeName() {
        return typeName;
    }
    public void setTypeName(String typeName) {
        this.typeName = typeName;
    }
    @Transient
    public String getAuditLevelName() {
        return auditLevelName;
    }
    public void setAuditLevelName(String auditLevelName) {
        this.auditLevelName = auditLevelName;
    }
    @Column(name = "health_report_type", nullable = true)
    public Integer getHealthReportType() {
        return healthReportType;
    }
    public void setHealthReportType(Integer healthReportType) {
        this.healthReportType = healthReportType;
    }
    @Column(name = "health_endpoint", nullable = true)
    public String getHealthEndpoint() {
        return healthEndpoint;
    }
    public void setHealthEndpoint(String healthEndpoint) {
        this.healthEndpoint = healthEndpoint;
    }
}

+ 150 - 0
src/main/java/com/yihu/hos/app/model/AppApiParameter.java

@ -0,0 +1,150 @@
package com.yihu.hos.app.model;
import javax.persistence.*;
/**
 * apps_api_parameter对象。
 *
 * @author linzhuo
 * @version 1.0
 * @created 2016年7月7日17:45:30
 */
@Entity
@Table(name = "apps_api_parameter")
public class AppApiParameter {
    private Integer id;
    private String name;
    private String type;
    private String typeName;
    private String dataType;
    private String dataTypeName;
    private String description;
    private String required;
    private String requiredName;
    private Integer appApiId;
    private String memo;
    private String defaultValue;
    private String __status;//非数据库字段,用于区分是做保存更新删除等操作
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Column(name = "name", nullable = true)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "description", nullable = true)
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    @Column(name = "type", nullable = true)
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    @Column(name = "data_type", nullable = true)
    public String getDataType() {
        return dataType;
    }
    public void setDataType(String dataType) {
        this.dataType = dataType;
    }
    @Column(name = "required", nullable = true)
    public String getRequired() {
        return required;
    }
    public void setRequired(String required) {
        this.required = required;
    }
    @Column(name = "app_api_id", nullable = true)
    public Integer getAppApiId() {
        return appApiId;
    }
    public void setAppApiId(Integer appApiId) {
        this.appApiId = appApiId;
    }
    @Column(name = "memo", nullable = true)
    public String getMemo() {
        return memo;
    }
    public void setMemo(String memo) {
        this.memo = memo;
    }
    @Column(name = "default_value", nullable = true)
    public String getDefaultValue() {
        return defaultValue;
    }
    public void setDefaultValue(String defaultValue) {
        this.defaultValue = defaultValue;
    }
    @Transient
    public String getTypeName() {
        return typeName;
    }
    public void setTypeName(String typeName) {
        this.typeName = typeName;
    }
    @Transient
    public String getDataTypeName() {
        return dataTypeName;
    }
    public void setDataTypeName(String dataTypeName) {
        this.dataTypeName = dataTypeName;
    }
    @Transient
    public String getRequiredName() {
        return requiredName;
    }
    public void setRequiredName(String requiredName) {
        this.requiredName = requiredName;
    }
    @Transient
    public String get__status() {
        return __status;
    }
    public void set__status(String __status) {
        this.__status = __status;
    }
}

+ 89 - 0
src/main/java/com/yihu/hos/app/model/AppApiResponse.java

@ -0,0 +1,89 @@
package com.yihu.hos.app.model;
import javax.persistence.*;
/**
 * apps_api_response对象。
 *
 * @author linzhuo
 * @version 1.0
 * @created 2016年7月7日17:45:30
 */
@Entity
@Table(name = "apps_api_response")
public class AppApiResponse {
    private Integer id;
    private String name;
    private String dataType;
    private String description;
    private Integer appApiId;
    private String memo;
    private String __status;//非数据库字段,用于区分是做保存更新删除等操作
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Column(name = "name", nullable = true)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "description", nullable = true)
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    @Column(name = "data_type", nullable = true)
    public String getDataType() {
        return dataType;
    }
    public void setDataType(String dataType) {
        this.dataType = dataType;
    }
    @Column(name = "app_api_id", nullable = true)
    public Integer getAppApiId() {
        return appApiId;
    }
    public void setAppApiId(Integer appApiId) {
        this.appApiId = appApiId;
    }
    @Column(name = "memo", nullable = true)
    public String getMemo() {
        return memo;
    }
    public void setMemo(String memo) {
        this.memo = memo;
    }
    @Transient
    public String get__status() {
        return __status;
    }
    public void set__status(String __status) {
        this.__status = __status;
    }
}

+ 179 - 0
src/main/java/com/yihu/hos/app/model/AppFeature.java

@ -0,0 +1,179 @@
package com.yihu.hos.app.model;
import javax.persistence.*;
/**
 * apps_api_feature对象。
 *
 * @author linzhuo
 * @version 1.0
 * @created 2016年7月7日17:45:30
 */
@Entity
@Table(name = "apps_feature")
public class AppFeature {
    private Integer id;
    private String code; // 菜单编码
    private String name; // 菜单名称
    private String description; // 菜单描述
    private String type; // 类型,1:模块,2:菜单,3:功能按钮。
    private Integer parentId;// 父菜单
    private String prefixUrl; // 菜单相对访问路径前缀,即JavaWeb上下文路径或站点+上下文路径。
    private String url; // 菜单访问路径。模块时没有值,菜单时有值,按钮时不一定有值。
    private String iconUrl; // 图标访问路径
    private String auditLevel; // 审计类型,0:不审计,1:审计。
    private String openLevel; // 开放级别,0:私有(不作为授权对象),1:公开(收费/免费)
    private String appId; // 应用ID
    private String roleId;
    private Integer sort; // 菜单排序
    private Integer level; // 菜单级别
    private String content; // 页面菜单拼接对象
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Column(name = "name", nullable = true)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "description", nullable = true)
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    @Column(name = "code", nullable = true)
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "type", nullable = true)
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    @Column(name = "parent_id", nullable = true)
    public Integer getParentId() {
        return parentId;
    }
    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }
    @Column(name = "url", nullable = true)
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    @Column(name = "prefix_url", nullable = true)
    public String getPrefixUrl() {
        return prefixUrl;
    }
    public void setPrefixUrl(String prefixUrl) {
        this.prefixUrl = prefixUrl;
    }
    @Column(name = "icon_url", nullable = true)
    public String getIconUrl() {
        return iconUrl;
    }
    public void setIconUrl(String iconUrl) {
        this.iconUrl = iconUrl;
    }
    @Column(name = "audit_level", nullable = true)
    public String getAuditLevel() {
        return auditLevel;
    }
    public void setAuditLevel(String auditLevel) {
        this.auditLevel = auditLevel;
    }
    @Column(name = "open_level", nullable = true)
    public String getOpenLevel() {
        return openLevel;
    }
    public void setOpenLevel(String openLevel) {
        this.openLevel = openLevel;
    }
    @Column(name = "app_id", nullable = true)
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    @Transient
    public String getRoleId() {
        return roleId;
    }
    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }
    @Column(name = "sort", nullable = true)
    public Integer getSort() {
        return sort;
    }
    public void setSort(Integer sort) {
        this.sort = sort;
    }
    @Column(name = "level", nullable = true)
    public Integer getLevel() {
        return level;
    }
    public void setLevel(Integer level) {
        this.level = level;
    }
    @Column(name = "content", nullable = true)
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}

+ 105 - 0
src/main/java/com/yihu/hos/app/model/AppFeatureTree.java

@ -0,0 +1,105 @@
package com.yihu.hos.app.model;
import java.util.ArrayList;
import java.util.List;
/**
 * @author lincl
 * @version 1.0
 * @created 2016/7/11
 */
public class AppFeatureTree {
    int id;
    String name;
    String appId;
    int parentId;
    String type;
    String iconUrl;
    String memo;
    List children = new ArrayList<>();
    public AppFeatureTree(int id, String name, int parentId, String type, String iconUrl) {
        this.id = id;
        this.name = name;
        this.parentId = parentId;
        this.type = type;
        this.iconUrl = iconUrl;
    }
    public AppFeatureTree(int id, String name, String memo, int parentId, String type, String appId) {
        this.id = id;
        this.name = name;
        this.memo = memo;
        this.parentId = parentId;
        this.type = type;
        this.appId = appId;
    }
    public void addChild(AppFeatureTree child){
        children.add(child);
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getParentId() {
        return parentId;
    }
    public void setParentId(int parentId) {
        this.parentId = parentId;
    }
    public List getChildren() {
        return children;
    }
    public void setChildren(List children) {
        this.children = children;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getIconUrl() {
        return iconUrl;
    }
    public void setIconUrl(String iconUrl) {
        this.iconUrl = iconUrl;
    }
    public String getMemo() {
        return memo;
    }
    public void setMemo(String memo) {
        this.memo = memo;
    }
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
}

+ 201 - 0
src/main/java/com/yihu/hos/app/model/SystemServiceEndpoint.java

@ -0,0 +1,201 @@
package com.yihu.hos.app.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/8/16.
 */
public class SystemServiceEndpoint implements java.io.Serializable {
    private String id;
    private String code;
    private String name;
    private String appId;
    private String version;
    private String description;
    private String endpoint;
    private String requestProtocol;
    private String requestParameterList;
    private String requesModule;
    private String requestMethod;
    private String responeResult;
    private String responeError;
    private Integer healthReportType;
    private String healthEndpoint;
    private Integer metricsReportType;
    private String metricsEndpoint;
    private Integer valid;
    private String requestFormat;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date createDate;
    public SystemServiceEndpoint() {
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getEndpoint() {
        return endpoint;
    }
    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }
    public String getRequestProtocol() {
        return requestProtocol;
    }
    public void setRequestProtocol(String requestProtocol) {
        this.requestProtocol = requestProtocol;
    }
    public String getRequestParameterList() {
        return requestParameterList;
    }
    public void setRequestParameterList(String requestParameterList) {
        this.requestParameterList = requestParameterList;
    }
    public String getRequesModule() {
        return requesModule;
    }
    public void setRequesModule(String requesModule) {
        this.requesModule = requesModule;
    }
    public String getRequestMethod() {
        return requestMethod;
    }
    public void setRequestMethod(String requestMethod) {
        this.requestMethod = requestMethod;
    }
    public String getResponeResult() {
        return responeResult;
    }
    public void setResponeResult(String responeResult) {
        this.responeResult = responeResult;
    }
    public String getResponeError() {
        return responeError;
    }
    public void setResponeError(String responeError) {
        this.responeError = responeError;
    }
    public Integer getHealthReportType() {
        return healthReportType;
    }
    public void setHealthReportType(Integer healthReportType) {
        this.healthReportType = healthReportType;
    }
    public String getHealthEndpoint() {
        return healthEndpoint;
    }
    public void setHealthEndpoint(String healthEndpoint) {
        this.healthEndpoint = healthEndpoint;
    }
    public Integer getMetricsReportType() {
        return metricsReportType;
    }
    public void setMetricsReportType(Integer metricsReportType) {
        this.metricsReportType = metricsReportType;
    }
    public String getMetricsEndpoint() {
        return metricsEndpoint;
    }
    public void setMetricsEndpoint(String metricsEndpoint) {
        this.metricsEndpoint = metricsEndpoint;
    }
    public Integer getValid() {
        return valid;
    }
    public void setValid(Integer valid) {
        this.valid = valid;
    }
    public String getRequestFormat() {
        return requestFormat;
    }
    public void setRequestFormat(String requestFormat) {
        this.requestFormat = requestFormat;
    }
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
}

+ 46 - 0
src/main/java/com/yihu/hos/app/service/AppApiParameterService.java

@ -0,0 +1,46 @@
package com.yihu.hos.app.service;
import com.yihu.hos.app.dao.AppApiParameterDao;
import com.yihu.hos.app.model.AppApiParameter;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.baseservice.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * Created by chenweida on 2016/1/21.
 */
@Service
public class AppApiParameterService extends BaseService<AppApiParameter>{
    static final Logger logger = LoggerFactory.getLogger(AppApiParameterService.class);
    @Autowired
    private AppApiParameterDao appApiParameterDao;
    @Transactional
    public AppApiParameter create(AppApiParameter obj) throws Exception {
        appApiParameterDao.saveEntity(obj);
        return obj;
    }
    public AppApiParameter getById(Integer id) throws Exception {
        return appApiParameterDao.getEntity(AppApiParameter.class, id);
    }
    @Transactional
    public void delete(Integer id) throws Exception {
        AppApiParameter obj = appApiParameterDao.getEntity(AppApiParameter.class, id);
        appApiParameterDao.deleteEntity(obj);
    }
    @Transactional
    public AppApiParameter update(AppApiParameter obj) throws Exception {
        appApiParameterDao.updateEntity(obj);
        return obj;
    }
}

+ 46 - 0
src/main/java/com/yihu/hos/app/service/AppApiResponseService.java

@ -0,0 +1,46 @@
package com.yihu.hos.app.service;
import com.yihu.hos.app.dao.AppApiResponseDao;
import com.yihu.hos.app.model.AppApiResponse;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.baseservice.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * Created by chenweida on 2016/1/21.
 */
@Service
public class AppApiResponseService extends BaseService<AppApiResponse>{
    static final Logger logger = LoggerFactory.getLogger(AppApiResponseService.class);
    @Autowired
    private AppApiResponseDao appApiResponseDao;
    @Transactional
    public AppApiResponse create(AppApiResponse obj) throws Exception {
        appApiResponseDao.saveEntity(obj);
        return obj;
    }
    public AppApiResponse getById(Integer id) throws Exception {
        return appApiResponseDao.getEntity(AppApiResponse.class, id);
    }
    @Transactional
    public void delete(Integer id) throws Exception {
        AppApiResponse obj = appApiResponseDao.getEntity(AppApiResponse.class, id);
        appApiResponseDao.deleteEntity(obj);
    }
    @Transactional
    public AppApiResponse update(AppApiResponse obj) throws Exception {
        appApiResponseDao.updateEntity(obj);
        return obj;
    }
}

+ 127 - 0
src/main/java/com/yihu/hos/app/service/AppApiService.java

@ -0,0 +1,127 @@
package com.yihu.hos.app.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.app.dao.AppApiDao;
import com.yihu.hos.app.model.AppApi;
import com.yihu.hos.app.model.AppApiParameter;
import com.yihu.hos.app.model.AppApiResponse;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.baseservice.BaseService;
import com.yihu.hos.web.framework.util.DateTimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
/**
 * Created by chenweida on 2016/1/21.
 */
@Service("appApiService")
public class AppApiService extends BaseService<AppApi>{
    public static final String BEAN_ID = "appApiService";
    private static final String DELETE = "delete";
    private static final String ADD = "add";
    private static final String UPDATE = "update";
    private static final String NEW_DATA = "0";
    private static final String DATA_STATUS = "__status";
    @Autowired
    public ObjectMapper objectMapper;
    static final Logger logger = LoggerFactory.getLogger(AppApiService.class);
    @Autowired
    private AppApiParameterService appApiParameterService;
    @Autowired
    private AppApiResponseService appApiResponseService;
    @Resource(name = AppApiDao.BEAN_ID)
    private AppApiDao appApiDao;
    public AppApi getById(Integer id) throws Exception {
        return appApiDao.getEntity(AppApi.class, id);
    }
    @Transactional
    public void delete(Integer id) throws Exception {
        AppApi appApi = appApiDao.getEntity(AppApi.class, id);
        appApiDao.deleteEntity(appApi);
    }
    @Transactional
    public AppApi saveOrUpdate(AppApi obj) throws Exception {
        if ("".equals(obj.getMethodName())){
            obj.setMethodName(null);
        }
        appApiDao.saveOrUpdateEntity(obj);
        return obj;
    }
    /**
     * 保存apiParms及apiResponse
     *
     * @param apiId
     * @param apiParms
     * @param apiResponse
     */
    private void saveApiParmsResponse(Integer apiId, String apiParms, String apiResponse) {
        try {
            List<Map<String, Object>> list;
            if (!StringUtils.isEmpty(apiParms)) {
                list = objectMapper.readValue(apiParms, List.class);
                for (Map<String, Object> parmsMap : list) {
                    //删除的是新增的数据直接跳过
                    if (DELETE.equals(parmsMap.get(DATA_STATUS)) && NEW_DATA.equals(parmsMap.get("id") + "")) {
                        continue;
                    } else {
                        parmsMap.put("appApiId", apiId);
                        String json = objectMapper.writeValueAsString(parmsMap);
                        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.ISO8601Pattern));
                        AppApiParameter obj = objectMapper.readValue(json,  AppApiParameter.class);
                        if (NEW_DATA.equals(parmsMap.get("id") + "")) {
                            appApiParameterService.create(obj);
                        } else if (UPDATE.equals(parmsMap.get(DATA_STATUS))) {
                            appApiParameterService.update(obj);
                        } else if (DELETE.equals(parmsMap.get(DATA_STATUS))) {
                            appApiParameterService.delete(obj.getId());
                        }
                    }
                }
            }
            if (!StringUtils.isEmpty(apiResponse)) {
                list = objectMapper.readValue(apiResponse, List.class);
                for (Map<String, Object> parmsMap : list) {
                    //删除的是新增的数据直接跳过
                    if (DELETE.equals(parmsMap.get(DATA_STATUS)) && NEW_DATA.equals(parmsMap.get("id") + "")) {
                        continue;
                    } else {
                        parmsMap.put("appApiId", apiId);
                        String json = objectMapper.writeValueAsString(parmsMap);
                        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.ISO8601Pattern));
                        AppApiResponse obj = objectMapper.readValue(json,  AppApiResponse.class);
                        if (ADD.equals(parmsMap.get(DATA_STATUS))) {
                            appApiResponseService.create(obj);
                        } else if (UPDATE.equals(parmsMap.get(DATA_STATUS))) {
                            appApiResponseService.update(obj);
                        } else if (DELETE.equals(parmsMap.get(DATA_STATUS))) {
                            appApiResponseService.delete(obj.getId());
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}

+ 82 - 0
src/main/java/com/yihu/hos/app/service/AppFeatureService.java

@ -0,0 +1,82 @@
package com.yihu.hos.app.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.app.dao.AppFeatureDao;
import com.yihu.hos.app.model.AppFeature;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.baseservice.BaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
/**
 * Created by chenweida on 2016/1/21.
 */
@Service("appFeatureService")
public class AppFeatureService extends BaseService<AppFeature> {
    public static final String BEAN_ID = "appFeatureService";
    static final Logger logger = LoggerFactory.getLogger(AppFeatureService.class);
    @Resource(name = AppFeatureDao.BEAN_ID)
    private AppFeatureDao appFeatureDao;
    @Transactional
    public AppFeature addFeature(AppFeature obj) throws Exception {
        Integer sort = obj.getSort();
        if(sort==null||sort==0){
            obj.setSort(1);
        }
        obj.setId(null);
        appFeatureDao.saveEntity(obj);
        return obj;
    }
    public List<AppFeature> getFeatureByCode(String code) throws Exception {
        return appFeatureDao.findByCode(code);
    }
    public AppFeature getById(Integer id) throws Exception {
        return appFeatureDao.getEntity(AppFeature.class, id);
    }
    @Transactional
    public void delete(Integer id) throws Exception {
        AppFeature feature = appFeatureDao.getEntity(AppFeature.class, id);
        appFeatureDao.deleteEntity(feature);
    }
    @Transactional
    public AppFeature update(AppFeature obj) throws Exception {
        appFeatureDao.updateEntity(obj);
        return obj;
    }
    /**
     * 生成菜单JSON对象字符串
     * @return AppFeature
     */
    public AppFeature joinMenuItemJsonStr(AppFeature appFeature) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put("id", appFeature.getId());
        contentMap.put("level", appFeature.getLevel());
        contentMap.put("text", appFeature.getName());
        if (!"1".equals(appFeature.getLevel())) {
            contentMap.put("pid", appFeature.getParentId());
        }
        if (appFeature.getUrl().startsWith("/")) {
            contentMap.put("url", "${contextRoot}" + appFeature.getUrl());
        }
        appFeature.setContent(objectMapper.writeValueAsString(contentMap));
        return appFeature;
    }
}

+ 84 - 0
src/main/java/com/yihu/hos/app/service/AppManager.java

@ -0,0 +1,84 @@
package com.yihu.hos.app.service;
import com.yihu.hos.app.dao.AppDao;
import com.yihu.hos.app.model.App;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.baseservice.BaseService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Random;
/**
 * Created by chenweida on 2016/1/21.
 */
@Service("appManager")
public class AppManager extends BaseService<App> {
    public static final String BEAN_ID = "appManager";
    static final Logger logger = LoggerFactory.getLogger(AppManager.class);
    @Resource(name = AppDao.BEAN_ID)
    private AppDao appDao;
    @Value("${spring.data.mongodb.gridFsDatabase}")
    private String dbName;
    private static String getRandomString(int length) {
        String str = "abcdefghigklmnopkrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(str.length() - 1);//0~61
            buffer.append(str.charAt(number));
        }
        return buffer.toString();
    }
    public App getAppById(String id) throws Exception {
        return appDao.getEntity(App.class, id);
    }
    public List<App> getAppByCode(String code) throws Exception {
        return appDao.findByCode(code);
    }
    @Transactional
    public App addApp(App obj) throws Exception {
        obj.setId(getRandomString(10));
        obj.setSecret(getRandomString(16));
        obj.setCreateTime(new Date());
        obj.setStatus("WaitingForApprove");
        List<App> appByCode = getAppByCode(obj.getCode());
        if (appByCode != null && appByCode.size() > 0) {
            throw new Exception("保存失败,应用Code已存在");
        }
        appDao.saveEntity(obj);
        return obj;
    }
    @Transactional
    public App updateApp(App obj) throws Exception {
        appDao.updateEntity(obj);
        return obj;
    }
    @Transactional
    public void deleteApp(String id) throws Exception {
        App systemApp = appDao.getEntity(App.class, id);
        appDao.deleteEntity(systemApp);
    }
    public List<App> getListByCondition(String appIds, String catalog, String manageType) {
        return appDao.getListByCondition(appIds, catalog, manageType);
    }
}

+ 99 - 0
src/main/java/com/yihu/hos/app/service/AppServiceManage.java

@ -0,0 +1,99 @@
package com.yihu.hos.app.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.app.dao.AppServiceDao;
import com.yihu.hos.app.model.SystemServiceEndpoint;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.baseservice.BaseService;
import com.yihu.hos.web.framework.constant.ContextAttributes;
import com.yihu.hos.web.framework.constant.EndPointConstant;
import com.yihu.hos.web.framework.thread.LocalContext;
import io.zbus.mq.Broker;
import io.zbus.mq.Message;
import io.zbus.mq.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
 * Created by chenweida on 2016/1/21.
 */
@Service("appService")
public class AppServiceManage extends BaseService<SystemServiceEndpoint> {
    public static final String BEAN_ID = "appService";
    static final Logger logger = LoggerFactory.getLogger(AppServiceManage.class);
    @Resource(name = AppServiceDao.BEAN_ID)
    private AppServiceDao appServiceDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private Broker broker;
    public SystemServiceEndpoint getById(String id) throws Exception {
        return appServiceDao.getEntity(SystemServiceEndpoint.class, id);
    }
    public SystemServiceEndpoint create(SystemServiceEndpoint service) throws Exception {
        service.setCreateDate(new Date());
        appServiceDao.saveEntity(service);
        this.sendMsg(EndPointConstant.ADD_ENDPOINT, service);
        return service;
    }
    public List<SystemServiceEndpoint> getByCode(String code) throws Exception {
        return appServiceDao.findByCode(code);
    }
    @Transactional
    public SystemServiceEndpoint update(SystemServiceEndpoint obj) throws Exception {
        appServiceDao.updateEntity(obj);
        this.sendMsg(EndPointConstant.ADD_ENDPOINT, obj);
        return obj;
    }
    @Transactional
    public void deleteById(String id) throws Exception {
        SystemServiceEndpoint service = appServiceDao.getEntity(SystemServiceEndpoint.class, id);
        appServiceDao.deleteEntity(service);
        this.sendMsg(EndPointConstant.DELETE_ENDPOINT, service);
    }
    private void sendMsg(String event, SystemServiceEndpoint endpoint) {
        if (broker == null) {
            logger.error("broker is null.");
            return;
        }
        try {
            String msg = objectMapper.writeValueAsString(endpoint);
            String tenant = LocalContext.getContext().getAttachment(ContextAttributes.TENANT_NAME);
            String topic = EndPointConstant.ZBUS_MQ + "@" + tenant;
            Producer producer = new Producer(broker);
            //确定为创建消息队列需要显示调用
            producer.declareTopic(topic);
            Message message = new Message();
            message.setTopic(topic);
            message.setHeader("event", event);
            message.setHeader("tenant", tenant);
            message.setMethod("POST");
            message.setBody(msg);
            producer.publish(message);
        } catch (IOException | InterruptedException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }
}

+ 38 - 0
src/main/java/com/yihu/hos/common/HosAdminLogger.java

@ -0,0 +1,38 @@
package com.yihu.hos.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.hos.core.datatype.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 数据交换平台日志记录器
 */
public class HosAdminLogger {
    private static Logger logger = LoggerFactory.getLogger(HosAdminLogger.class);
    /**
     * 业务日志输出
     *
     * @param caller 调用者
     * @param info 日志信息
     */
    public static void info(String caller, JsonNode info) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode log = objectMapper.createObjectNode();
            log.put("caller", caller);
            log.put("time", DateUtil.getCurrentString(DateUtil.DEFAULT_YMDHMSDATE_FORMAT));
            log.put("logType", "3");
            log.set("data", info);
            logger.info(log.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

+ 349 - 0
src/main/java/com/yihu/hos/common/JXLUtil.java

@ -0,0 +1,349 @@
package com.yihu.hos.common;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by chenweida on 2016/2/26.
 */
public class JXLUtil {
//    public static void main(String[] args) throws Exception {
//        OutputStream os = new FileOutputStream("D:/AAA.xlsx");
//        List data = new ArrayList<>();
//        Map<String, Object> param = new HashMap<String, Object>();
//        param.put("aaa", "aaa1");
//        data.add(param);
//        data.add(param);
//        data.add(param);
//        data.add(param);
//        HashMap<String, String> fieldMap = new LinkedHashMap<String, String>();
//        fieldMap.put("aaa", "aaa1");
//        fieldMap.put("aaa1", "aaa2");
//        fieldMap.put("aaa2", "aaa3");
//        JXLUtil.listMapToExcel(data, fieldMap, "aaaaaa", os);
//    }
    /**
     * 导出excel2003
     *
     * @param list      数据集合
     * @param fieldMap  类的英文属性和Excel中的中文列名的对应关系
     * @param sheetName 工作表的名称
     * @param out       导出流
     */
    public static <T> void listObjectToExcel(List<T> list, Map<String, String> fieldMap, String sheetName, OutputStream out) throws Exception {
        if (list.size() == 0 || list == null) {
            throw new Exception("数据源中没有任何数据");
        }
        int sheetSize = list.size();
        if (sheetSize > 65535 || sheetSize < 1) {
            sheetSize = 65535;
        }
        // 创建工作簿并发送到OutputStream指定的地方
        WritableWorkbook wwb;
        try {
            wwb = Workbook.createWorkbook(out);
            // 1.计算一共有多少个工作表
            int sheetNum = list.size() % sheetSize == 0 ? list.size() / sheetSize : (list.size() / sheetSize + 1);
            // 2.创建相应的工作表,并向其中填充数据
            for (int i = 0; i < sheetNum; i++) {
                // 如果只有一个工作表的情况
                if (1 == sheetNum) {
                    WritableSheet sheet = wwb.createSheet(sheetName, i);
                    fillObjectSheet(sheet, list, fieldMap, 0, list.size() - 1);
                    // 有多个工作表的情况
                } else {
                    WritableSheet sheet = wwb.createSheet(sheetName + (i + 1), i);
                    // 获取开始索引和结束索引
                    int firstIndex = i * sheetSize;
                    int lastIndex = (i + 1) * sheetSize - 1 > list.size() - 1 ? list
                            .size() - 1 : (i + 1) * sheetSize - 1;
                    // 填充工作表
                    fillObjectSheet(sheet, list, fieldMap, firstIndex, lastIndex);
                }
            }
            wwb.write();
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 导出excel2003
     *
     * @param list      数据集合
     * @param fieldMap  类的英文属性和Excel中的中文列名的对应关系
     * @param sheetName 工作表的名称
     * @param out       导出流
     */
    public static <T> void listMapToExcel(List<Map<String, Object>> list, Map<String, String> fieldMap, String sheetName, OutputStream out) throws Exception {
        if (list.size() == 0 || list == null) {
            throw new Exception("数据源中没有任何数据");
        }
        int sheetSize = list.size();
        if (sheetSize > 65535 || sheetSize < 1) {
            sheetSize = 65535;
        }
        // 创建工作簿并发送到OutputStream指定的地方
        WritableWorkbook wwb;
        try {
            wwb = Workbook.createWorkbook(out);
            // 1.计算一共有多少个工作表
            int sheetNum = list.size() % sheetSize == 0 ? list.size() / sheetSize : (list.size() / sheetSize + 1);
            // 2.创建相应的工作表,并向其中填充数据
            for (int i = 0; i < sheetNum; i++) {
                // 如果只有一个工作表的情况
                if (1 == sheetNum) {
                    WritableSheet sheet = wwb.createSheet(sheetName, i);
                    fillMapSheet(sheet, list, fieldMap, 0, list.size() - 1);
                    // 有多个工作表的情况
                } else {
                    WritableSheet sheet = wwb.createSheet(sheetName + (i + 1), i);
                    // 获取开始索引和结束索引
                    int firstIndex = i * sheetSize;
                    int lastIndex = (i + 1) * sheetSize - 1 > list.size() - 1 ? list
                            .size() - 1 : (i + 1) * sheetSize - 1;
                    // 填充工作表
                    fillMapSheet(sheet, list, fieldMap, firstIndex, lastIndex);
                }
            }
            wwb.write();
            wwb.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * <---------------------list转excel--------------------->
     * 导出到浏览器
     */
    public static <T> void listMapToExcel(List<Map<String, Object>> list, Map<String, String> fieldMap, String sheetName, HttpServletResponse response) {
        // 设置默认文件名为当前时间:年月日时分秒
        String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
        // 设置response头信息
        response.reset();
        response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
        // 创建工作簿并发送到浏览器
        try {
            OutputStream out = response.getOutputStream();
            listMapToExcel(list, fieldMap, sheetName, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * <---------------------list转excel--------------------->
     * 导出到浏览器
     */
    public static <T> void listObjectToExcel(List<T> list, Map<String, String> fieldMap, String sheetName, HttpServletResponse response) {
        // 设置默认文件名为当前时间:年月日时分秒
        String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
        // 设置response头信息
        response.reset();
        response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
        // 创建工作簿并发送到浏览器
        try {
            OutputStream out = response.getOutputStream();
            listObjectToExcel(list, fieldMap, sheetName, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //设置工作表自动列宽和首行加粗
    private static void setColumnAutoSize(WritableSheet ws, int extraWith) {
        // 获取本列的最宽单元格的宽度
        for (int i = 0; i < ws.getColumns(); i++) {
            int colWith = 0;
            for (int j = 0; j < ws.getRows(); j++) {
                String content = ws.getCell(i, j).getContents().toString();
                int cellWith = content.length();
                if (colWith < cellWith) {
                    colWith = cellWith;
                }
            }
            // 设置单元格的宽度为最宽宽度+额外宽度
            ws.setColumnView(i, colWith + extraWith);
        }
    }
    /**
     * @param in          : 输入流
     * @param entityClass :实体class
     * @param fieldMap    :Excel中的中文列头和类的英文属性的对应关系Map
     * @MethodName : excelToList
     * @Description : 将Excel转化为List
     */
    public static <T> List<T> excelToList(InputStream in, String sheetName, Class<T> entityClass, HashMap<String, String> fieldMap) {
        // 定义要返回的list
        List<T> resultList = new ArrayList<T>();
        try {
            // 根据Excel数据源创建WorkBook
            Workbook wb = Workbook.getWorkbook(in);
            // 获取工作表
            Sheet sheet = wb.getSheet(sheetName);
            // 获取工作表的有效行数
            int realRows = 0;
            for (int i = 0; i < sheet.getRows(); i++) {
                int nullCols = 0;
                for (int j = 0; j < sheet.getColumns(); j++) {
                    Cell currentCell = sheet.getCell(j, i);
                    if (currentCell == null
                            || "".equals(currentCell.getContents().toString())) {
                        nullCols++;
                    }
                }
                if (nullCols == sheet.getColumns()) {
                    break;
                } else {
                    realRows++;
                }
            }
            // 如果Excel中没有数据则提示错误
            if (realRows <= 1) {
                throw new Exception("Excel文件中没有任何数据");
            }
            Cell[] firstRow = sheet.getRow(0);
            String[] excelFieldNames = new String[firstRow.length];
            // 获取Excel中的列名
            for (int i = 0; i < firstRow.length; i++) {
                excelFieldNames[i] = firstRow[i].getContents().toString().trim();
            }
            // 判断需要的字段在Excel中是否都存在
            boolean isExist = true;
            List<String> excelFieldList = Arrays.asList(excelFieldNames);
            for (String cnName : fieldMap.keySet()) {
                if (!excelFieldList.contains(cnName)) {
                    isExist = false;
                    break;
                }
            }
            // 如果有列名不存在,则抛出异常,提示错误
            if (!isExist) {
                throw new Exception("Excel中缺少必要的字段,或字段名称有误");
            }
            // 将列名和列号放入Map中,这样通过列名就可以拿到列号
            LinkedHashMap<String, Integer> colMap = new LinkedHashMap<String, Integer>();
            for (int i = 0; i < excelFieldNames.length; i++) {
                colMap.put(excelFieldNames[i], firstRow[i].getColumn());
            }
            // 将sheet转换为list
            for (int i = 1; i < realRows; i++) {
                // 新建要转换的对象
                T entity = entityClass.newInstance();
                // 给对象中的字段赋值
                for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                    // 获取中文字段名
                    String cnNormalName = entry.getKey();
                    // 获取英文字段名
                    String enNormalName = entry.getValue();
                    // 根据中文字段名获取列号
                    int col = colMap.get(cnNormalName);
                    // 获取当前单元格中的内容
                    String content = sheet.getCell(col, i).getContents().toString().trim();
                    ReflectUtil.setProperty(entity, enNormalName, content);
                }
                resultList.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }
    //向工作表中填充数据
    private static <T> void fillMapSheet(WritableSheet sheet, List<Map<String, Object>> list,
                                         Map<String, String> fieldMap, int firstIndex, int lastIndex) throws Exception {
        // 定义存放英文字段名和中文字段名的数组
        String[] enFields = new String[fieldMap.size()];
        String[] cnFields = new String[fieldMap.size()];
        // 填充数组
        int count = 0;
        for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
            enFields[count] = entry.getKey();
            cnFields[count] = entry.getValue();
            count++;
        }
        // 填充表头
        for (int i = 0; i < cnFields.length; i++) {
            Label label = new Label(i, 0, cnFields[i]);
            sheet.addCell(label);
        }
        // 填充内容
        int rowNo = 1;
        for (int index = firstIndex; index <= lastIndex; index++) {
            // 获取单个对象
            Map<String, Object> item = list.get(index);
            for (int i = 0; i < enFields.length; i++) {
                Object objValue = null;
                objValue = item.get(enFields[i]);
                String fieldValue = objValue == null ? "" : objValue.toString();
                Label label = new Label(i, rowNo, fieldValue);
                sheet.addCell(label);
            }
            rowNo++;
        }
        // 设置自动列宽
        setColumnAutoSize(sheet, 5);
    }
    //向工作表中填充数据
    private static <T> void fillObjectSheet(WritableSheet sheet, List<T> list,
                                            Map<String, String> fieldMap, int firstIndex, int lastIndex) throws Exception {
        // 定义存放英文字段名和中文字段名的数组
        String[] enFields = new String[fieldMap.size()];
        String[] cnFields = new String[fieldMap.size()];
        // 填充数组
        int count = 0;
        for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
            enFields[count] = entry.getKey();
            cnFields[count] = entry.getValue();
            count++;
        }
        // 填充表头
        for (int i = 0; i < cnFields.length; i++) {
            Label label = new Label(i, 0, cnFields[i]);
            sheet.addCell(label);
        }
        // 填充内容
        int rowNo = 1;
        for (int index = firstIndex; index <= lastIndex; index++) {
            // 获取单个对象
            T item = list.get(index);
            for (int i = 0; i < enFields.length; i++) {
                Object objValue = null;
                objValue = ReflectUtil.getNestedProperty(item, enFields[i]);
                String fieldValue = objValue == null ? "" : objValue.toString();
                Label label = new Label(i, rowNo, fieldValue);
                sheet.addCell(label);
            }
            rowNo++;
        }
        // 设置自动列宽
        setColumnAutoSize(sheet, 5);
    }
}

+ 150 - 0
src/main/java/com/yihu/hos/common/ReflectUtil.java

@ -0,0 +1,150 @@
package com.yihu.hos.common;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Created by chenweida on 2016/2/26.
 */
public class ReflectUtil {
    @SuppressWarnings("all")
//    public static void main(String[] args) throws Exception {
//    }
    /**
     * @description 设置对象属性值
     * @param obj
     *            实体对象
     * @param fieldName
     *            属性名
     * @param value
     *            属性值
     */
    public static void setProperty(Object obj, String fieldName, Object value) {
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            if (field != null) {
                Class<?> fieldType = field.getType();
                field.setAccessible(true);
                // 根据字段类型给字段赋值
                if (String.class == fieldType) {
                    field.set(obj, String.valueOf(value));
                } else if ((Integer.TYPE == fieldType)
                        || (Integer.class == fieldType)) {
                    field.set(obj, Integer.parseInt(value.toString()));
                } else if ((Long.TYPE == fieldType)
                        || (Long.class == fieldType)) {
                    field.set(obj, Long.valueOf(value.toString()));
                } else if ((Float.TYPE == fieldType)
                        || (Float.class == fieldType)) {
                    field.set(obj, Float.valueOf(value.toString()));
                } else if ((Short.TYPE == fieldType)
                        || (Short.class == fieldType)) {
                    field.set(obj, Short.valueOf(value.toString()));
                } else if ((Double.TYPE == fieldType)
                        || (Double.class == fieldType)) {
                    field.set(obj, Double.valueOf(value.toString()));
                } else if (Character.TYPE == fieldType) {
                    if ((value != null) && (value.toString().length() > 0)) {
                        field.set(obj,
                                Character.valueOf(value.toString().charAt(0)));
                    }
                } else if (Date.class == fieldType) {
                    if (value instanceof Date) {
                        field.set(obj, value);
                    } else if (value instanceof String) {
                        field.set(obj, new SimpleDateFormat(
                                "yyyy-MM-dd HH:mm:ss").parse(value.toString()));
                    }
                } else {
                    field.set(obj, value);
                }
                field.setAccessible(false);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
    /**
     * @description 获取对象属性值
     * @param obj
     *            实体对象
     * @param fieldName
     *            属性名
     */
    public static Object getProperty(Object obj, String fieldName) {
        Field field = getFieldName(obj, fieldName);
        Object value = null;
        try {
            if (field != null) {
                Class<?> fieldType = field.getType();
                field.setAccessible(true);
                // 根据字段类型给字段赋值
                if (Date.class == fieldType) {
                    Object o = field.get(obj);
                    if (o != null) {
                        value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                .format(o);
                    }
                } else {
                    value = field.get(obj);
                }
                field.setAccessible(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }
    // 获取department.name 属性值
    public static Object getNestedProperty(Object obj, String fieldName) {
        Object value = null;
        String[] attributes = fieldName.split("\\.");
        try {
            value = getProperty(obj, attributes[0]);
            for (int i = 1; i < attributes.length; i++) {
                value = getProperty(value, attributes[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }
    // 获取属性
    public static Field getFieldName(Object obj, String fieldName) {
        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
                .getSuperclass()) {
            try {
                return superClass.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
            }
        }
        return null;
    }
    /**
     * 获取对象所有字段的名字
     * @param obj 目标对象
     * @return 字段名字的数组
     */
    public static String[] getFieldNames(Object obj) {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        List<String> fieldNames = new ArrayList<String>();
        for (int i = 0; i < fields.length; i++) {
            if ((fields[i].getModifiers() & Modifier.STATIC) == 0) {
                fieldNames.add(fields[i].getName());
            }
        }
        return fieldNames.toArray(new String[fieldNames.size()]);
    }
    public void say(String name){
    }
}

+ 119 - 0
src/main/java/com/yihu/hos/common/Services.java

@ -0,0 +1,119 @@
package com.yihu.hos.common;
/**
 * 平台顶级服务列表.
 *
 */
public class Services {
    public final static String EnvironmentOption = "com.yihu.ha.EnvironmentOption";
    public final static String RedisClient = "com.yihu.ha.RedisClient";
    public final static String HBaseClient= "com.yihu.ha.HBaseClient";
    public final static String SolrClient = "com.yihu.ha.SolrClient";
    public final static String SQLGeneralDAO = "com.yihu.ha.SQLGeneralDAO";
    public final static String AddressManager = "com.yihu.ha.AddressManager";
    public final static String AppManager = "com.yihu.ha.AppManager";
    public final static String JsonPackageManager = "com.yihu.ha.JsonPackageManager";
    public final static String EhrArchiveManager = "com.yihu.ha.EhrArchiveManager";
    public final static String SNSPlatformManager = "com.yihu.ha.SNSPlatformManager";
    public final static String DemographicIndex = "com.yihu.ha.DemographicIndex";
    public final static String DemographicIndexStragety = "com.yihu.ha.DemographicIndexStragety";
    public final static String SystemDictManager = "com.yihu.ha.SystemDictManager";
    public final static String OrgManager = "com.yihu.ha.OrgManager";
    public final static String CardManager = "com.yihu.ha.CardManager";
    public final static String TextResource = "com.yihu.ha.TextResource";
    public final static String SecurityManager = "com.yihu.ha.SecurityManager";
    public final static String CDAVersionManager = "com.yihu.ha.CDAVersionManager";
    public final static String CDAManager="com.yihu.ha.CDADocumentManager";
    public final static String StandardSourceManager="com.yihu.ha.StandardSourceManager";
    public final static String DataSetManager = "com.yihu.ha.DataSetManager";
    public final static String MetaDataManager = "com.yihu.ha.MetaDataManager";
    public final static String DictEntryManager = "com.yihu.ha.DictEntryManager";
    public final static String DictManager = "com.yihu.ha.DictManager";
    public final static String StdDiffer = "com.yihu.ha.StdDiffer";
    public final static String StdDispatchManager = "com.yihu.ha.StdDispatchManager";
    public final static String StdVersionFileManager = "com.yihu.ha.StdVersionFileManager";
    public final static String SchemaManager = "com.yihu.ha.SchemaManager";
    public final static String UserManager = "com.yihu.ha.UserManager";
    public final static String TokenManager = "com.yihu.ha.TokenManager";
    public final static String ObjectMapper = "com.yihu.ha.ObjectMapper";
    public final static String ArchiveTemplateManager = "com.yihu.ha.ArchiveTemplateManager";
    public final static String DataSetRelationshipManager = "com.yihu.ha.CdaDatasetRelationshipManager";
    public final static String ConventionalDictEntry = "com.yihu.ha.ConventionalDictEntry";
    public final static String SolrIndexer = "com.yihu.ha.SolrIndexer";
    public final static String JobManager = "com.yihu.ha.JobManager";
    public final static String SchedulerFactory = "com.yihu.ha.SchedulerFactory";
    public final static String MonitorManager = "com.yihu.ha.MonitorManager";
    public final static String OrgDictManager = "com.yihu.ha.OrgDictManager";
    public final static String OrgDictItemManager = "com.yihu.ha.OrgDictItemManager";
    public final static String OrgDataSetManager = "com.yihu.ha.OrgDataSetManager";
    public final static String OrgMetaDataManager = "com.yihu.ha.OrgMetaDataManager";
    public final static String OrgAdapterPlanManager = "com.yihu.ha.OrgAdapterPlanManager";
    public final static String AdapterDataSetManager = "com.yihu.ha.AdapterDataSetManager";
    public final static String AdapterDictManager = "com.yihu.ha.AdapterDictManager";
    public final static String AdapterOrgManager = "com.yihu.ha.AdapterOrgManager";
    public final static String AdapterInfoSendManager = "com.yihu.ha.AdapterInfoSendManager";
    public final static String RsCategoryServiceImpl = "com.yihu.ha.resource.service.impl.RsCategoryServiceImpl";
    /******************************************************************************************/
    public final static String Organization = "com.yihu.ehr.system.service.OrganizationManager";
    public final static String Datacollect = "com.yihu.ehr.datacollect.service.DatacollectManager";
    public final static String DatacollectService = "com.yihu.ehr.datacollect.service.DatacollectService";
    public final static String DatapushService = "com.yihu.ehr.datacollect.service.DatapushService";
    public final static String Datasource = "com.yihu.ehr.system.service.DatasourceManager";
    public final static String BaseDict = "com.yihu.ehr.system.service.BaseDictManager";
    public final static String StdService = "com.yihu.ehr.resource.service.impl.StdService";
}

+ 194 - 0
src/main/java/com/yihu/hos/common/controller/BaseRestEndPoint.java

@ -0,0 +1,194 @@
package com.yihu.hos.common.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.web.framework.constant.ErrorCode;
import com.yihu.hos.web.framework.constant.PageArg;
import com.yihu.hos.web.framework.exception.EsbApiException;
import com.yihu.hos.web.framework.util.DateTimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 控制器基类。提供模型转换,分页规范实现。
 *
 * @author Sand
 * @version 1.0
 * @created 2016.04.07 17:01
 */
public class BaseRestEndPoint extends AbstractController {
    protected final static String ResourceCount = "X-Total-Count";
    protected final static String ResourceLink = "Link";
    @Autowired
    protected ObjectMapper objectMapper;
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        return null;
    }
    /**
     * 将实体转换为模型。
     *
     * @param source
     * @param targetCls
     * @param properties
     * @param <T>
     * @return
     */
    public <T> T convertToModel(Object source, Class<T> targetCls, String... properties) {
        if (source == null) {
            return null;
        }
        T target = BeanUtils.instantiate(targetCls);
        BeanUtils.copyProperties(source, target, propertyDiffer(properties, targetCls));
        return target;
    }
    public <T> T toEntity(String json, Class<T> entityCls) {
        try {
            objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.ISO8601Pattern));
            T entity = objectMapper.readValue(json, entityCls);
            return entity;
        } catch (IOException ex) {
            throw new EsbApiException(ErrorCode.SystemError, "Unable to parse json, " + ex.getMessage());
        }
    }
    public String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            return null;
        }
    }
    /**
     * 将实体集合转换为模型集合。
     *
     * @param sources
     * @param targets
     * @param properties
     * @param <T>
     * @return
     */
    public <T> Collection<T> convertToModels(Collection sources, Collection<T> targets, Class<T> targetCls, String properties) {
        if (sources == null) {
            return null;
        }
        Iterator iterator = sources.iterator();
        while (iterator.hasNext()) {
            Object source = iterator.next();
            T target = (T) BeanUtils.instantiate(targetCls);
            BeanUtils.copyProperties(source, target, propertyDiffer(StringUtils.isEmpty(properties) ? null : properties.split(","), targetCls));
            targets.add(target);
        }
        return targets;
    }
    /**
     * 计算不在类中的属性。
     *
     * @return
     */
    protected String[] propertyDiffer(String[] properties, Class targetCls) {
        if (properties == null || properties.length == 0) return null;
        PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(targetCls);
        List<String> propertiesList = Arrays.asList(properties);
        List<String> arrayList = new ArrayList<>();
        for (PropertyDescriptor targetPd : targetPds) {
            Method writeMethod = targetPd.getWriteMethod();
            if (writeMethod != null && !propertiesList.contains(targetPd.getName())) {
                arrayList.add(targetPd.getName());
            }
        }
        return arrayList.toArray(new String[arrayList.size()]);
    }
    /**
     * 客户端调用REST接口时,若返回的是分页结果,则需要在响应头中添加资源的总数量及其他资源的分页导航。
     * EHR平台使用响应头中的 X-Total-Count 字段记录资源的总数量,link header作为其他资源的分页导航。
     *
     * @return
     */
    public void pagedResponse(
            HttpServletRequest request,
            HttpServletResponse response,
            Long resourceCount, Integer currentPage, Integer pageSize) {
        if (request == null || response == null) return;
        response.setHeader(ResourceCount, Long.toString(resourceCount));
        if (resourceCount == 0) return;
        if (currentPage == null) currentPage = new Integer(PageArg.DefaultPage);
        if (pageSize == null) pageSize = new Integer(PageArg.DefaultSize);
        String baseUri = "<" + request.getRequestURL().append("?").toString() + request.getQueryString() + ">";
        long firstPage = currentPage == 1 ? -1 : 1;
        long prevPage = currentPage == 1 ? -1 : currentPage - 1;
        long lastPage = resourceCount % pageSize == 0 ? resourceCount / pageSize : resourceCount / pageSize + 1;
        long nextPage = currentPage == lastPage ? -1 : currentPage + 1;
        lastPage = currentPage == lastPage ? -1 : lastPage;
        Map<String, String> map = new HashMap<>();
        if (firstPage != -1)
            map.put("rel='first',", baseUri.replaceAll("page=\\d+", "page=" + Long.toString(firstPage)));
        if (prevPage != -1) map.put("rel='prev',", baseUri.replaceAll("page=\\d+", "page=" + Long.toString(prevPage)));
        if (nextPage != -1) map.put("rel='next',", baseUri.replaceAll("page=\\d+", "page=" + Long.toString(nextPage)));
        if (lastPage != -1) map.put("rel='last',", baseUri.replaceAll("page=\\d+", "page=" + Long.toString(lastPage)));
        response.setHeader(ResourceLink, linkMap(map));
    }
    private String linkMap(Map<String, String> map) {
        StringBuffer links = new StringBuffer("");
        for (String key : map.keySet()) {
            links.append(map.get(key)).append("; ").append(key);
        }
        return links.toString();
    }
    protected Integer reducePage(Integer page) {
        if (page != null || page > 0) {
            page = page - 1;
            return page;
        }
        return 1;
    }
    protected String getClientId(HttpServletRequest request){
        String userAgent = "";
        Enumeration<String> headers = request.getHeaders("User-Agent");
        while (headers.hasMoreElements()){
            String s = headers.nextElement();
            if (!s.contains("jetty")){
                userAgent = s;
            }
        }
        return StringUtils.isEmpty(userAgent) ? "" : userAgent.split(" ").length>1?userAgent.split(" ")[1]:userAgent.split(" ")[0];
    }
}

+ 308 - 0
src/main/java/com/yihu/hos/common/controller/CommonPageController.java

@ -0,0 +1,308 @@
package com.yihu.hos.common.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yihu.hos.core.http.HTTPResponse;
import com.yihu.hos.core.http.HttpClientKit;
import com.yihu.hos.model.syspermission.AppFeatureModel;
import com.yihu.hos.remotemanage.service.RemoteShellService;
import com.yihu.hos.system.model.SystemUser;
import com.yihu.hos.tenant.model.TenantSession;
import com.yihu.hos.tenant.service.AuthenticateService;
import com.yihu.hos.web.framework.constant.ContextAttributes;
import com.yihu.hos.web.framework.model.AccessToken;
import com.yihu.hos.web.framework.model.Envelop;
import com.yihu.hos.web.framework.model.EnvelopExt;
import com.yihu.hos.web.framework.util.controller.BaseController;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
/**
 * 数据采集配置页面
 * Created by hzp on 2015/8/12.
 */
@RequestMapping("/")
@Controller("commonPageController")
public class CommonPageController extends BaseController {
    @Value("${hos.saasAdmin}")
    private String saasAdmin;
    @Value("${hos.clientId}")
    private String clientId;
    @Autowired
    private AuthenticateService authenticateService;
    private RemoteShellService remoteShellService;
    @RequestMapping("testPage")
    public String initial(Model model) {
        model.addAttribute("contentPage", "/common/test");
        return "pageView";
    }
    /**
     *  租户授权失败跳转页面
     * @param model
     * @return
     */
    @RequestMapping("tenantAutoFail")
    public String tenantAutoFail(Model model) {
        model.addAttribute("contentPage", "/common/tenantAutoFail");
        return "pageView";
    }
    /**
     *  集成登录验证失败跳转页面
     * @param model
     * @return
     */
    @RequestMapping("/oauth2/tokenValidFail")
    public String tokenValidFail(Model model) {
        model.addAttribute("contentPage", "/common/tokenValidFail");
        return "pageView";
    }
    /*
    登录页面
     */
    @RequestMapping("loginPage")
    public String login(Model model, HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String urlType = (String) request.getSession().getAttribute("attachment");
        request.getSession().removeAttribute("attachment");
        //租户类型
        model.addAttribute("urlType", urlType);
        try {
            boolean auth = authenticateService.auth(session, saasAdmin);
            if (!auth) {
                //授权失败
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                PrintWriter out = null;
                try {
                    out = response.getWriter();
//                    out.print("<script>alert('登录地址有误-用户授权失败!');</script>");
                    response.sendRedirect("/esb/tenantAutoFail");
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    IOUtils.closeQuietly(out);
                }
            } else {
                remoteShellService.start();//启动
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("contentPage", "/common/login");
        return "pageView";
    }
    /**
     * 租户登录页面
     *
     * @param model
     * @param tenantName
     * @param request
     * @return
     */
    @RequestMapping("{tenantName}/loginPage")
    public String tenantLogin(Model model,
                              @PathVariable(name = "tenantName") String tenantName,
                              HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        boolean auth = false;
        try {
            auth = authenticateService.auth(session, tenantName);
            System.out.println("auth:   " + auth);
            if (!auth) {
                //授权失败,切换回管理平台数据库
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                PrintWriter out = null;
                try {
                    out = response.getWriter();
//                    out.print("<script>alert('请求地址不存在!');</script>");
                    response.sendRedirect("/esb/tenantAutoFail");
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    IOUtils.closeQuietly(out);
                }
            } else {
                remoteShellService.start();//启动远程连接
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("contentPage", "/common/login");
        return "pageView";
    }
    /*
首页页面
 */
    @RequestMapping("indexPage")
    public String index(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        SystemUser user = (SystemUser) session.getAttribute("userInfo");
        if (session.getAttribute(ContextAttributes.TENANT_SESSION)!=null){
            TenantSession tenantSession = (TenantSession) session.getAttribute(ContextAttributes.TENANT_SESSION);
            model.addAttribute("tenant", tenantSession.getTenant());
        }
;
        model.addAttribute("userName", user.getUserName());
        //获取菜单
        String menu = "[{id: 1, text: '任务管理',icon:'${staticRoot}/images/index/menu2_icon.png'},\n" +
                "        {id: 11, pid: 1, text: '任务跟踪', url: '${contextRoot}/datacollect/trackJob',targetType:'1'},\n" +
                "        {id: 12, pid: 1, text: '任务补采', url: '${contextRoot}/datacollect/repeatDatacollect'},\n" +
                "        {id: 13, pid: 1, text: '任务配置', url: '${contextRoot}/datacollect/configJob'},\n" +
                "        {id: 2, text: '标准管理',icon:'${staticRoot}/images/index/menu3_icon.png'},\n" +
                "        {id: 21, pid: 2, text: '集成标准', url: '${contextRoot}/integration/initial/standard'},\n" +
                "        {id: 22, pid: 2, text: '应用标准', url: '${contextRoot}/integration/initial/application'},\n" +
                "        {id: 23, pid: 2, text: '适配方案', url: '${contextRoot}/adapterPlan/initial'},\n" +
                "        {id: 3, text: '资源管理',icon:'${staticRoot}/images/index/menu4_icon.png'},\n" +
                "        {id: 31, pid: 3, text: '资源注册', url: '${contextRoot}/resource/resource/initial'},\n" +
                "        {id: 32, pid: 3, text: '资源浏览', url: '${contextRoot}/resource/resourcePage'},\n" +
                "        {id: 34, pid: 3, text: '资源分类', url: '${contextRoot}/resource/rsCategory/initial'},\n" +
                "        {id: 35, pid: 3, text: '业务资源', url: '${contextRoot}/resourceRest/initial'},\n" +
                "        {id: 4, text: '维度管理',icon:'${staticRoot}/images/index/menu5_icon.png'},\n" +
                "        {id: 41, pid: 4, text: '维度配置', url: '${contextRoot}/dimension/dimension'},\n" +
                "        {id: 42, pid: 4, text: '维度类别配置', url: '${contextRoot}/dimension/dimensioncatetory'},\n" +
                "        {id: 9, text: '系统配置',icon:'${staticRoot}/images/index/menu6_icon.png'},\n" +
                "        {id: 91, pid: 9, text: '机构配置', url: '${contextRoot}/org/initial'},\n" +
                "        {id: 92, pid: 9, text: '数据源配置', url: '${contextRoot}/datasource/configSources'},\n" +
                "        {id: 93, pid: 9, text: '菜单配置', url: '${contextRoot}/menu/initial'},\n" +
                "        {id: 100, pid: 9, text: '菜单按钮配置', url: '${contextRoot}/menu/menuAction/initial'},\n" +
                "        {id: 94, pid: 9, text: '用户管理', url: '${contextRoot}/user/initial'},\n" +
                "        {id: 95, pid: 9, text: '角色管理', url: '${contextRoot}/role/initial'},\n" +
                "        {id: 96, pid: 9, text: '权限管理', url: '${contextRoot}/authority/initial'},\n" +
                "        {id: 97, pid: 9, text: '字典管理', url: '${contextRoot}/dict/initial' },\n" +
                "        {id: 98, pid: 9, text: '系统参数', url: '${contextRoot}/param/initial'},\n" +
                "        {id: 99, pid: 9, text: '<spring:message code=\"title.app.manage\"/>', url: '${contextRoot}/app/initial'}]";
        model.addAttribute("menu", menu);
        model.addAttribute("contentPage", "/common/index");
        return "pageView";
    }
    /**
     * oauth2 自动登录后首页
     *
     * @param tenantName 租户名称
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("{tenantName}/oauth2/index")
    public String tenantIndex(
            @PathVariable(name = "tenantName") String tenantName,
            HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        boolean auth = false;
        String loginName = request.getParameter(ContextAttributes.LOGIN_NAME);
        SystemUser userInfo = new SystemUser();
        userInfo.setLoginCode(loginName);
        userInfo.setUserName("管理员");
        session.setAttribute("userInfo", userInfo);
        try {
            auth = authenticateService.auth(session, tenantName);
            if (!auth) {
                model.addAttribute("contentPage", "/common/tokenValidFail");
                return "pageView";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("userName", loginName);
        model.addAttribute("tenant", tenantName);
        //获取菜单
        String menu = "[{id: 1, text: '任务管理',icon:'${staticRoot}/images/index/menu2_icon.png'},\n" +
                "        {id: 11, pid: 1, text: '任务跟踪', url: '${contextRoot}/datacollect/trackJob',targetType:'1'},\n" +
                "        {id: 12, pid: 1, text: '任务补采', url: '${contextRoot}/datacollect/repeatDatacollect'},\n" +
                "        {id: 13, pid: 1, text: '任务配置', url: '${contextRoot}/datacollect/configJob'},\n" +
                "        {id: 2, text: '标准管理',icon:'${staticRoot}/images/index/menu3_icon.png'},\n" +
                "        {id: 21, pid: 2, text: '集成标准', url: '${contextRoot}/integration/initial/standard'},\n" +
                "        {id: 22, pid: 2, text: '应用标准', url: '${contextRoot}/integration/initial/application'},\n" +
                "        {id: 23, pid: 2, text: '适配方案', url: '${contextRoot}/adapterPlan/initial'},\n" +
                "        {id: 3, text: '资源管理',icon:'${staticRoot}/images/index/menu4_icon.png'},\n" +
                "        {id: 31, pid: 3, text: '资源注册', url: '${contextRoot}/resource/resource/initial'},\n" +
                "        {id: 32, pid: 3, text: '资源浏览', url: '${contextRoot}/resource/resourcePage'},\n" +
                "        {id: 34, pid: 3, text: '资源分类', url: '${contextRoot}/resource/rsCategory/initial'},\n" +
                "        {id: 35, pid: 3, text: '业务资源', url: '${contextRoot}/resourceRest/initial'},\n" +
                "        {id: 4, text: '维度管理',icon:'${staticRoot}/images/index/menu5_icon.png'},\n" +
                "        {id: 41, pid: 4, text: '维度配置', url: '${contextRoot}/dimension/dimension'},\n" +
                "        {id: 42, pid: 4, text: '维度类别配置', url: '${contextRoot}/dimension/dimensioncatetory'},\n" +
                "        {id: 9, text: '系统配置',icon:'${staticRoot}/images/index/menu6_icon.png'},\n" +
                "        {id: 91, pid: 9, text: '机构配置', url: '${contextRoot}/org/initial'},\n" +
                "        {id: 92, pid: 9, text: '数据源配置', url: '${contextRoot}/datasource/configSources'},\n" +
                "        {id: 93, pid: 9, text: '菜单配置', url: '${contextRoot}/menu/initial'},\n" +
                "        {id: 100, pid: 9, text: '菜单按钮配置', url: '${contextRoot}/menu/menuAction/initial'},\n" +
                "        {id: 94, pid: 9, text: '用户管理', url: '${contextRoot}/user/initial'},\n" +
                "        {id: 95, pid: 9, text: '角色管理', url: '${contextRoot}/role/initial'},\n" +
                "        {id: 96, pid: 9, text: '权限管理', url: '${contextRoot}/authority/initial'},\n" +
                "        {id: 97, pid: 9, text: '字典管理', url: '${contextRoot}/dict/initial' },\n" +
                "        {id: 98, pid: 9, text: '系统参数', url: '${contextRoot}/param/initial'},\n" +
                "        {id: 99, pid: 9, text: '<spring:message code=\"title.app.manage\"/>', url: '${contextRoot}/app/initial'}]";
        model.addAttribute("menu", menu);
        model.addAttribute("contentPage", "/common/index");
        //从此处登入不显示logo(标识showLogo==false)
        model.addAttribute("showLogo", "false");
        return "pageView";
    }
    /**
     * oauth2 自动登陆中间页
     *
     * @param model
     * @param tenantName
     * @return
     */
    @RequestMapping(value = "{tenantName}/oauth2/signin")
    public String signin(Model model,
                         @PathVariable(name = "tenantName") String tenantName) {
        model.addAttribute("tenantName", tenantName);
        model.addAttribute("contentPage", "common/signin");
        model.addAttribute("successFlg", true);
        return "pageView";
    }
    @Autowired
    public void setRemoteShellService(RemoteShellService remoteShellService) {
        this.remoteShellService = remoteShellService;
    }
}

+ 57 - 0
src/main/java/com/yihu/hos/common/controller/EnvelopRestEndPoint.java

@ -0,0 +1,57 @@
package com.yihu.hos.common.controller;
import com.yihu.ehr.util.id.BizObject;
import com.yihu.ehr.util.id.ObjectId;
import com.yihu.ehr.util.rest.Envelop;
import java.util.List;
/**
 * REST风格控控制器基类。此控制器用于对API进行校验,并处理平台根层级的业务,如API参数校验,错误及返回码设定等。
 * <p>
 * 根层级的校验,如果是正确的,直接返回HTTP代码200,若出错,则会将HTTP返回代码设置为1X或2X,并在HTTP响应体中包含响应的信息。
 * HTTP响应体格式为JSON。
 * + 成功:会根据各业务逻辑自行决定要返回的数据,各业务模块的返回结构不同。
 * + 失败:{"code":"错误代码", "message":"错误原因"}
 *
 * @author zhiyong
 * @author Sand
 */
public class EnvelopRestEndPoint extends BaseRestEndPoint {
//    @Value("${deploy.region}")
    Short deployRegion = 3502;
    /**
     * 返回一个信封对象。信封对象的返回场景参见 Envelop.
     *
     * @param modelList
     * @param totalCount
     * @return
     */
    protected Envelop getResult(List modelList, int totalCount) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(true);
        envelop.setDetailModelList(modelList);
        envelop.setTotalCount(totalCount);
        return envelop;
    }
    public Envelop failed(String errMsg){
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        envelop.setErrorMsg(errMsg);
        return envelop;
    }
    public Envelop success(Object object){
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(true);
        envelop.setObj(object);
        return envelop;
    }
    protected String getObjectId(BizObject bizObject){
        return new ObjectId(deployRegion, bizObject).toString();
    }
}

+ 97 - 0
src/main/java/com/yihu/hos/common/controller/ExtendEndPoint.java

@ -0,0 +1,97 @@
package com.yihu.hos.common.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.web.framework.constant.ErrorCode;
import com.yihu.hos.web.framework.exception.EsbApiException;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
 * @author lincl
 * @version 1.0
 * @created 2016/2/4
 */
public class ExtendEndPoint<T>  extends EnvelopRestEndPoint {
    protected Long[] strToLongArr(String str){
        if(str==null || str.trim().length()==0)
            return new Long[0];
        return strArrToLongArr(str.split(","));
    }
    protected Integer[] strToIntegergArr(String str){
        if(str==null || str.trim().length()==0)
            return new Integer[0];
        return strArrToIntegerArr(str.split(","));
    }
    protected Integer[] strArrToIntegerArr(String[] strArr){
        Integer[] rs = new Integer[strArr.length];
        for (int i=0; i< strArr.length; i++){
            rs[i] = Integer.valueOf(strArr[i]);
        }
        return rs;
    }
    protected Long[] strArrToLongArr(String[] strArr){
        Long[] rs = new Long[strArr.length];
        for (int i=0; i< strArr.length; i++){
            rs[i] = Long.valueOf(strArr[i]);
        }
        return rs;
    }
    protected <T> T jsonToObj(String json ,Class<T> clz) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(json, clz);
    }
    protected T getModel(Object o){
        return (T) convertToModel(o, getModelClass());
    }
    public Class getModelClass() {
        Type genType = this.getClass().getGenericSuperclass();
        Type[] parameters = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class) parameters[0];
    }
    /*******************************************************************************************/
    /****************    以下是错误返回信息方法              **********************************/
    /*******************************************************************************************/
    protected EsbApiException errSystem(){
        return new EsbApiException(ErrorCode.SystemError, "系统出错!");
    }
    protected EsbApiException errParm(){
        return new EsbApiException(ErrorCode.InvalidParameter, "参数解析错误!");
    }
    protected EsbApiException errMissCode(){
        return errMissParm("代码");
    }
    protected EsbApiException errMissId(){
        return errMissParm("编号");
    }
    protected EsbApiException errRepeatCode(){
        return new EsbApiException(ErrorCode.RepeatCode);
    }
    protected EsbApiException errMissParm(String msg){
        return new EsbApiException(ErrorCode.MissParameter, msg);
    }
    protected EsbApiException errNotFound(String objName, Object id){
        return new EsbApiException(ErrorCode.NotFoundObj, objName, String.valueOf(id));
    }
    protected EsbApiException errMissVersion(){
        return new EsbApiException(ErrorCode.MissVersion, "版本号不能为空!");
    }
}

+ 353 - 0
src/main/java/com/yihu/hos/common/graph/DGraphImpl.java

@ -0,0 +1,353 @@
package com.yihu.hos.common.graph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
 * 邻接链表(Adjacency List)实现的有向图
 * @param <V>
 */
public class DGraphImpl<V> implements IDGraph<V> {
    private static Logger logger = LoggerFactory.getLogger(DGraphImpl.class);
    /**
     * 顶点对象,其中有对应的顶点以及从以此顶点为起点的边
     */
    private class VE {
        /**此顶点*/
        private V v;
        /**以此顶点为起点的边的集合,是一个列表,列表的每一项是一条边*/
        private List<Edge<V>> mEdgeList;
        
        /**
         * 构造一个新的顶点对象
         * @param v
         */
        public VE(V v) {
            this.v = v;
            this.mEdgeList = new LinkedList<Edge<V>>();
        }
        
        @Override
        public String toString() {
            String ret = String.format("v : %s , list len : %s",
                                       v, mEdgeList.size());
            return ret;
        }
        
        /**
         * 将一条边添加到边集合中
         * @param e
         */
        public void addEdge(Edge<V> e) {
            if(getEdge(e.getDest()) == null) {
                mEdgeList.add(e);
            } else {
                logger.warn("edge exist : %s", e);
            }
        }
        
        /**
         * 读取某条边
         * @param dest
         * @return
         */
        public Edge<V> getEdge(V dest) {
            Edge<V> ret = null;
            if(dest != null) {
                for(Edge<V> edge : mEdgeList) {
                    if(edge.getDest() != null &&
                       dest.equals(edge.getDest())) {
                        ret = edge;
                        break;
                    }
                }
            }
            return ret;
        }
        
        /**
         * 读取某条边
         * @param dest
         * @return
         */
        public Edge<V> removeEdge(V dest) {
            Edge<V> ret = null;
            if(dest != null) {
                for(Edge<V> edge : mEdgeList) {
                    if(edge.getDest() != null &&
                       dest.equals(edge.getDest())) {
                        ret = edge;
                        mEdgeList.remove(edge);
                        break;
                    }
                }
            }
            return ret;
        }
    }
    
    /**
     * 广度优先的迭代器
     */
    public class BFSIterator implements Iterator<V> {
        /**已访问过的顶点列表*/
        private List<V> mVisitList = null;
        /**待访问的顶点队列*/
        private Queue<V> mVQueue = null;
        /**
         * 构造广度优先迭代器
         * @param root
         */
        public BFSIterator(V root) {
            mVisitList = new LinkedList<V>();
            mVQueue = new LinkedList<V>();
            //将初始节点入队列
            mVQueue.offer(root);
        }
        @Override
        public boolean hasNext() {
            if(mVQueue.size() > 0) {
                return true;
            } else {
                return false;
            }
        }
        @Override
        public V next() {
            //1.取队列元素
            V v = mVQueue.poll();
            if(v != null) {
                //2.将此元素的邻接边中对应顶点入队列,这些顶点需要符合以下条件:
                //1)没访问过;
                //2)不在队列中;
                VE ve = getVE(v);
                if(ve != null) {
                    List<Edge<V>> list = ve.mEdgeList;
                    for(Edge<V> edge : list) {
                        V dest = edge.getDest();
                        if(!VinList(dest, mVisitList.iterator()) &&
                           !VinList(dest, mVQueue.iterator())) {
                            mVQueue.offer(dest);
                        }
                    }
                }
                //3.将此顶点添加到已访问过的顶点列表中
                mVisitList.add(v);
            }
            //4.返回出队列的元素
            return v;
        }
        @Override
        public void remove() {
            // 暂时不实现
        }
    }
    /**顶点列表,由于会经常进行插入删除,使用链表队列*/
    private LinkedList<VE> mVEList;
    /**
     * 构造邻接链表有向图
     */
    public DGraphImpl() {
        mVEList = new LinkedList<VE>();
    }
    @Override
    public int add(V v) {
        int index = -1;
        if(v != null) {
            VE ve = new VE(v);
            mVEList.add(ve);
            index = mVEList.indexOf(ve);
        }
        return index;
    }
    @Override
    public void add(Edge<V> e) {
        if(e != null) {
            VE ve = getVE(e.getSource());
            if(ve != null) {
                //若边的起点已经在列表里,则直接将其添加到对应的顶点对象中
                ve.addEdge(e);
            } else {
                //否则提示错误
                logger.error("Error, can't find v : %s", e.getSource());
            }
        }
    }
    
    @Override
    public V remove(V v) {
        V ret = null;
        
        VE ve = removeVE(v);
        if(ve != null) {
            ret = ve.v;
        }
        
        removeRelateEdge(v);
        
        return ret;
    }
    @Override
    public Edge<V> remove(Edge<V> e) {
        Edge<V> ret = null;
        
        if(e != null) {
            VE ve = getVE(e.getSource());
            if(ve != null) {
                ret = ve.removeEdge(e.getDest());
            }
        }
        
        return ret;
    }
    @Override
    public V get(int index) {
        V ret = null;
        if(index >=0 && index < mVEList.size()) {
            VE ve = mVEList.get(index);
            if(ve != null) {
                ret = ve.v;
            }
        }
        return ret;
    }
    @Override
    public Edge<V> get(int src, int dest) {
        Edge<V> ret = null;
        V s = get(src);
        V d = get(dest);
        if(s != null && d != null) {
            VE ve = getVE(s);
            if(ve != null) {
                ret = ve.getEdge(d);
            }
        }
        return ret;
    }
    @Override
    public Iterator<V> iterator(V root) {
        Iterator<V> ret = null;
            //广度优先的迭代器
        ret = new BFSIterator(root);
        return ret;
    }
    @Override
    public void convertDAG() {
        // TODO Auto-generated method stub
        
    }
    /**
     * 从顶点对象列表中读取输入顶点对应的所有边对象
     * @param v
     * @return
     */
    @Override
    public List<Edge<V>> getEdgeList(V v) {
        List<Edge<V>> edgeList = new ArrayList<>();
        VE ret = null;
        if(v != null) {
            for(VE ve : mVEList) {
                if(ve.v != null && v.equals(ve.v)) {
                    ret = ve;
                    break;
                }
            }
        }
        if (ret != null) {
            return ret.mEdgeList;
        }
        return edgeList;
    }
    //////////////////////////////私有方法//////////////////////////////
    /**
     * 从顶点对象列表中读取输入顶点对应的对象
     * @param v
     * @return
     */
    public VE getVE(V v) {
        VE ret = null;
        if(v != null) {
            for(VE ve : mVEList) {
                if(ve.v != null && v.equals(ve.v)) {
                    ret = ve;
                    break;
                }
            }
        }
        return ret;
    }
    /**
     * 从顶点对象列表中删除输入顶点对应的对象
     * @param v
     * @return 删除的顶点对象
     */
    private VE removeVE(V v) {
        VE ret = null;
        if(v != null) {
            for(VE ve : mVEList) {
                if(ve.v != null && v.equals(ve.v)) {
                    ret = ve;
                    mVEList.remove(ve);
                    break;
                }
            }
        }
        return ret;
    }
    
    /**
     * 删除以某个点作为重点的边
     * @param v
     */
    private void removeRelateEdge(V v) {
        if(v != null) {
            for(VE ve : mVEList) {
                ve.removeEdge(v);
            }
        }
    }
    
    /**
     * 判断某个端点是否在某个列表里
     * @param v
     * @param it
     * @return
     */
    private boolean VinList(V v, Iterator<V> it) {
        boolean ret = false;
        
        if(v != null && it != null) {
            while(it.hasNext()) {
                V v_temp = it.next();
                if(v_temp != null && v_temp.equals(v)) {
                    ret = true;
                    break;
                }
            }
        }
        
        return ret;
    }
}

+ 56 - 0
src/main/java/com/yihu/hos/common/graph/Edge.java

@ -0,0 +1,56 @@
package com.yihu.hos.common.graph;
/**
 * 一条边,可以根据需要继承此类
 * @param <V>
 */
public class Edge<V> {
    /**起点*/
    private V src;
    /**终点*/
    private V dest;
    /**名称*/
    private V name;
    
    /**
     * 带名称的一条边
     * @param src
     * @param dest
     * @param name
     */
    public Edge(V src, V dest, V name) {
        this.src = src;
        this.dest = dest;
        this.name = name;
    }
    
    /**
     * 获取起点
     * @return
     */
    public V getSource() {
        return this.src;
    }
    
    /**
     * 获取终点
     * @return
     */
    public V getDest() {
        return this.dest;
    }
    
    /**
     * 获取名称
     * @return
     */
    public V getName() {
        return this.name;
    }
    
    @Override
    public String toString() {
        String ret = String.format("src : %s , dest : %s , weight : %s", src, dest, name);
        return ret;
    }
}

+ 75 - 0
src/main/java/com/yihu/hos/common/graph/IDGraph.java

@ -0,0 +1,75 @@
package com.yihu.hos.common.graph;
import java.util.Iterator;
import java.util.List;
/**
 * 有向图接口,定义需要实现的各个方法,可以选择使用邻接矩阵或者邻接链表来实现
 * @param <V> V代表端点,可以根据需要设置器数据类型
 */
public interface IDGraph<V> {
    
    /**广度优先遍历*/
    public static final int ITERATOR_TYPE_BFS = 0;
    
    /**
     * 添加一个端点
     * @param v
     * @return 新增端点的编号,-1表示插入失败
     */
    public int add(V v);
    
    /**
     * 添加一个边
     * @param e
     */
    public void add(Edge<V> e);
    
    /**
     * 删除一个顶点,与其相连的边也会被删除
     * @param v
     * @return 被删除的顶点,如果找不到对应顶点则返回null
     */
    public V remove(V v);
    
    /**
     * 删除一条边
     * @param e
     * @return 被删除的边,如果找不到对应的边则返回null
     */
    public Edge<V> remove(Edge<V> e);
    
    /**
     * 获得一个顶点
     * @param index 顶点的编号
     * @return
     */
    public V get(int index);
    
    /**
     * 获得一条边
     * @param src 起点的编号
     * @param dest 终点的编号
     * @return
     */
    public Edge<V> get(int src, int dest);
    
    /**
     * 得到当前图的迭代器,用于对图进行遍历
     * @param root 从哪个点开始遍历
     * @return
     */
    public Iterator<V> iterator(V root);
    
    /**
     * 将图转换为无环图
     */
    public void convertDAG();
    /**
     * 从顶点对象列表中读取输入顶点对应的所有边对象
     * @param v
     * @return
     */
    public List<Edge<V>> getEdgeList(V v);
}

+ 219 - 0
src/main/java/com/yihu/hos/config/BeanConfig.java

@ -0,0 +1,219 @@
package com.yihu.hos.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.filter.HibernateFilter;
import com.yihu.hos.interceptor.AuditInterceptor;
import com.yihu.hos.listeners.ApplicationStart;
import com.yihu.hos.standard.match.dictionary.DictitemStandardExistStrategy;
import com.yihu.hos.standard.match.metadata.MetatdataStandardExistStrategy;
import io.zbus.mq.Broker;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/8/5.
 */
@Configuration
@EnableTransactionManagement
@ComponentScan("com.yihu.hos")
//@ImportResource({"classpath:spring/applicationContext.xml"}) //applicationContext相关bean创建
public class BeanConfig {
    public static Map<String, String> vesionedEntitys = new HashMap<>();
    static {
        vesionedEntitys.put("com.yihu.hos.standard.model.standard.StdDataSetModel", "std_dataset_");
        vesionedEntitys.put("com.yihu.hos.standard.model.standard.StdMetaDataModel", "std_metadata_");
        vesionedEntitys.put("com.yihu.hos.standard.model.standard.StdDictionaryModel", "std_dictionary_");
        vesionedEntitys.put("com.yihu.hos.standard.model.standard.StdDictionaryModel", "std_dictionary_entry_");
        vesionedEntitys.put("com.yihu.ehr.standard.document.service.CDADocument", "std_cda_document_");
        vesionedEntitys.put("com.yihu.ehr.standard.document.service.CDADataSetRelationship", "std_cda_data_set_relationship_");
    }
    @Autowired
    private DataSource dataSource;
    @Value("${hos.zbus.url}")
    private String zbusUrl;
    private Broker broker;
    @Value("${hos.filesystem.url}")
    private String fsUrl;
    @Bean
    public Broker getBroker() {
        broker = new Broker(zbusUrl);
        return broker;
    }
    public String getZbusUrl() {
        return zbusUrl;
    }
    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
        localSessionFactoryBean.setDataSource(this.dataSource);
        Properties properties1 = new Properties();
        properties1.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        properties1.setProperty("hibernate.show_sql", "false");
        properties1.setProperty("hibernate.format_sql", "true");
        localSessionFactoryBean.setHibernateProperties(properties1);
        localSessionFactoryBean.setPackagesToScan("com.yihu.hos.*.entity", "com.yihu.hos.*.model");
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("resource/");
        localSessionFactoryBean.setMappingDirectoryLocations(resource);
        //设置拦截器
        localSessionFactoryBean.setEntityInterceptor(this.auditInterceptor());
        return localSessionFactoryBean;
    }
    //txManager事务开启
//    @Bean
//    public HibernateTransactionManager txManager() throws SQLException {
//        HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
//        LocalSessionFactoryBean sessionFactoryBean = this.sessionFactory();
//        hibernateTransactionManager.setSessionFactory(sessionFactoryBean.getObject());
//        return hibernateTransactionManager;
//    }
    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        // resolver.setDefaultEncoding("UTF-8");
        //resolver.setMaxUploadSize(50 * 1024 * 1024);// 上传文件大小 5M 5*1024*1024
        return resolver;
    }
    //国际化配置
    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasenames("text/message");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
    @Bean
    public CookieLocaleResolver localeResolver() {
        CookieLocaleResolver localeResolver = new CookieLocaleResolver();
        localeResolver.setCookieName("Language");
        localeResolver.setCookieMaxAge(604800);
        localeResolver.setDefaultLocale(new Locale("zh_cn"));
        return localeResolver;
    }
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        return new LocaleChangeInterceptor();
    }
    @Bean
    public JdbcTemplate jdbcTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        try {
            jdbcTemplate.setDataSource(this.dataSource);
            jdbcTemplate.setLazyInit(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jdbcTemplate;
    }
    //Hibernate模版配置
    @Bean
    public HibernateTemplate hibernateTemplate() throws SQLException {
        HibernateTemplate hibernateTemplate = new HibernateTemplate();
        LocalSessionFactoryBean sessionFactory = this.sessionFactory();
        hibernateTemplate.setSessionFactory(sessionFactory.getObject());
        return hibernateTemplate;
    }
    @Bean
    public Session getSession() throws HibernateException {
        LocalSessionFactoryBean sessionFactory = this.sessionFactory();
        return sessionFactory.getObject().openSession();
    }
    @Bean
    public AuditInterceptor auditInterceptor() {
        return new AuditInterceptor();
    }
    public String getFsUrl() {
        return fsUrl;
    }
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(5);
        threadPoolTaskExecutor.setMaxPoolSize(10);
        threadPoolTaskExecutor.setQueueCapacity(25);
        threadPoolTaskExecutor.setKeepAliveSeconds(300);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }
    @Bean
    public MetatdataStandardExistStrategy metatdataStandardExistStrategy() {
        return new MetatdataStandardExistStrategy();
    }
    @Bean
    public DictitemStandardExistStrategy dictitemStandardExistStrategy() {
        return new DictitemStandardExistStrategy();
    }
    @Bean
    public HibernateFilter filterConfig() {
        return new HibernateFilter();
    }
    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }
    @Bean
    public ApplicationStart applicationStart() {
        return new ApplicationStart();
    }
    @Override
    protected void finalize() throws Throwable {
        if (broker != null) {
            broker.close();
        }
        super.finalize();
    }
}

+ 42 - 0
src/main/java/com/yihu/hos/config/JsonDateValueProcessor.java

@ -0,0 +1,42 @@
package com.yihu.hos.config;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class JsonDateValueProcessor  implements JsonValueProcessor {
    private String format ="yyyy-MM-dd hh:mm:ss";
    public JsonDateValueProcessor() {
        super();
    }
    public JsonDateValueProcessor(String format) {
        super();
        this.format = format;
    }
    public Object processArrayValue(Object paramObject,
                                    JsonConfig paramJsonConfig) {
        return process(paramObject);
    }
    public Object processObjectValue(String paramString, Object paramObject,
                                     JsonConfig paramJsonConfig) {
        return process(paramObject);
    }
    private Object process(Object value){
        if(value instanceof Date){
            SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
            return sdf.format(value);
        }
        return value == null ? "" : value.toString();
    }
}

+ 57 - 0
src/main/java/com/yihu/hos/config/MongoConfig.java

@ -0,0 +1,57 @@
package com.yihu.hos.config;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static java.util.Collections.singletonList;
/**
 * @created Airhead 2016/7/27.
 */
@Configuration
public class MongoConfig {
    @Value("${spring.data.mongodb.host}")
    private String host;
    @Value("${spring.data.mongodb.port}")
    private int port;
    @Value("${spring.data.mongodb.username}")
    private String username;
    @Value("${spring.data.mongodb.password}")
    private String password;
    @Value("${spring.data.mongodb.authenticationDatabase}")
    private String authenticationDatabase;
    @Bean
    public MongoClient mongoClient() throws Exception {
        return new MongoClient(singletonList(new ServerAddress(host, port)),
                singletonList(MongoCredential.createCredential(username, authenticationDatabase, password.toCharArray())));
    }
    @Bean
    public Mongo mongo() throws Exception {
        return new MongoClient(singletonList(new ServerAddress(host, port)),
                singletonList(MongoCredential.createCredential(username, authenticationDatabase, password.toCharArray())));
    }
    public String getHost() {
        return host;
    }
    public int getPort() {
        return port;
    }
    public String getUsername() {
        return username;
    }
    public String getPassword() {
        return password;
    }
}

+ 39 - 0
src/main/java/com/yihu/hos/config/RedisConfig.java

@ -0,0 +1,39 @@
package com.yihu.hos.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import java.io.Serializable;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.11.25 17:33
 */
//@Configuration
public class RedisConfig {
//    @Bean
//    @Primary
    RedisTemplate<String, Serializable> redisTemplate(RedisConnectionFactory jedisConnectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Serializable.class));
        redisTemplate.setHashValueSerializer(new GenericToStringSerializer<>(Long.class));
        return redisTemplate;
    }
//    @Bean
//    public static ConfigureRedisAction configureRedisAction() {
//        return ConfigureRedisAction.NO_OP;
//    }
}

+ 28 - 0
src/main/java/com/yihu/hos/config/WebMvcConfig.java

@ -0,0 +1,28 @@
package com.yihu.hos.config;
import com.yihu.hos.interceptor.WebMvcInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
 *  web 请求拦截
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/12/26.
 */
//@Configurable
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new WebMvcInterceptor());
    }
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
        HiddenHttpMethodFilter hiddenHttpMethodFilter= new HiddenHttpMethodFilter();
        return hiddenHttpMethodFilter;
    }
}

+ 113 - 0
src/main/java/com/yihu/hos/config/WebSecurityConfig.java

@ -0,0 +1,113 @@
package com.yihu.hos.config;
import com.yihu.hos.jwt.secruity.JwtAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.authentication.dao.ReflectionSaltSource;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import java.util.Arrays;
//@SuppressWarnings("SpringJavaAutowiringInspection")
//@Configuration
//@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .authenticationProvider(daoAuthenticationProvider())
                .userDetailsService(this.userDetailsService)
                .passwordEncoder(md5PasswordEncoder());
    }
    //md5方式加密
    @Bean
    public Md5PasswordEncoder md5PasswordEncoder() {
        Md5PasswordEncoder md5PasswordEncoder = new Md5PasswordEncoder();
        md5PasswordEncoder.setEncodeHashAsBase64(true);
        return md5PasswordEncoder;
    }
//    @Bean
//    public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
//        return new JwtAuthenticationTokenFilter();
//    }
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // 由于使用的是JWT,我们这里不需要csrf
                .csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                // 基于token,所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                //.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // 允许对于网站静态资源的无授权访问
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                // 对于获取token的rest api要允许匿名访问
                .antMatchers("/auth/**").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();
        // 添加JWT filter
//        httpSecurity
//                .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
        // 禁用缓存
        httpSecurity.headers().cacheControl();
    }
    @Bean
    DaoAuthenticationProvider daoAuthenticationProvider() {
        ReflectionSaltSource saltSource = new ReflectionSaltSource();
        saltSource.setUserPropertyToUse("salt");//獲取salt
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(md5PasswordEncoder());//設置加密器
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setSaltSource(saltSource);
        return daoAuthenticationProvider;
    }
    //
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        ProviderManager authenticationManager = new ProviderManager(Arrays.asList(daoAuthenticationProvider()));
        //不擦除认证密码,擦除会导致TokenBasedRememberMeServices因为找不到Credentials再调用UserDetailsService而抛出UsernameNotFoundException
        authenticationManager.setEraseCredentialsAfterAuthentication(false);
        return authenticationManager;
    }
}

+ 241 - 0
src/main/java/com/yihu/hos/crawler/controller/CrawlerController.java

@ -0,0 +1,241 @@
package com.yihu.hos.crawler.controller;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.crawler.service.CrawlerService;
import com.yihu.hos.standard.service.adapter.AdapterSchemeService;
import com.yihu.hos.web.framework.model.ActionResult;
import com.yihu.hos.web.framework.model.DetailModelResult;
import com.yihu.hos.web.framework.model.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 目前版本只需要采集,上传和注册病人档案就可了。
 * <p>
 * Created by Airhead on 2015/12/16.
 */
@RequestMapping("/crawlerEndpoint")
@Controller("crawlerController")
@Api(protocols = "http", value = "CrawlerController", description = "档案采集接口", tags = {"采集"})
public class CrawlerController {
    @Resource
    CrawlerService crawlerService;
    @Resource(name = AdapterSchemeService.BEAN_ID)
    private AdapterSchemeService adapterSchemeService;
    /**
     * 任务编排
     */
    @RequestMapping("jobLayout")
    public String jobLayout(Model model) {
        model.addAttribute("contentPage", "/crawler/jobLayout");
        return "partView";
    }
    /*
   任务编排数据映射
    */
    @RequestMapping("jobDataMapping")
    public String jobDataMapping(Model model, Integer versionId, String datasetIdStr) {
        try {
            model.addAttribute("versionId", versionId);
            model.addAttribute("datasetIdStr", datasetIdStr);
            model.addAttribute("contentPage", "/crawler/dataMapping");
            return "pageView";
        } catch (Exception ex) {
            model.addAttribute("contentPage", "/crawler/dataMapping");
            return "pageView";
        }
    }
    @RequestMapping("datasetDetail")
    public String datasetDetail(Model model, Integer schemeId, String schemeNm, String cacheDatasetId, String versionId) {
        model.addAttribute("contentPage", "/crawler/datasetDetail");
        model.addAttribute("schemeId", schemeId);
        model.addAttribute("versionId", versionId);
        model.addAttribute("schemeNm", schemeNm);
        model.addAttribute("cacheDatasetId", cacheDatasetId);
        return "pageView";
    }
    /**
     * 保存任务编排数据
     */
    @RequestMapping(value = "saveDateSet", method = RequestMethod.POST)
    @ApiOperation(value = "保存任务编排", produces = "application/json", notes = "保存任务编排")
    @ResponseBody
    public Result saveJobData(
            @ApiParam(name = "job", value = "任务编排信息", required = true)
            @RequestParam(value = "job") String jobInfo,
            @ApiParam(name = "rows", value = "当前行数", required = true)
            @RequestParam(value = "rows") Integer rows,
            @ApiParam(name = "page", value = "当前页数", required = true)
            @RequestParam(value = "page") Integer page) {
        try {
            crawlerService.saveJobData(jobInfo, rows, page);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("保存失败");
        }
        return Result.success("保存成功");
    }
    /**
     * 获取适配方案 数据集关系
     *
     * @param versionId 适配方案版本ID
     * @return
     */
    @RequestMapping("getSchemeDataSets")
    @ResponseBody
    public DetailModelResult getSchemeDataSets(
            @RequestParam(value = "versionId", required = true) Long versionId,
            @RequestParam(value = "name", required = false) String name
    ) {
        try {
            return crawlerService.getSchemeDataset(versionId, name);
        } catch (Exception e) {
            e.printStackTrace();
            return new DetailModelResult();
        }
    }
    /**
     * 保存适配方案 数据映射关系
     *
     * @param version
     * @param data    映射关系
     * @return
     */
    @RequestMapping("saveSchemeRelation")
    @ResponseBody
    public ActionResult addSchemeRelation(
            @RequestParam(value = "version", required = true) String version,
            @RequestParam(value = "data", required = true) String data
    ) {
        try {
            return crawlerService.saveDataSetRelation(version, data);
        } catch (Exception ex) {
            ex.printStackTrace();
            return new ActionResult();
        }
    }
    @RequestMapping(value = "getRelations", produces = "text/html; charset=utf-8")
    @ResponseBody
    public String getRelations(
            @RequestParam(value = "versionId", required = true) Long versionId,
            @RequestParam(value = "datasetIdStr", required = false) String datasetIdStr,
            @RequestParam(value = "lines", required = false) String lines,
            HttpServletResponse response) {
        try {
            return crawlerService.getRelations(versionId, datasetIdStr, lines);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @RequestMapping("setRelationsCache")
    @ResponseBody
    public Result setRelationsCache(
            @RequestParam(value = "versionId", required = true) Integer versionId,
            @RequestParam(value = "lines", required = false) String lines
    ) {
        try {
            crawlerService.setLinesCache(versionId, lines);
            return Result.success("缓存映射关系成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("缓存映射关系失败");
    }
    /**
     * 删除任务编排数据
     */
    @RequestMapping(value = "deleteDateSet", method = RequestMethod.POST)
    @ApiOperation(value = "删除任务编排", produces = "application/json", notes = "删除任务编排")
    @ResponseBody
    public Result deleteJobData(
            @ApiParam(name = "version", value = "版本号", required = true)
            @RequestParam(value = "version") String version) {
        if (version != null) {
            String message = crawlerService.deleteJobData(version);
            if (StringUtil.isEmpty(message)) {
                return Result.success("删除成功");
            } else {
                return Result.error(message);
            }
        } else {
            return Result.error("删除失败");
        }
    }
    /**
     * 分页显示任务编排数据
     */
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ApiOperation(value = "分页显示任务编排", produces = "application/json", notes = "分页显示任务编排")
    @ResponseBody
    public DetailModelResult listJobData(
            @ApiParam(name = "rows", value = "Limit the size of result set. Must be an integer")
            @RequestParam(value = "rows", required = false) Integer rows,
            @ApiParam(name = "page", value = "Start position of result set. Must be an integer")
            @RequestParam(value = "page", required = false) Integer page) throws Exception {
        return crawlerService.getDataSetResult(rows, page);
    }
    @RequestMapping(value = "getSchemeList", method = RequestMethod.POST)
    @ApiOperation(value = "获取适配方案-方案版本下拉框", produces = "application/json", notes = "获取适配方案-方案版本下拉框")
    @ResponseBody
    public DetailModelResult getSchemeList() {
        DetailModelResult result = adapterSchemeService.getAdapterSchemeResultModelList();
        return result;
    }
    /**
     * 获取任务编排保存数据集
     */
    @RequestMapping(value = "savedJobData", method = RequestMethod.POST)
    @ApiOperation(value = "获取保存的数据集", produces = "application/json", notes = "保存的数据集")
    @ResponseBody
    public DetailModelResult ListSavedJobData(
            @ApiParam(name = "version", value = "版本号", required = true)
            @RequestParam(value = "version") Long version
    ) {
        return crawlerService.getDataSetSavedResult(version);
    }
    /**
     * 获取任务编排保存适配方案-方案版本
     */
    @RequestMapping(value = "savedSchemeList", method = RequestMethod.POST)
    @ApiOperation(value = "获取保存的适配方案", produces = "application/json", notes = "保存的适配方案")
    @ResponseBody
    public DetailModelResult SavedSchemeList() {
        return crawlerService.getSchemeSavedResult();
    }
}

+ 40 - 0
src/main/java/com/yihu/hos/crawler/dao/CrawlerDatasetDao.java

@ -0,0 +1,40 @@
package com.yihu.hos.crawler.dao;
import com.yihu.hos.crawler.model.flow.CrawlerDataSetModel;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import java.math.BigInteger;
import java.util.List;
/**
 * Created by HZY on 2016/4/27.
 */
@Repository("CrawlerDatasetDao")
public class CrawlerDatasetDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "CrawlerDatasetDao";
    public List<CrawlerDataSetModel> getCrawlerDatasetList(Long versionId) throws Exception {
        String sql = "select * from crawler_dataset where scheme_version_id='" + versionId + "'";
        return super.queryListBySql(sql, CrawlerDataSetModel.class);
    }
    public void deleteCrawlerDatasetList(Long versionId) throws Exception {
        String sql = "delete from crawler_dataset where scheme_version_id= :scheme_version_id";
        Query query = getCurrentSession().createSQLQuery(sql);
        query.setLong("scheme_version_id", versionId);
        query.executeUpdate();
    }
    public Integer getTotalRows() throws Exception {
        String countSql = "SELECT COUNT(*) FROM (SELECT a.scheme_id, a.scheme_version_id, GROUP_CONCAT(a.dataset_id SEPARATOR ',') AS datasetId, GROUP_CONCAT(a.dataset_name SEPARATOR ',') AS datasetName" +
                "  FROM crawler_dataset a " +
                "  GROUP BY a.scheme_id, a.scheme_version_id ) b WHERE 1= 1";
        Query query = getCurrentSession().createSQLQuery(countSql);
        List<BigInteger> list = query.list();
        int count = list.get(0).intValue();
        return count;
    }
}

+ 40 - 0
src/main/java/com/yihu/hos/crawler/dao/CrawlerFlowDao.java

@ -0,0 +1,40 @@
package com.yihu.hos.crawler.dao;
import com.yihu.hos.crawler.model.flow.CrawlerFlowModel;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
 * Created by HZY on 2016/4/27.
 */
@Repository("CrawlerFlowDao")
public class CrawlerFlowDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "CrawlerFlowDao";
    public List<CrawlerFlowModel> getCrawlerFlowList(Long versionId) {
        String adapterVersionHql = "FROM CrawlerFlowModel where schemeVersionId= :schemeVersionId";
        Query query = getCurrentSession().createQuery(adapterVersionHql);
        query.setParameter("schemeVersionId", versionId);
        List<CrawlerFlowModel> modelList = query.list();
        return modelList;
    }
    public void deleteCrawlerFlowList(Long versionId)throws Exception  {
        String sql = "delete from crawler_flow where scheme_version_id='"+versionId+"'";
        super.execute(sql);
    }
    public List<CrawlerFlowModel> getCrawlerFlowList(Integer versionId,List<String> datasetCodes) {
        String adapterVersionHql = "FROM CrawlerFlowModel where schemeVersionId= :schemeVersionId and datasetCode in (:datasetCode) and inputDatasetCode in (:inputDatasetCode)";
        Query query = getCurrentSession().createQuery(adapterVersionHql);
        query.setParameter("schemeVersionId", versionId);
        query.setParameterList("datasetCode", datasetCodes);
        query.setParameterList("inputDatasetCode", datasetCodes);
        List<CrawlerFlowModel> modelList = query.list();
        return modelList;
    }
}

+ 32 - 0
src/main/java/com/yihu/hos/crawler/dao/CrawlerFlowHeadDao.java

@ -0,0 +1,32 @@
package com.yihu.hos.crawler.dao;
import com.yihu.hos.crawler.model.flow.CrawlerFlowHeadModel;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
 * Created by HZY on 2016/4/27.
 */
@Repository("CrawlerFlowHeadDao")
public class CrawlerFlowHeadDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "CrawlerFlowHeadDao";
    public void deleteCrawlerFlowHeadList(Long versionId) throws Exception {
        String sql = "delete from crawler_flow_head where scheme_version_id= :scheme_version_id";
        Query query = getCurrentSession().createSQLQuery(sql);
        query.setLong("scheme_version_id", versionId);
        query.executeUpdate();
    }
    public List<CrawlerFlowHeadModel> getCrawlerFlowHeadList(Long versionId) {
        String sql = "FROM CrawlerFlowHeadModel where schemeVersionId= :schemeVersionId";
        Query query = getCurrentSession().createQuery(sql);
        query.setParameter("schemeVersionId", versionId);
        List<CrawlerFlowHeadModel> modelList = query.list();
        return modelList;
    }
}

+ 95 - 0
src/main/java/com/yihu/hos/crawler/format/AdapterBase.java

@ -0,0 +1,95 @@
package com.yihu.hos.crawler.format;
import com.yihu.hos.standard.model.adapter.AdapterSchemeVersionModel;
import com.yihu.hos.standard.service.adapter.*;
import com.yihu.hos.standard.service.standard.StdDictEntryService;
import com.yihu.hos.standard.service.standard.StdDictService;
import com.yihu.hos.web.framework.model.standard.AdapterVersion;
import com.yihu.hos.web.framework.util.springutil.SpringBeanUtil;
import javax.annotation.Resource;
/**
 * 适配器基类,DAO缓存
 *
 * @created Created by Air on 2015/6/10.
 */
public class AdapterBase {
    @Resource(name = AdapterDatasetService.BEAN_ID)
    private AdapterDatasetService adapterDatasetService;
    @Resource(name = AdapterSchemeVersionService.BEAN_ID)
    private AdapterSchemeVersionService adapterSchemeVersionService;
    @Resource(name = AdapterMetadataService.BEAN_ID)
    private AdapterMetadataService adapterMetadataService;
    @Resource(name = AdapterDictEntryService.BEAN_ID)
    private AdapterDictEntryService adapterDictEntryService;
    @Resource(name = AdapterDictService.BEAN_ID)
    private AdapterDictService adapterDictService;
    @Resource(name =StdDictEntryService.BEAN_ID )
    private StdDictEntryService stdDictEntryService;
    @Resource(name =StdDictService.BEAN_ID )
    private StdDictService stdDictService;
    protected AdapterVersion adapterVersion;
    public AdapterVersion getAdapterVersion() {
        AdapterSchemeVersionModel adapterSchemeVersionModel = getAdapterSchemeVersionService().getEhrAdapterVersionLasted();
        if (adapterSchemeVersionModel == null) {
            adapterSchemeVersionModel=new AdapterSchemeVersionModel();
        }
        String version = adapterSchemeVersionModel.getVersion();
         adapterVersion = new AdapterVersion(version);
        return adapterVersion;
    }
    public AdapterDatasetService getAdapterDatasetService() {
        if (adapterDatasetService == null) {
            adapterDatasetService = SpringBeanUtil.getService(AdapterDatasetService.BEAN_ID);
        }
        return adapterDatasetService;
    }
    public AdapterSchemeVersionService getAdapterSchemeVersionService() {
        if (adapterSchemeVersionService == null) {
            adapterSchemeVersionService = SpringBeanUtil.getService(AdapterSchemeVersionService.BEAN_ID);
        }
        return adapterSchemeVersionService;
    }
    public AdapterMetadataService getAdapterMetadataService() {
        if (adapterMetadataService == null) {
            adapterMetadataService = SpringBeanUtil.getService(AdapterMetadataService.BEAN_ID);
        }
        return adapterMetadataService;
    }
    public AdapterDictService getAdapterDictService() {
        if (adapterDictService == null) {
            adapterDictService = SpringBeanUtil.getService(AdapterDictService.BEAN_ID);
        }
        return adapterDictService;
    }
    public AdapterDictEntryService getAdapterDictEntryService() {
        if (adapterDictEntryService == null) {
            adapterDictEntryService = SpringBeanUtil.getService(AdapterDictEntryService.BEAN_ID);
        }
        return adapterDictEntryService;
    }
    public StdDictEntryService getStdDictEntryService() {
        if (stdDictEntryService == null) {
            stdDictEntryService = SpringBeanUtil.getService(StdDictEntryService.BEAN_ID);
        }
        return stdDictEntryService;
    }
    public StdDictService getStdDictService() {
        if (stdDictService == null) {
            stdDictService = SpringBeanUtil.getService(StdDictService.BEAN_ID);
        }
        return stdDictService;
    }
}

+ 72 - 0
src/main/java/com/yihu/hos/crawler/format/AdapterScheme.java

@ -0,0 +1,72 @@
package com.yihu.hos.crawler.format;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.standard.model.adapter.AdapterDatasetModel;
import com.yihu.hos.standard.model.adapter.AdapterMetadataModel;
import com.yihu.hos.standard.model.adapter.AdapterSchemeVersionModel;
import com.yihu.hos.standard.service.adapter.AdapterDatasetService;
import com.yihu.hos.web.framework.model.standard.AdapterVersion;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 适配方案
 * 一个适配方案可能有一到多个机构要采集数据
 *
 * @created Created by Air on 2015/6/3.
 */
public class AdapterScheme  extends AdapterBase{
    @Resource(name = AdapterDatasetService.BEAN_ID)
    private AdapterDatasetService adapterDatasetService;
    private HashMap<String, List<AdapterMetadataModel>> adapterMetaDataMap;
    public AdapterScheme() {
    }
    public synchronized HashMap<String, List<AdapterMetadataModel>> getAdapterMetaDataMap() {
        if (adapterMetaDataMap ==null){
            AdapterSchemeVersionModel adapterSchemeVersionModel = getAdapterSchemeVersionService().getEhrAdapterVersionLasted();
            if (adapterSchemeVersionModel == null) {
                adapterSchemeVersionModel=new AdapterSchemeVersionModel();
            }
            String version = adapterSchemeVersionModel.getVersion();
            AdapterVersion adapterVersion = new AdapterVersion(version);
            adapterMetaDataMap =new HashMap<>();
            Map<String, String> condition = new HashMap<>();
            condition.put("column", "adapter_dataset_code");
            String conditionStr ="";
            ObjectMapper mapper = new ObjectMapper();
            try {
                conditionStr = mapper.writeValueAsString(condition);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            List<AdapterDatasetModel> adapterDataSets = adapterDatasetService.getAdapterDatasetNotNullList(adapterVersion, conditionStr);
            for (AdapterDatasetModel adapterDataSet:adapterDataSets){
                List<AdapterMetadataModel> adapterMetaDataTList = getAdapterMetadataService().getAdapterMetadataByDataset(version, adapterDataSet.getId());
                if (adapterMetaDataTList!=null && adapterMetaDataTList.size()>0){
                    adapterMetaDataMap.put(adapterDataSet.getStdDatasetCode(), adapterMetaDataTList);
                }
            }
        }
        return adapterMetaDataMap;
    }
    public List<AdapterMetadataModel> getAdapterMetaDatas(String dataSetCode){
        if (dataSetCode==null){
            return new ArrayList<>();
        }
        return getAdapterMetaDataMap().get(dataSetCode);
    }
}

+ 108 - 0
src/main/java/com/yihu/hos/crawler/model/adapter/AdapterDataSet.java

@ -0,0 +1,108 @@
package com.yihu.hos.crawler.model.adapter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.core.datatype.CollectionUtil;
import com.yihu.hos.crawler.model.patient.PatientIdentity;
import com.yihu.hos.standard.model.adapter.AdapterDatasetModel;
import com.yihu.hos.standard.model.adapter.AdapterDictEntryModel;
import com.yihu.hos.standard.model.adapter.AdapterMetadataModel;
import com.yihu.hos.standard.service.adapter.AdapterMetadataService;
import com.yihu.hos.web.framework.model.standard.AdapterVersion;
import com.yihu.hos.web.framework.util.springutil.SpringBeanUtil;
import java.util.*;
/**
 * @author Air
 * @version 1.0
 * @created 2015.08.11 11:29
 */
public class AdapterDataSet {
    private List<AdapterMetaData> adapterMetaDataList;
    private AdapterDatasetModel adapterDatasetModel;
    private Map<String, AdapterMetaData> adapterMetaDataMap;
    private String eventNoCode;
    private AdapterVersion adapterVersion;
    public AdapterDataSet(AdapterDatasetModel adapterDatasetModel, AdapterVersion adapterVersion, Map<Integer, List<AdapterDictEntryModel>> entryMap) {
        this.adapterDatasetModel = adapterDatasetModel;
        this.adapterVersion = adapterVersion;
        prepareData(entryMap);
    }
    public AdapterDatasetModel getAdapterDataSetT() {
        return adapterDatasetModel;
    }
    public void prepareData(Map<Integer, List<AdapterDictEntryModel>> entryMap) {
        try {
            adapterMetaDataList = new ArrayList<>();
            adapterMetaDataMap = new HashMap<>();
            Map<String, Object> condition = new HashMap<>();
            condition.put("column", "adapter_metadata_code");
            ObjectMapper objectMapper = new ObjectMapper();
            AdapterMetadataService metadataService = SpringBeanUtil.getService(AdapterMetadataService.BEAN_ID);
            List<AdapterMetadataModel> adapterMetaDataModelList = metadataService.getAdapterMetadataNotNullList(adapterVersion, adapterDatasetModel.getStdDatasetId(),objectMapper.writeValueAsString(condition));
            List<Long> stdMetaDataIdList = new ArrayList<>();
            if (!CollectionUtil.isEmpty(adapterMetaDataModelList)) {
                for (AdapterMetadataModel adapterMetadataModel : adapterMetaDataModelList) {
                    stdMetaDataIdList.add(adapterMetadataModel.getStdMetadataId());
                }
                for (AdapterMetadataModel adapterMetadataModel : adapterMetaDataModelList) {
                    AdapterMetaData adapterMetaData = new AdapterMetaData(adapterMetadataModel, adapterVersion, entryMap);
                    adapterMetaDataList.add(adapterMetaData);
                    adapterMetaDataMap.put(adapterMetadataModel.getStdMetadataCode().toUpperCase(), adapterMetaData);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public Map<String, AdapterMetaData> getAdapterMetaDataMap() {
        return adapterMetaDataMap;
    }
    public List<AdapterMetaData> getAdapterMetaDataList() {
        return adapterMetaDataList;
    }
    public boolean isHavePatientID() {
        return findPatientIdentity(PatientIdentity.getPatientIDCode());
    }
    public boolean isHaveEventNo() {
        Set<String> eventNoSet = PatientIdentity.getEventNoSet();
        for (String eventNo : eventNoSet) {
            if (findPatientIdentity(eventNo)) {
                eventNoCode = eventNo;
                return true;
            }
        }
        return false;
    }
    public boolean isHaveLocalCardNo() {
        return findPatientIdentity(PatientIdentity.getLocalCardNoCode());
    }
    public boolean isHaveIdCard() {
        return findPatientIdentity(PatientIdentity.getIdCardCode());
    }
    public boolean findPatientIdentity(String code) {
        if (getAdapterMetaDataMap().get(code) == null) {
            return false;
        }
        return true;
    }
    public String getEventNoCode() {
        return eventNoCode;
    }
}

+ 46 - 0
src/main/java/com/yihu/hos/crawler/model/adapter/AdapterDict.java

@ -0,0 +1,46 @@
package com.yihu.hos.crawler.model.adapter;
import com.yihu.hos.crawler.format.AdapterBase;
import com.yihu.hos.standard.model.adapter.AdapterDictEntryModel;
import com.yihu.hos.standard.model.adapter.AdapterDictModel;
import com.yihu.hos.web.framework.model.standard.AdapterVersion;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author Air
 * @version 1.0
 * @created 2015.08.11 11:31
 */
public class AdapterDict extends AdapterBase {
    private AdapterDictModel adapterDictModel;
    private AdapterDictModel adapterDictT;
    private Map<String, String> adapterValueToCodeMap;
    private Map<String, String> adapterCodeToCodeMap;
    public AdapterDict(AdapterDictModel adapterDictModel, AdapterVersion adapterVersion, Map<Integer, List<AdapterDictEntryModel>> entryMap) {
        this.adapterDictModel = adapterDictModel;
        this.adapterDictT = adapterDictModel;
        prepareData(entryMap);
    }
    public void prepareData(Map<Integer, List<AdapterDictEntryModel>> entryMap) {
        adapterValueToCodeMap = new HashMap<>();
        adapterCodeToCodeMap = new HashMap<>();
        List<AdapterDictEntryModel> adapterDictEntryModelList = entryMap.get(adapterDictModel.getStdDictId());
        for (AdapterDictEntryModel adapterDictEntryModel : adapterDictEntryModelList) {
            adapterValueToCodeMap.put(adapterDictEntryModel.getStdEntryValue(), adapterDictEntryModel.getAdapterEntryCode());
            adapterCodeToCodeMap.put(adapterDictEntryModel.getStdEntryCode(), adapterDictEntryModel.getAdapterEntryCode());
        }
    }
    public Map<String, String> getAdapterValueToCodeMap() {
        return adapterValueToCodeMap;
    }
    public Map<String, String> getAdapterCodeToCodeMap() {
        return adapterCodeToCodeMap;
    }
}

+ 13 - 0
src/main/java/com/yihu/hos/crawler/model/adapter/AdapterDictEntry.java

@ -0,0 +1,13 @@
package com.yihu.hos.crawler.model.adapter;
import com.yihu.hos.standard.model.adapter.AdapterDictEntryModel;
public class AdapterDictEntry {
    private AdapterDictEntryModel adapterDictEntryModel;
    private String version;
    public AdapterDictEntry(AdapterDictEntryModel adapterDictEntryModel, String version) {
        this.adapterDictEntryModel = adapterDictEntryModel;
        this.version = version;
    }
}

+ 62 - 0
src/main/java/com/yihu/hos/crawler/model/adapter/AdapterMetaData.java

@ -0,0 +1,62 @@
package com.yihu.hos.crawler.model.adapter;
import com.yihu.hos.core.datatype.NumberUtil;
import com.yihu.hos.crawler.model.transform.DictDataType;
import com.yihu.hos.standard.model.adapter.AdapterDictEntryModel;
import com.yihu.hos.standard.model.adapter.AdapterDictModel;
import com.yihu.hos.standard.model.adapter.AdapterMetadataModel;
import com.yihu.hos.standard.service.adapter.AdapterDictService;
import com.yihu.hos.web.framework.model.standard.AdapterVersion;
import com.yihu.hos.web.framework.util.springutil.SpringBeanUtil;
import java.util.List;
import java.util.Map;
/**
 * @author Air
 * @version 1.0
 * @created 2015.08.11 11:31
 */
public class AdapterMetaData {
    private AdapterMetadataModel adapterMetadataModel;
    private AdapterDict adapterDict;
    private AdapterVersion adapterVersion;
    public AdapterMetaData(AdapterMetadataModel adapterMetadataModel, AdapterVersion adapterVersion, Map<Integer, List<AdapterDictEntryModel>> entryMap) {
        this.adapterMetadataModel = adapterMetadataModel;
        this.adapterVersion = adapterVersion;
        prepareData(entryMap);
    }
    public AdapterMetadataModel getAdapterMetadataModel() {
        return adapterMetadataModel;
    }
    public void prepareData(Map<Integer, List<AdapterDictEntryModel>> entryMap) {
        long stdDictId = adapterMetadataModel.getStdDictId();
        if (!NumberUtil.isZero((int)stdDictId)) {
            AdapterDictService adapterDictService = SpringBeanUtil.getService(AdapterDictService.BEAN_ID);
            /**
             * 默认适配字典的id与数据元的标准id一致
             */
            AdapterDictModel adapterDictModel = (AdapterDictModel) adapterDictService.get(AdapterDictModel.class, adapterVersion.getDictTableName(), adapterMetadataModel.getStdDictId());
            if (adapterDictModel != null) {
                adapterDict = new AdapterDict(adapterDictModel, adapterVersion, entryMap);
            }
        }
    }
    public AdapterDict getAdapterDict() {
        return adapterDict;
    }
    public DictDataType getAdapterDictDataType() {
        Integer orgDictDataType = adapterMetadataModel.getAdapterDataType();
        if (orgDictDataType == null){
            return DictDataType.VALUE;
        }
        return DictDataType.values()[orgDictDataType];
    }
}

+ 63 - 0
src/main/java/com/yihu/hos/crawler/model/flow/CrawlerDataSetModel.java

@ -0,0 +1,63 @@
package com.yihu.hos.crawler.model.flow;
import com.yihu.hos.web.framework.model.Result;
import java.io.Serializable;
/**
 * 任务编排-数据集关系
 *
 * @created HZY 2016/4/27.
 */
public class CrawlerDataSetModel extends Result implements Serializable {
    private Long schemeId;
    private Long schemeVersionId;
    private Long datasetId;
    private String datasetCode;
    private String datasetName;
    public Long getSchemeId() {
        return schemeId;
    }
    public void setSchemeId(Long schemeId) {
        this.schemeId = schemeId;
    }
    public Long getSchemeVersionId() {
        return schemeVersionId;
    }
    public void setSchemeVersionId(Long schemeVersionId) {
        this.schemeVersionId = schemeVersionId;
    }
    public Long getDatasetId() {
        return datasetId;
    }
    public void setDatasetId(Long datasetId) {
        this.datasetId = datasetId;
    }
    public String getDatasetCode() {
        return datasetCode;
    }
    public void setDatasetCode(String datasetCode) {
        this.datasetCode = datasetCode;
    }
    public String getDatasetName() {
        return datasetName;
    }
    public void setDatasetName(String datasetName) {
        this.datasetName = datasetName;
    }
}

+ 53 - 0
src/main/java/com/yihu/hos/crawler/model/flow/CrawlerFlowHeadModel.java

@ -0,0 +1,53 @@
package com.yihu.hos.crawler.model.flow;
import com.yihu.hos.web.framework.model.Result;
import java.io.Serializable;
/**
 * 标准基本信息
 *
 * @created Airhead 2015/12/23.
 */
public class CrawlerFlowHeadModel extends Result implements Serializable {
    private Long schemeVersionId;
    private String datasetCode;
    private String metadataCode;
    private String identityCode;
    public Long getSchemeVersionId() {
        return schemeVersionId;
    }
    public void setSchemeVersionId(Long schemeVersionId) {
        this.schemeVersionId = schemeVersionId;
    }
    public String getDatasetCode() {
        return datasetCode;
    }
    public void setDatasetCode(String datasetCode) {
        this.datasetCode = datasetCode;
    }
    public String getMetadataCode() {
        return metadataCode;
    }
    public void setMetadataCode(String metadataCode) {
        this.metadataCode = metadataCode;
    }
    public String getIdentityCode() {
        return identityCode;
    }
    public void setIdentityCode(String identityCode) {
        this.identityCode = identityCode;
    }
}

+ 93 - 0
src/main/java/com/yihu/hos/crawler/model/flow/CrawlerFlowModel.java

@ -0,0 +1,93 @@
package com.yihu.hos.crawler.model.flow;
import com.yihu.hos.web.framework.model.Result;
import java.io.Serializable;
/**
 * 标准基本信息
 *
 * @created Airhead 2015/12/23.
 */
public class CrawlerFlowModel extends Result implements Serializable {
    private Integer id;
    private Long schemeVersionId;
    private String datasetCode;
    private String metadataCode;
    private String inputDatasetCode;
    private String inputMetadataCode;
    private String inputMetadataCode2;
    private String inputDefaultValue;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Long getSchemeVersionId() {
        return schemeVersionId;
    }
    public void setSchemeVersionId(Long schemeVersionId) {
        this.schemeVersionId = schemeVersionId;
    }
    public String getDatasetCode() {
        return datasetCode;
    }
    public void setDatasetCode(String datasetCode) {
        this.datasetCode = datasetCode;
    }
    public String getMetadataCode() {
        return metadataCode;
    }
    public void setMetadataCode(String metadataCode) {
        this.metadataCode = metadataCode;
    }
    public String getInputDatasetCode() {
        return inputDatasetCode;
    }
    public void setInputDatasetCode(String inputDatasetCode) {
        this.inputDatasetCode = inputDatasetCode;
    }
    public String getInputMetadataCode() {
        return inputMetadataCode;
    }
    public void setInputMetadataCode(String inputMetadataCode) {
        this.inputMetadataCode = inputMetadataCode;
    }
    public String getInputMetadataCode2() {
        return inputMetadataCode2;
    }
    public void setInputMetadataCode2(String inputMetadataCode2) {
        this.inputMetadataCode2 = inputMetadataCode2;
    }
    public String getInputDefaultValue() {
        return inputDefaultValue;
    }
    public void setInputDefaultValue(String inputDefaultValue) {
        this.inputDefaultValue = inputDefaultValue;
    }
}

+ 21 - 0
src/main/java/com/yihu/hos/crawler/model/flow/resultModel/CrawlerDatasetResultDetailModel.java

@ -0,0 +1,21 @@
package com.yihu.hos.crawler.model.flow.resultModel;
import com.yihu.hos.crawler.model.flow.CrawlerDataSetModel;
/**
 * 任务编排数据集关联
 */
public class CrawlerDatasetResultDetailModel extends CrawlerDataSetModel implements java.io.Serializable {
	private String checked;
	public String getChecked() {
		return checked;
	}
	public void setChecked(String checked) {
		this.checked = checked;
	}
}

+ 21 - 0
src/main/java/com/yihu/hos/crawler/model/flow/resultModel/CrawlerDatasetResultModel.java

@ -0,0 +1,21 @@
package com.yihu.hos.crawler.model.flow.resultModel;
import com.yihu.hos.standard.model.adapter.AdapterSchemeVersionModel;
import java.io.Serializable;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/4/27.
 */
public class CrawlerDatasetResultModel extends AdapterSchemeVersionModel implements Serializable {
    private String dataSets;
    public String getDataSets() {
        return dataSets;
    }
    public void setDataSets(String dataSets) {
        this.dataSets = dataSets;
    }
}

+ 30 - 0
src/main/java/com/yihu/hos/crawler/model/flow/resultModel/FlowEntrance.java

@ -0,0 +1,30 @@
package com.yihu.hos.crawler.model.flow.resultModel;
import java.io.Serializable;
/**
 *  编排入口
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/4/27.
 */
public class FlowEntrance implements Serializable {
    private String dataSet;
    private String meta;
    public String getDataSet() {
        return dataSet;
    }
    public void setDataSet(String dataSet) {
        this.dataSet = dataSet;
    }
    public String getMeta() {
        return meta;
    }
    public void setMeta(String meta) {
        this.meta = meta;
    }
}

+ 48 - 0
src/main/java/com/yihu/hos/crawler/model/flow/resultModel/FlowLines.java

@ -0,0 +1,48 @@
package com.yihu.hos.crawler.model.flow.resultModel;
import java.io.Serializable;
/**
 *  编排映射关系
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/4/27.
 */
public class FlowLines implements Serializable {
    private String from;
    private String to;
    private String fromPort;
    private String toPort;
    public String getFrom() {
        return from;
    }
    public void setFrom(String from) {
        this.from = from;
    }
    public String getTo() {
        return to;
    }
    public void setTo(String to) {
        this.to = to;
    }
    public String getFromPort() {
        return fromPort;
    }
    public void setFromPort(String fromPort) {
        this.fromPort = fromPort;
    }
    public String getToPort() {
        return toPort;
    }
    public void setToPort(String toPort) {
        this.toPort = toPort;
    }
}

+ 41 - 0
src/main/java/com/yihu/hos/crawler/model/flow/resultModel/FlowMapping.java

@ -0,0 +1,41 @@
package com.yihu.hos.crawler.model.flow.resultModel;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
/**
 * 适配方案映射数据类
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/4/28.
 */
public class FlowMapping implements Serializable {
    private List<FlowEntrance> entrances;
    private List<FlowLines> lines;
    private Integer schemeVersionId;
    public List<FlowEntrance> getEntrances() {
        return entrances;
    }
    public void setEntrances(List<FlowEntrance> entrances) {
        this.entrances = entrances;
    }
    public List<FlowLines> getLines() {
        return lines;
    }
    public void setLines(List<FlowLines> lines) {
        this.lines = lines;
    }
    public Integer getSchemeVersionId() {
        return schemeVersionId;
    }
    public void setSchemeVersionId(Integer schemeVersionId) {
        this.schemeVersionId = schemeVersionId;
    }
}

+ 47 - 0
src/main/java/com/yihu/hos/crawler/model/flow/resultModel/MappingDataset.java

@ -0,0 +1,47 @@
package com.yihu.hos.crawler.model.flow.resultModel;
import java.util.List;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/4/29.
 */
public class MappingDataset {
    private Long id;
    private String code;
    private String name;
    private List<MappingMetadata> data;
    public List<MappingMetadata> getData() {
        return data;
    }
    public void setData(List<MappingMetadata> data) {
        this.data = data;
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

+ 36 - 0
src/main/java/com/yihu/hos/crawler/model/flow/resultModel/MappingMetadata.java

@ -0,0 +1,36 @@
package com.yihu.hos.crawler.model.flow.resultModel;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/4/29.
 */
public class MappingMetadata {
    private Long id;
    private String code;
    private String name;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

+ 103 - 0
src/main/java/com/yihu/hos/crawler/model/patient/Patient.java

@ -0,0 +1,103 @@
package com.yihu.hos.crawler.model.patient;
/**
 * @author Air
 * @version 1.0
 * @created 2015.08.14 10:12
 */
public class Patient {
    private String patientId;
    private String eventNo;
    private String localCardNo;
    private String idCard;
    private String orgCode;
    private String latestTime;
    private String referenceTime;
    private String reUploadFlg;
    private String jobTimeStamp;
    private String failType; //采集失败类型
    public Patient() {
    }
    public String getPatientId() {
        return patientId;
    }
    public void setPatientId(String patientId) {
        this.patientId = patientId;
    }
    public String getEventNo() {
        return eventNo;
    }
    public void setEventNo(String eventNo) {
        this.eventNo = eventNo;
    }
    public String getLocalCardNo() {
        return localCardNo;
    }
    public void setLocalCardNo(String localCardNo) {
        this.localCardNo = localCardNo;
    }
    public String getIdCard() {
        return idCard;
    }
    public void setIdCard(String idCard) {
        this.idCard = idCard;
    }
    public String getOrgCode() {
        return orgCode;
    }
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    public String getLatestTime() {
        return latestTime;
    }
    public void setLatestTime(String latestTime) {
        this.latestTime = latestTime;
    }
    public String getReferenceTime() {
        return referenceTime;
    }
    public void setReferenceTime(String referenceTime) {
        this.referenceTime = referenceTime;
    }
    public String getJobTimeStamp() {
        return jobTimeStamp;
    }
    public void setJobTimeStamp(String jobTimeStamp) {
        this.jobTimeStamp = jobTimeStamp;
    }
    public String getReUploadFlg() {
        return reUploadFlg;
    }
    public void setReUploadFlg(String reUploadFlg) {
        this.reUploadFlg = reUploadFlg;
    }
    public String getFailType() {
        return failType;
    }
    public void setFailType(String failType) {
        this.failType = failType;
    }
}

+ 59 - 0
src/main/java/com/yihu/hos/crawler/model/patient/PatientIdentity.java

@ -0,0 +1,59 @@
package com.yihu.hos.crawler.model.patient;
import java.util.HashSet;
import java.util.Set;
/**
 * 病人身份标识
 * 病人ID, 事件号(门诊号,住院号等),卡号,身份证号
 * 目前使用的是病人ID和事件号
 *
 * @author Air
 * @version 1.0
 * @created 2015.06.16 16:29
 */
public class PatientIdentity {
    public static final String PATIENT_ID = "PATIENT_ID";
    public static final String LOCAL_CARD_NO = "CARD_NO";
    public static final String ID_CARD = "DE02_01_030_00";
    public static Set<String> EVENT_NO_SET = new HashSet<>();
    private String eventNoCode;
    private String refTimeCode;
    public PatientIdentity(String eventNoCode, String refTimeCode) {
        this.eventNoCode = eventNoCode;
        this.refTimeCode = refTimeCode;
        EVENT_NO_SET.add(eventNoCode);
    }
    public static String getPatientIDCode() {
        return PATIENT_ID;
    }
    public static String getLocalCardNoCode() {
        return LOCAL_CARD_NO;
    }
    public static String getIdCardCode() {
        return ID_CARD;
    }
    public static Set<String> getEventNoSet() {
        return EVENT_NO_SET;
    }
    public static void addEventNoCode(String eventNoCode) {
        EVENT_NO_SET.add(eventNoCode);
    }
    public String getEventNoCode() {
        return eventNoCode;
    }
    public String getRefTimeCode() {
        return refTimeCode;
    }
}

+ 110 - 0
src/main/java/com/yihu/hos/crawler/model/patient/PatientIndex.java

@ -0,0 +1,110 @@
package com.yihu.hos.crawler.model.patient;
/**
 * 病人摘要标识
 *
 *
 * @author HXY
 * @version 1.0
 * @created 2016.03.01 13:50
 */
public class PatientIndex {
    public static final String PATIENT_ID = "PATIENT_ID";
    private String eventNoCode;
    private String refTimeCode;
//    private String organization;
    private String officeCode;
    private String officeName;
    private String leaveTime;
    private String diagDataSet;
    private String diagCode;
    private String diagName;
    private String diagType;
    public PatientIndex() {
    }
    public String getDiagType() {
        return diagType;
    }
    public void setDiagType(String diagType) {
        this.diagType = diagType;
    }
    public static String getPatientId() {
        return PATIENT_ID;
    }
    public String getEventNoCode() {
        return eventNoCode;
    }
    public void setEventNoCode(String eventNoCode) {
        this.eventNoCode = eventNoCode;
    }
    public String getRefTimeCode() {
        return refTimeCode;
    }
    public void setRefTimeCode(String refTimeCode) {
        this.refTimeCode = refTimeCode;
    }
//    public String getOrganization() {
//        return organization;
//    }
//
//    public void setOrganization(String organization) {
//        this.organization = organization;
//    }
    public String getOfficeCode() {
        return officeCode;
    }
    public void setOfficeCode(String officeCode) {
        this.officeCode = officeCode;
    }
    public String getOfficeName() {
        return officeName;
    }
    public void setOfficeName(String officeName) {
        this.officeName = officeName;
    }
    public String getLeaveTime() {
        return leaveTime;
    }
    public void setLeaveTime(String leaveTime) {
        this.leaveTime = leaveTime;
    }
    public String getDiagDataSet() {
        return diagDataSet;
    }
    public void setDiagDataSet(String diagDataSet) {
        this.diagDataSet = diagDataSet;
    }
    public String getDiagCode() {
        return diagCode;
    }
    public void setDiagCode(String diagCode) {
        this.diagCode = diagCode;
    }
    public String getDiagName() {
        return diagName;
    }
    public void setDiagName(String diagName) {
        this.diagName = diagName;
    }
}

+ 41 - 0
src/main/java/com/yihu/hos/crawler/model/standard/StdDict.java

@ -0,0 +1,41 @@
package com.yihu.hos.crawler.model.standard;
import com.yihu.hos.crawler.format.AdapterBase;
import com.yihu.hos.standard.model.standard.StdDictionaryEntryModel;
import com.yihu.hos.standard.model.standard.StdDictionaryModel;
/**
 * @author Air
 * @version 1.0
 * @created 2015.08.11 15:25
 */
public class StdDict extends AdapterBase {
    private StdDictionaryModel stdDictT;
    public StdDict(StdDictionaryModel stdDictT) {
        this.stdDictT = stdDictT;
    }
    public StdDictionaryModel getStdDictT() {
        return stdDictT;
    }
    public String toValue(String code) {
        StdDictionaryEntryModel entryModel=getStdDictEntryService().getStEntryValueByCode(adapterVersion.getVersion(), stdDictT.getId(), code);
        if (entryModel==null){
            return null;
        }else {
            return entryModel.getValue();
        }
    }
    public String toCode(String value) {
        StdDictionaryEntryModel entryModel=getStdDictEntryService().getStEntryValueByCode(adapterVersion.getVersion(), stdDictT.getId(), value);
        if (entryModel==null){
            return null;
        }else {
            return entryModel.getCode();
        }
    }
}

+ 37 - 0
src/main/java/com/yihu/hos/crawler/model/standard/StdMetaData.java

@ -0,0 +1,37 @@
package com.yihu.hos.crawler.model.standard;
import com.yihu.hos.crawler.format.AdapterBase;
import com.yihu.hos.crawler.model.transform.DictDataType;
import com.yihu.hos.standard.model.standard.StdMetaDataModel;
import static com.yihu.hos.crawler.model.transform.MetaDataType.S2;
import static com.yihu.hos.crawler.model.transform.MetaDataType.S3;
/**
 * @author Air
 * @version 1.0
 * @created 2015.08.11 15:25
 */
public class StdMetaData extends AdapterBase {
    private StdMetaDataModel stdMetaDataT;
    public StdMetaData(StdMetaDataModel stdMetaDataT) {
        this.stdMetaDataT = stdMetaDataT;
    }
    public StdMetaDataModel getStdMetaDataT() {
        return stdMetaDataT;
    }
    public DictDataType getDictDataType() {
        Long dict = stdMetaDataT.getDictId();
        String type = stdMetaDataT.getType();
        int dictValueType;
        if (dict!=null && (type.equals(S2.name()) || type.equals(S3.name()))) {
            dictValueType = DictDataType.CODE.ordinal();
        } else {
            dictValueType = DictDataType.VALUE.ordinal();
        }
        return DictDataType.values()[dictValueType];
    }
}

+ 9 - 0
src/main/java/com/yihu/hos/crawler/model/transform/DictDataType.java

@ -0,0 +1,9 @@
package com.yihu.hos.crawler.model.transform;
/**
 * Created by Administrator on 2015/9/16.
 */
public enum DictDataType {
    VALUE, //值
    CODE //编码
}

+ 65 - 0
src/main/java/com/yihu/hos/crawler/model/transform/EhrCondition.java

@ -0,0 +1,65 @@
package com.yihu.hos.crawler.model.transform;
/**
 * 集成平台采集条件基类
 * Created by HZY on 2016/2/25.
 */
public class EhrCondition {
    private String andOr;
    private String field;
    private String condition;
    private String value;
    public EhrCondition(String condition, String field, String value){
        this.andOr=" AND ";
        this.field=field;
        this.condition=condition;
        this.value=value;
    }
    public void andQuery(String condition,String field,String value){
        this.andOr=" AND ";
        this.field=field;
        this.condition=condition;
        this.value=value;
    }
    public void orQuery(String condition,String field,String value){
        this.andOr=" OR ";
        this.field=field;
        this.condition=condition;
        this.value=value;
    }
    public String getAndOr() {
        return andOr;
    }
    public void setAndOr(String andOr) {
        this.andOr = andOr;
    }
    public String getField() {
        return field;
    }
    public void setField(String field) {
        this.field = field;
    }
    public String getCondition() {
        return condition;
    }
    public void setCondition(String condition) {
        this.condition = condition;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
}

+ 15 - 0
src/main/java/com/yihu/hos/crawler/model/transform/IVerifier.java

@ -0,0 +1,15 @@
package com.yihu.hos.crawler.model.transform;
/**
 * @author Airhead
 * @version 1.0
 * @created 22-5-2015 11:24:26
 */
public interface IVerifier {
    /**
     */
    boolean check();
    String getErrorInfo();
}

+ 12 - 0
src/main/java/com/yihu/hos/crawler/model/transform/LogicValues.java

@ -0,0 +1,12 @@
package com.yihu.hos.crawler.model.transform;
/**
 * Created by HZY on 2016/1/29.
 */
public class LogicValues {
    public static final String LOGIC_OK = "ok";
    public static final String LOGIC_NO = "no";
    public static final String LOGIC_TRUE = "true";
    public static final String LOGIC_FALSE = "false";
}

+ 45 - 0
src/main/java/com/yihu/hos/crawler/model/transform/MetaDataType.java

@ -0,0 +1,45 @@
package com.yihu.hos.crawler.model.transform;
/**
 * 数据元类型
 *
 * @created Created by Air on 2015/6/9.
 */
public enum MetaDataType {
    /**
     * 字符,不可枚举
     */
    S1,
    /**
     * 字符,枚举<=3个
     */
    S2,
    /**
     * 字符,代码表
     */
    S3,
    /**
     * 布尔,0(False),1(True)
     */
    L,
    /**
     * 数值,
     */
    N,
    /**
     * 日期
     */
    D,
    /**
     * 时间日期
     */
    DT,
    /**
     * 时间
     */
    T,
    /**
     * 二进制
     */
    BY
}

+ 37 - 0
src/main/java/com/yihu/hos/crawler/model/transform/MetaDataVerify.java

@ -0,0 +1,37 @@
package com.yihu.hos.crawler.model.transform;
import com.yihu.hos.crawler.model.standard.StdMetaData;
/**
 * @author Airhead
 * @version 1.0
 * @created 22-5-2015 11:24:25
 */
public class MetaDataVerify implements IVerifier {
    private StdMetaData stdMetaData;
    private String value;
    private String errorInfo;
    public MetaDataVerify(StdMetaData stdMetaData, String value) {
        this.stdMetaData = stdMetaData;
        this.value = value;
    }
    public void finalize() throws Throwable {
    }
    /**
     * 目前不做任何数据校验
     * 必要时根据StdMetaData的type, format内容做校验
     */
    public boolean check() {
        return true;
    }
    @Override
    public String getErrorInfo() {
        return errorInfo;
    }
}//end MetaDataVerify

+ 21 - 0
src/main/java/com/yihu/hos/crawler/model/transform/TransformType.java

@ -0,0 +1,21 @@
package com.yihu.hos.crawler.model.transform;
/**
 * @created  Air on 2015/6/8.
 */
public enum TransformType {
    /**
     * 数据集
     */
    DATA_SET_JSON,
    DATA_SET_XML,
    /**
     * CDA
     */
    CDA_JSON,
    CDA_XML,
    /**
     * 非结构化
     */
    DOCUMENT,
}

+ 515 - 0
src/main/java/com/yihu/hos/crawler/service/CrawlerService.java

@ -0,0 +1,515 @@
package com.yihu.hos.crawler.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.crawler.dao.CrawlerDatasetDao;
import com.yihu.hos.crawler.dao.CrawlerFlowDao;
import com.yihu.hos.crawler.dao.CrawlerFlowHeadDao;
import com.yihu.hos.crawler.model.flow.CrawlerDataSetModel;
import com.yihu.hos.crawler.model.flow.CrawlerFlowHeadModel;
import com.yihu.hos.crawler.model.flow.CrawlerFlowModel;
import com.yihu.hos.crawler.model.flow.resultModel.*;
import com.yihu.hos.datacollect.model.DtoJobDataset;
import com.yihu.hos.standard.model.adapter.AdapterDatasetModel;
import com.yihu.hos.standard.model.adapter.AdapterMetadataModel;
import com.yihu.hos.standard.model.adapter.AdapterSchemeVersionModel;
import com.yihu.hos.standard.model.adapter.resultModel.AdapterSchemeResultModel;
import com.yihu.hos.standard.model.adapter.resultModel.AdapterSchemeVersionResultDetailModel;
import com.yihu.hos.standard.service.adapter.AdapterDatasetService;
import com.yihu.hos.standard.service.adapter.AdapterMetadataService;
import com.yihu.hos.standard.service.adapter.AdapterSchemeService;
import com.yihu.hos.standard.service.adapter.AdapterSchemeVersionService;
import com.yihu.hos.web.framework.constant.SqlConstants;
import com.yihu.hos.web.framework.model.ActionResult;
import com.yihu.hos.web.framework.model.DetailModelResult;
import com.yihu.hos.web.framework.model.standard.AdapterVersion;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
@Transactional
@Service("CrawlerService")
public class CrawlerService {
    public static final String BEAN_ID = "CrawlerService";
    @Resource(name = AdapterSchemeVersionService.BEAN_ID)
    private AdapterSchemeVersionService adapterSchemeVersionService;
    @Resource(name = AdapterDatasetService.BEAN_ID)
    private AdapterDatasetService adapterDatasetService;
    @Resource(name = CrawlerDatasetDao.BEAN_ID)
    private CrawlerDatasetDao crawlerDatasetDao;
    @Resource(name = CrawlerFlowDao.BEAN_ID)
    private CrawlerFlowDao crawlerFlowDao;
    @Resource(name = CrawlerFlowHeadDao.BEAN_ID)
    private CrawlerFlowHeadDao crawlerFlowHeadDao;
    @Resource(name = AdapterMetadataService.BEAN_ID)
    private AdapterMetadataService adapterMetadataService;
    private static Map<Integer, List<FlowLines>> lineCache = new HashMap<>();
    @Resource(name = AdapterSchemeService.BEAN_ID)
    private AdapterSchemeService adapterSchemeService;
    @Autowired
    private ObjectMapper objectMapper;
    public static Map<Integer, List<FlowLines>> getLineCache() {
        return lineCache;
    }
    /**
     * 保存编排映射关系
     *
     * @param version 适配方案版本
     * @param json    映射数据
     * @return
     * @throws Exception
     */
    public ActionResult saveDataSetRelation(String version, String json) throws Exception {
        ObjectNode root = objectMapper.readValue(json,ObjectNode.class);
        ArrayNode jsonList = (ArrayNode) root.get("lines");
        ArrayNode entrances = (ArrayNode) root.get("entrances");
        AdapterSchemeVersionModel versionModel = (AdapterSchemeVersionModel) adapterSchemeVersionService.get(Long.valueOf(version));
        if (jsonList != null && jsonList.size() > 0) {
            // 删除旧关联关系
            crawlerFlowDao.deleteCrawlerFlowList(versionModel.getId());
            for (JsonNode obj : jsonList) {
                String from = obj.get("from").toString();
                String to = obj.get("to").toString();
                String fromPort = obj.get("fromPort").toString();
                String toPort = obj.get("toPort").toString();
                // 保存编排关系
                CrawlerFlowModel crawlerFlow = new CrawlerFlowModel();
                crawlerFlow.setDatasetCode(to);
                crawlerFlow.setInputDatasetCode(from);
                crawlerFlow.setMetadataCode(toPort);
                crawlerFlow.setInputMetadataCode(fromPort);
                crawlerFlow.setSchemeVersionId(versionModel.getId());
                crawlerFlowDao.saveEntity(crawlerFlow);
            }
            // 删除编排头部信息
            crawlerFlowHeadDao.deleteCrawlerFlowHeadList(versionModel.getId());
            for (JsonNode obj : entrances) {
                String dataSet = obj.get("dataSet").toString();
                String meta = obj.get("meta").toString();
                //  保存入口数据集
                CrawlerFlowHeadModel headModel = new CrawlerFlowHeadModel();
                headModel.setSchemeVersionId(versionModel.getId());
                headModel.setDatasetCode(dataSet);
                headModel.setMetadataCode(meta);
                crawlerFlowHeadDao.saveEntity(headModel);
            }
        }
        return new ActionResult(true, "保存成功!");
    }
    /**
     * 获取任务编排数据集列表
     *
     * @param schemeVersionId
     * @return
     * @throws Exception
     */
    public DetailModelResult getSchemeDataset(Long schemeVersionId, String datasetName) throws Exception {
        AdapterSchemeVersionModel versionModel = (AdapterSchemeVersionModel) adapterSchemeVersionService.get(schemeVersionId);
        //获取适配数据集总和
        Map<String, Object> map = new HashMap<String, Object>();
        String condition = null;
        if (datasetName != null && !"".equals(datasetName)) {
            map.put("name", datasetName);
            condition = objectMapper.writeValueAsString(condition);
        }
        List<AdapterDatasetModel> adapterDatasetModelList = adapterDatasetService.getDatasetList(AdapterDatasetModel.class, versionModel.getVersion(), condition, null, null, null);
        // 筛选掉 未适配数据
        List<AdapterDatasetModel> nAdapterDataSetModelList = new ArrayList<>();
        for (AdapterDatasetModel datasetModel : adapterDatasetModelList) {
            if (datasetModel.getAdapterDatasetId() != null && datasetModel.getAdapterDatasetName() != null && datasetModel.getAdapterDatasetCode() != null) {
                nAdapterDataSetModelList.add(datasetModel);
            }
        }
        //获取编排数据集
        List<CrawlerDataSetModel> crawlerDataset = crawlerDatasetDao.getCrawlerDatasetList(versionModel.getId());
        DetailModelResult re = new DetailModelResult();
        List<CrawlerDatasetResultDetailModel> list = new ArrayList<>();
        for (AdapterDatasetModel datasetModel : nAdapterDataSetModelList) {
            if (!StringUtil.isStrEmpty(datasetModel.getAdapterDatasetCode())) {
                List<AdapterMetadataModel> metadatas = adapterMetadataService.getAdapterMetadataByDataset(versionModel.getVersion(), datasetModel.getStdDatasetId());
                if (metadatas != null && metadatas.size() > 0) {
                    CrawlerDatasetResultDetailModel obj = new CrawlerDatasetResultDetailModel();
                    obj.setSchemeVersionId(schemeVersionId);
                    obj.setDatasetId(datasetModel.getStdDatasetId());
                    obj.setDatasetCode(datasetModel.getStdDatasetCode());
                    obj.setDatasetName(datasetModel.getStdDatasetName());
                    obj.setSchemeId(datasetModel.getSchemeId());
                    if (crawlerDataset != null && crawlerDataset.size() > 0) {
                        for (CrawlerDataSetModel cDataSet : crawlerDataset) {
                            if (cDataSet.getDatasetId().equals(datasetModel.getStdDatasetId())) {
                                obj.setSchemeVersionId(cDataSet.getSchemeVersionId());
                                obj.setChecked("1");
                                break;
                            }
                        }
                    }
                    list.add(obj);
                }
            }
        }
        re.setDetailModelList(list);
        return re;
    }
    /**
     * 保存任务编排数据
     *
     * @param json
     * @param rows
     * @param page @return
     * @throws Exception
     */
    public void saveJobData(String json, Integer rows, Integer page) throws Exception {
        ArrayNode jsonList = objectMapper.readValue(json,ArrayNode.class);
        //清空当页数据
        deleteCurrentPage(rows, page);
        for (JsonNode obj : jsonList) {
            if (obj.has("schemeId") && obj.has("versionId")) {
                String schemeId = obj.get("schemeId").asText();
                String versionId = obj.get("versionId").asText();
                AdapterSchemeVersionModel versionModel = (AdapterSchemeVersionModel) adapterSchemeVersionService.get(Long.valueOf(versionId));
                if (versionModel != null) {
                    AdapterVersion adapterVersion = new AdapterVersion(versionModel.getVersion());
                    //删除已存在的数据集
                    crawlerDatasetDao.deleteCrawlerDatasetList(versionModel.getId());
                    List<AdapterDatasetModel> adapterDatasetModelList;
                    //根据id字符串获取编排数据集
                    if (obj.has("dataSets")) {
                        List<Integer> newDatasetIdList = new ArrayList<>();
                        String dataSetStr = obj.get("dataSets").asText();
                        if (StringUtils.isNotBlank(dataSetStr)) {
                            String[] IdList = dataSetStr.split(",");
                            for (String aIdList : IdList) {
                                if (!Objects.equals(aIdList, "")) {
                                    Integer DaSetId = Integer.valueOf(aIdList);
                                    newDatasetIdList.add(DaSetId);
                                }
                            }
                        }
                        adapterDatasetModelList = adapterDatasetService.getListByAdapterDatasetIdList(adapterVersion, newDatasetIdList);
                        for (AdapterDatasetModel model : adapterDatasetModelList) {
                            CrawlerDataSetModel dataSetModel = new CrawlerDataSetModel();
                            dataSetModel.setSchemeId(Long.valueOf(schemeId));
                            dataSetModel.setSchemeVersionId(versionModel.getId());
                            dataSetModel.setDatasetId(model.getStdDatasetId());
                            dataSetModel.setDatasetCode(model.getStdDatasetCode());
                            dataSetModel.setDatasetName(model.getStdDatasetName());
                            crawlerDatasetDao.saveEntity(dataSetModel);
                        }
                    }
                    //如果保存传入编排映射关系,进行保存操作
                    if (obj.has("relation") && !Objects.equals(obj.get("relation").asText(), "")) {
                        saveDataSetRelation(versionId, obj.get("relation").asText());
                    }
                }
            }
        }
    }
    public List<FlowEntrance> getFlowEntrances(Long schemeVersionId) {
        List<FlowEntrance> entrances = new ArrayList<>();
        List<CrawlerFlowHeadModel> modelList = crawlerFlowHeadDao.getCrawlerFlowHeadList(schemeVersionId);
        for (CrawlerFlowHeadModel headModel : modelList) {
            FlowEntrance entrance = new FlowEntrance();
            entrance.setDataSet(headModel.getDatasetCode());
            entrance.setMeta(headModel.getMetadataCode());
            entrances.add(entrance);
        }
        return entrances;
    }
    public List<FlowLines> getFlowLines(Long schemeVersionId) {
        List<FlowLines> lines = new ArrayList<>();
        List<CrawlerFlowModel> modelList = crawlerFlowDao.getCrawlerFlowList(schemeVersionId);
        for (CrawlerFlowModel model : modelList) {
            FlowLines line = new FlowLines();
            line.setFrom(model.getInputDatasetCode());
            line.setFromPort(model.getInputMetadataCode());
            line.setTo(model.getDatasetCode());
            line.setToPort(model.getMetadataCode());
            lines.add(line);
        }
        return lines;
    }
    /**
     * 删除编排数据
     *
     * @param version
     */
    @Transactional
    public String deleteJobData(String version) {
        try {
            AdapterSchemeVersionModel versionModel = (AdapterSchemeVersionModel) adapterSchemeVersionService.get(Long.valueOf(version));
            if (versionModel == null || versionModel.getId() == null) {
                return "删除失败";
            }
            //删除对应表记录
            crawlerDatasetDao.deleteCrawlerDatasetList(versionModel.getId());
            crawlerFlowHeadDao.deleteCrawlerFlowHeadList(versionModel.getId());
            crawlerFlowDao.deleteCrawlerFlowList(versionModel.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败";
        }
        return SqlConstants.EMPTY;
    }
    /**
     * 数据集列表
     *
     * @param limit  rows
     * @param offset page
     * @return
     */
    public DetailModelResult getDataSetResult(Integer limit, Integer offset) {
        try {
            StringBuffer stringBuffer = new StringBuffer();
            String sql = "SELECT 1 as status, a.scheme_id, a.scheme_version_id, GROUP_CONCAT(a.dataset_id SEPARATOR ',') AS datasetId, GROUP_CONCAT(a.dataset_name SEPARATOR ',') AS datasetName" +
                    " FROM crawler_dataset a " +
                    " GROUP BY a.scheme_id, a.scheme_version_id ";
            stringBuffer.append(sql);
            if (limit != null && offset != null) {
                if (limit > 0 && offset > 0) {
                    stringBuffer.append("  LIMIT " + (offset - 1) * limit + "," + limit);
                }
            }
            stringBuffer.append(" ;");
            Integer total = crawlerDatasetDao.getTotalRows();
            List<Map<String, Object>> list = crawlerDatasetDao.queryListBySql(stringBuffer.toString());
            DetailModelResult detailModelResult = DetailModelResult.success("获取数据集成功");
            detailModelResult.setDetailModelList(list);
            detailModelResult.setTotalCount(total);
            return detailModelResult;
        } catch (Exception e) {
            e.printStackTrace();
            return DetailModelResult.error("获取数据集失败");
        }
    }
    /**
     * 获取编排已选择的适配数据集
     *
     * @param schemeVersionId
     * @param datasetIdStr
     * @return
     * @throws Exception
     */
    public List<MappingDataset> getSchemeDatasetByChecked(Long schemeVersionId, String datasetIdStr) throws Exception {
        AdapterSchemeVersionModel versionModel = (AdapterSchemeVersionModel) adapterSchemeVersionService.get(schemeVersionId);
        //获取适配数据集总和
        AdapterVersion adapterVersion = new AdapterVersion(versionModel.getVersion());
        List<AdapterDatasetModel> adapterDatasetModelList = new ArrayList<>();
        if (datasetIdStr != null && !"".equals(datasetIdStr)) {
            String[] datasetIdList = datasetIdStr.split(",");
            List<Integer> newDatasetIdList = new ArrayList<>();
            for (String datasetId : datasetIdList) {
                if (!StringUtil.isStrEmpty(datasetId)) {
                    Integer newDatasetId = Integer.parseInt(datasetId);
                    newDatasetIdList.add(newDatasetId);
                }
            }
            adapterDatasetModelList = adapterDatasetService.getListByAdapterDatasetIdList(adapterVersion, newDatasetIdList);
        } else {
            adapterDatasetModelList = adapterDatasetService.getDatasetList(AdapterDatasetModel.class, versionModel.getVersion(), null, null, null, null);
        }
        //获取编排数据集
        List<CrawlerDataSetModel> crawlerDataset = crawlerDatasetDao.getCrawlerDatasetList(versionModel.getId());
        List<MappingDataset> list = new ArrayList<>();
        for (AdapterDatasetModel datasetModel : adapterDatasetModelList) {
//            if (crawlerDataset != null && crawlerDataset.size() > 0) {
            MappingDataset obj = new MappingDataset();
//                for (CrawlerDataSetModel cDataSet : crawlerDataset) {
            if (!StringUtil.isStrEmpty(datasetModel.getAdapterDatasetCode())) {
                List<MappingMetadata> metadatas = getMappingMetaDatasByDataset(versionModel.getVersion(), datasetModel.getStdDatasetId());
                obj.setId(datasetModel.getStdDatasetId());
                obj.setCode(datasetModel.getStdDatasetCode());
                obj.setName(datasetModel.getStdDatasetName());
                obj.setData(metadatas);
//                        break;
            }
//                }
            list.add(obj);
//            }
        }
        return list;
    }
    /**
     * 返回前端映射数据元信息
     *
     * @param adapterVersion 适配版本号
     * @param dataSetId      适配数据集ID
     * @return
     */
    public List<MappingMetadata> getMappingMetaDatasByDataset(String adapterVersion, Long dataSetId) {
        List<AdapterMetadataModel> adapterMetadataModels = adapterMetadataService.getAdapterMetadataByDataset(adapterVersion, dataSetId);
        AdapterDatasetModel adapterDatasetModel = adapterMetadataService.getAdapterDataset(adapterVersion, dataSetId);
        List<MappingMetadata> resultList = new ArrayList<>();
        if (adapterMetadataModels != null && adapterMetadataModels.size() > 0) {
            for (AdapterMetadataModel metadataModel : adapterMetadataModels) {
                if (!StringUtil.isStrEmpty(metadataModel.getAdapterMetadataCode())) {
                    MappingMetadata metadata = new MappingMetadata();
                    metadata.setId(metadataModel.getAdapterMetadataId());
                    metadata.setCode(adapterDatasetModel.getAdapterDatasetCode() + "-" + metadataModel.getAdapterMetadataCode());
                    metadata.setName(metadataModel.getAdapterMetadataName());
                    resultList.add(metadata);
                }
            }
        }
        return resultList;
    }
    /**
     * 获取适配方案映射数据
     *
     * @param schemeVersionId
     * @param datasetIdStr
     * @return
     */
    public String getRelations(Long schemeVersionId, String datasetIdStr, String lineStr) {
        ObjectNode jsonObject = objectMapper.createObjectNode();
        try {
            List<MappingDataset> datasets = getSchemeDatasetByChecked(schemeVersionId, datasetIdStr);
            List<FlowLines> lines = getFlowLines(schemeVersionId);
            if (StringUtil.isEmpty(lineStr)) {
                lines = getFlowLines(schemeVersionId);
            } else {
                lines = lineCache.get(schemeVersionId);
            }
            jsonObject.set("tables", objectMapper.valueToTree(datasets));
            jsonObject.set("rels", objectMapper.valueToTree(lines));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }
    public void setLinesCache(Integer schemeVersionId, String lines) throws IOException {
        ObjectNode rootNode = objectMapper.readValue(lines, ObjectNode.class);
        String lineJson = rootNode.get("lines").toString();
        List<FlowLines> line = objectMapper.readValue(lineJson, List.class);
        lineCache.put(schemeVersionId, line);
    }
    public void deleteCurrentPage(Integer rows, Integer page) {
        DetailModelResult currentResut = getDataSetResult(rows, page);
        List<Map<String, Object>> list = currentResut.getDetailModelList();
        for (Map<String, Object> map : list) {
            String version = String.valueOf(map.get("scheme_version_id"));
            deleteJobData(version);
        }
    }
    public DetailModelResult getDataSetSavedResult(Long version) {
        try {
            DetailModelResult checkedSchemeLs = getDataSetResult(null, null);
            List<Map<String, Object>> list = checkedSchemeLs.getDetailModelList();
            for (Map<String, Object> objectMap : list) {
                String versionID = objectMap.get("scheme_version_id").toString();
                if (versionID.equals(version.toString())) {
                    String datasetIdStr = objectMap.get("dataSetId").toString();
                    List<MappingDataset> datasetList = getSchemeDatasetByChecked(version, datasetIdStr);
                    List<DtoJobDataset>  rsJobDatasetList = new ArrayList<>();
                    for (MappingDataset dataset : datasetList) {
                        DtoJobDataset rsJobDataset = new DtoJobDataset();
                        rsJobDataset.setJobDatasetId(dataset.getId().toString());
                        rsJobDataset.setJobDatasetName(dataset.getName());
                        rsJobDataset.setJobDatasetCode(dataset.getCode());
                        rsJobDatasetList.add(rsJobDataset);
                    }
                    DetailModelResult result = new DetailModelResult();
                    result.setDetailModelList(rsJobDatasetList);
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DetailModelResult.error("获取已存任务编排数据集错误");
        }
        return DetailModelResult.error("获取已存任务编排数据集错误");
    }
    public DetailModelResult getSchemeSavedResult() {
        DetailModelResult allScheme = adapterSchemeService.getAdapterSchemeResultModelList();
        List<AdapterSchemeResultModel> allSchemeLs = allScheme.getDetailModelList();
        if (allSchemeLs != null && allSchemeLs.size() > 0) {
            DetailModelResult checkedSchemeLs = getDataSetResult(null, null);
            List<Map<String, Object>> list = checkedSchemeLs.getDetailModelList();
            Set<String> schemeIdSets = new HashSet<>();
            Set<String> versionSets = new HashSet<>();
            DetailModelResult result = new DetailModelResult();
            List<AdapterSchemeVersionResultDetailModel> versionModelList = new ArrayList<>();
            if (list != null && list.size() > 0) {
                for (Map<String, Object> objectMap : list) {
                    if (objectMap.get("scheme_id") != null && objectMap.get("scheme_version_id") != null) {
                        schemeIdSets.add(objectMap.get("scheme_id").toString());
                        versionSets.add(objectMap.get("scheme_version_id").toString());
                    }
                }
                if (schemeIdSets.size() > 0 && versionSets.size() > 0) {
                    for (AdapterSchemeResultModel schemeL : allSchemeLs) {
                        String schemeID = schemeL.getSchemeId().toString();
                        if (schemeIdSets.contains(schemeID)) {
                            String name = schemeL.getName();
                            List<AdapterSchemeVersionModel> versionModels = schemeL.getVersionList();
                            for (AdapterSchemeVersionModel versionModel : versionModels) {
                                String versionID = versionModel.getId().toString();
                                if (versionSets.contains(versionID)) {
                                    AdapterSchemeVersionResultDetailModel model = new AdapterSchemeVersionResultDetailModel();
                                    model.setSchemeName(name);
                                    model.setId(versionModel.getId());
                                    model.setName(versionModel.getName());
                                    model.setSchemeId(versionModel.getSchemeId());
                                    model.setBaseVersion(versionModel.getBaseVersion());
                                    model.setPath(versionModel.getPath());
                                    model.setPublishStatus(versionModel.getPublishStatus());
                                    model.setPublishTime(versionModel.getPublishTime());
                                    model.setPublishUser(versionModel.getPublishUser());
                                    model.setVersion(versionModel.getVersion());
                                    versionModelList.add(model);
                                }
                            }
                        }
                    }
                    result.setDetailModelList(versionModelList);
                    return result;
                }
            }
        }
        return DetailModelResult.error("获取已编排任务适配方案失败!");
    }
}

+ 411 - 0
src/main/java/com/yihu/hos/datacollect/controller/DataCollectController.java

@ -0,0 +1,411 @@
package com.yihu.hos.datacollect.controller;
import com.yihu.hos.common.Services;
import com.yihu.hos.datacollect.model.RsJobConfig;
import com.yihu.hos.datacollect.service.DatacollectManager;
import com.yihu.hos.resource.service.StdService;
import com.yihu.hos.system.service.DatasourceManager;
import com.yihu.hos.web.framework.constant.DateConvert;
import com.yihu.hos.web.framework.model.ActionResult;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 数据采集配置页面
 * Created by hzp on 2015/8/12.
 */
@RequestMapping("/datacollectEndpoint")
@Controller("dataCollectController")
public class DataCollectController extends BaseController {
    @Resource(name = Services.Datacollect)
    DatacollectManager datacollect;
    @Resource(name = StdService.BEAN_ID)
    StdService stdService;
    @Resource(name = Services.Datasource)
    DatasourceManager datasource;
    /*
* 通过id获取job
 */
    @RequestMapping("getJobById")
    @ResponseBody
    public RsJobConfig getJobById(@RequestParam(value="jobId") String jobId) throws Exception {
        RsJobConfig job = datacollect.getJobById(jobId);
        return job;
    }
    //获取方案列表
    @RequestMapping("getSchemeVersion")
    @ResponseBody
    public List getSchemeVersion() {
        List data = stdService.getSchemeVersion();
        return data;
    }
    /*
    获取任务列表
    */
    @RequestMapping("getJob")
    @ResponseBody
    public Result getJob(String name, int page, int rows) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("name", name);
            return datacollect.getJobList(map, page, rows);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    @RequestMapping("compareServeTime")
    @ResponseBody
    public Result compareServeTime(String time) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (df.parse(time).before(new Date())) {
                return Result.success("beforeServeTime");
            } else
                return Result.error("afterServeTime");
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    /**
     * 根据适配方案获取数据集列表
     */
    @RequestMapping("getSchemeDataset")
    @ResponseBody
    public Result getSchemeDataset(String schemeId, String schemeVersion, String jobId) {
        try {
            return datacollect.getSchemeDataset(schemeId, schemeVersion, jobId);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    /**
     * 根据适配方案+数据集获取字段列表
     */
    @RequestMapping("getSchemeDatasetCol")
    @ResponseBody
    public Result getSchemeDatasetCol(String schemeId, String schemeVersion, String datasetId) {
        try {
            return datacollect.getSchemeDatasetCol(schemeId, schemeVersion, datasetId);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    /*
       新增任务
    */
    @RequestMapping("addJob")
    @ResponseBody
    public Result addJob(@RequestBody String rsJobConfig,
                         @RequestParam(value="cron") String cron,
                         @RequestParam(value="jobDataset") String jobDataset) {
        try {
            return datacollect.addJob(toEntity(rsJobConfig, RsJobConfig.class), cron, jobDataset);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("新增任务失败!");
        }
    }
    /*
       修改任务
    */
    @RequestMapping("updateJob")
    @ResponseBody
    public Result updateJob(@RequestBody String rsJobConfig,
                            @RequestParam(value="cron") String cron,
                            @RequestParam(value="jobDataset") String jobDataset) {
        try {
            return datacollect.updateJob(toEntity(rsJobConfig,RsJobConfig.class), cron, jobDataset);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error("修改任务失败!");
        }
    }
    /*
      修改任务状态
   */
    @RequestMapping("validJob")
    @ResponseBody
    public Result validJob(String jobId, String valid) {
        try {
            return datacollect.validJob(jobId, valid);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    /*
      删除任务
   */
    @RequestMapping("deleteJob")
    @ResponseBody
    public Result deleteJob(@RequestParam(value="jobId") String jobId) {
        try {
            return datacollect.deleteJob(jobId);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error(ex.getMessage());
        }
    }
    /**
     * 获取任务信息
     *
     * @return
     */
    @RequestMapping("getJobInfo")
    @ResponseBody
    public Result getJobInfo(String jobId) {
        try {
            RsJobConfig job = datacollect.getJobById(jobId);
            if (job != null) {
                ActionResult re = new ActionResult(true, "");
                re.setData(job.getValid());
                return re;
            } else {
                return new ActionResult(false, "非法操作!");
            }
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    /**
     * 根据任务Id获取相关数据集下拉数据
     *
     * @return
     */
    @RequestMapping("getJobDatasetByJobId")
    @ResponseBody
    public Result getJobDatasetByJobId(String jobId) {
        try {
            return datacollect.getJobDatasetByJobId(jobId);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    /*************************
     * 数据集--数据源管理
     ******************************************/
    /*
    数据集配置
     */
    @RequestMapping("configDataset")
    public String configDataset(Model model) {
        try {
            model.addAttribute("stdVersion", "569e19522e3d");
            //获取数据源数据
            model.addAttribute("datasourceList", datasource.getDatasourceByOrg("").toJson());
            model.addAttribute("contentPage", "/datacollect/configDataset");
            return "partView";
        } catch (Exception ex) {
            model.addAttribute("contentPage", "error");
            return "partView";
        }
    }
    @RequestMapping("getDatasourceByOrg")
    public String getDatasourceByOrg(String orgCode) throws Exception {
        return datasource.getDatasourceByOrg(orgCode).toJson();
    }
    /**
     * 数据集数据源管理列表(包含全部数据集)
     *
     * @return
     */
    @RequestMapping("getDatasetSource")
    @ResponseBody
    public Result getDatasetSource(String stdVersion) {
        try {
            return datacollect.getDatasetSource(stdVersion);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    /**
     * 更新数据集数据源
     *
     * @return
     */
    @RequestMapping("saveDatasetSource")
    @ResponseBody
    public Result saveDatasetSource(String stdVersion, String json) {
        try {
            return datacollect.saveDatasetSource(json);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    /*************************** 任务执行 ************************************************/
    /**
     * 执行任务
     *
     * @return
     */
    @RequestMapping("executeJob")
    @ResponseBody
    public Result executeJob(String jobId) {
        try {
            //获取任务详细信息
            RsJobConfig job = datacollect.getJobById(jobId);
            String content = job.getJobContent();
            Class<?> classType = Class.forName(content);
            Method method = classType.getMethod("execute", new Class[]{String.class});
            method.invoke(classType.newInstance(), jobId);
            return Result.success("处理完成!");
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    /*
    任务补采界面
     */
    @RequestMapping("repeatDatacollect")
    public String repeatDatacollect(Model model, String jobId, String jobDatasetId, String jobStatus, String jobTimeFrom, String jobTimeTo) {
        try {
            model.addAttribute("jobId", jobId == null ? "" : jobId);
            model.addAttribute("jobDatasetId", jobDatasetId == null ? "" : jobDatasetId);
            model.addAttribute("jobStatus", jobStatus == null ? "" : jobStatus);
            if (jobTimeFrom != null && jobTimeFrom.length() > 0) {
                Date timeFrom = DateConvert.toDate(jobTimeFrom);
                model.addAttribute("jobTimeFrom", DateConvert.toString(timeFrom));
            } else {
                GregorianCalendar gc = new GregorianCalendar();
                gc.setTime(new Date());
                gc.add(5, -1);
                model.addAttribute("jobTimeFrom", DateConvert.toString(gc.getTime()));
            }
            if (jobTimeTo != null && jobTimeTo.length() > 0) {
                Date timeTo = DateConvert.toDate(jobTimeTo);
                model.addAttribute("jobTimeTo", DateConvert.toString(timeTo));
            } else {
                model.addAttribute("jobTimeTo", DateConvert.toString(new Date()));
            }
            model.addAttribute("contentPage", "/datacollect/repeatDatacollect");
            return "partView";
        } catch (Exception ex) {
            model.addAttribute("contentPage", "error");
            return "partView";
        }
    }
    /**
     * 任务详细日志列表
     *
     * @return
     */
    @RequestMapping("getJobLogDetail")
    @ResponseBody
    public Result getJobLogDetail(String jobId, String jobDatasetId, String jobStatus, String jobTimeFrom, String jobTimeTo, int page, int rows) {
        try {
            Map<String, Object> conditionMap = new HashMap<String, Object>();
            conditionMap.put("jobId", jobId);
            conditionMap.put("jobDatasetId", jobDatasetId);
            conditionMap.put("jobStatus", jobStatus);
            conditionMap.put("jobTimeFrom", jobTimeFrom);
            conditionMap.put("jobTimeTo", jobTimeTo);
            return datacollect.getJobLogDetail(conditionMap, page, rows);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    /**
     * 补采数据
     *
     * @return
     */
    @RequestMapping("repeat")
    @ResponseBody
    public Result repeat(String ids) {
        return Result.error("非法操作!");
    }
    /*************************** 任务跟踪 ***********************************/
    /**
     * 任务跟踪界面
     *
     * @return
     */
    @RequestMapping("trackJob")
    public String trackJob(Model model, String jobId) {
        try {
            model.addAttribute("contentPage", "/datacollect/trackJob");
            return "pageView";
        } catch (Exception ex) {
            model.addAttribute("contentPage", "error");
            return "partView";
        }
    }
    /**
     * 任务日志列表
     *
     * @return
     */
    @RequestMapping("getJobLog")
    @ResponseBody
    public Result getJobLog(String jobId, int page, int rows) {
        try {
            Map<String, Object> conditionMap = new HashMap<String, Object>();
            conditionMap.put("jobId", jobId);
            return datacollect.getJobLog(conditionMap, page, rows);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
    /**
     * 任务详细根据数据集分组
     *
     * @return
     */
    @RequestMapping("getJobLogDataset")
    @ResponseBody
    public Result getJobLogDataset(String logId) {
        try {
            return datacollect.getJobLogDataset(logId);
        } catch (Exception ex) {
            return Result.error(ex.getMessage());
        }
    }
}

+ 26 - 0
src/main/java/com/yihu/hos/datacollect/controller/JobConfigController.java

@ -0,0 +1,26 @@
package com.yihu.hos.datacollect.controller;
import com.yihu.hos.datacollect.service.JobConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
 * @author Airhead
 * @created 2018-03-30
 */
@RestController
@RequestMapping("/job/config")
public class JobConfigController {
    @Autowired
    private JobConfigService jobConfigService;
    @RequestMapping(path = "data", method = RequestMethod.GET)
    public List getData(@RequestParam(value = "lastUpdate", required = false) String lastUpdate) throws Exception {
        return jobConfigService.getData(lastUpdate);
    }
}

+ 26 - 0
src/main/java/com/yihu/hos/datacollect/controller/JobDataSetController.java

@ -0,0 +1,26 @@
package com.yihu.hos.datacollect.controller;
import com.yihu.hos.datacollect.service.JobDataSetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
 * @author Airhead
 * @created 2018-03-30
 */
@RestController
@RequestMapping("/job/data-set")
public class JobDataSetController {
    @Autowired
    private JobDataSetService jobDataSetService;
    @RequestMapping(path = "data", method = RequestMethod.GET)
    public List getData(@RequestParam(value = "lastUpdate", required = false) String lastUpdate) throws Exception {
        return jobDataSetService.getData(lastUpdate);
    }
}

+ 281 - 0
src/main/java/com/yihu/hos/datacollect/dao/DatacollectDao.java

@ -0,0 +1,281 @@
package com.yihu.hos.datacollect.dao;
import com.yihu.hos.datacollect.model.DtoJobDataset;
import com.yihu.hos.datacollect.model.RsJobDataset;
import com.yihu.hos.resource.model.RsDatasourceDataset;
import com.yihu.hos.web.framework.constant.DateConvert;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.model.DataGridResult;
import com.yihu.hos.web.framework.model.SimpleChartItem;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
/**
 * Created by hzp on 2016/1/11.
 */
@Repository("DatacollectDao")
public class DatacollectDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "DatacollectDao";
    /**
     * 通过机构代码获取版本号
     */
    
    public String getVersionByQLC(String orgCode) throws Exception
    {
        try{
            String sql = "select version from adapter_scheme_version v "+
                         " left join system_organization o on o.qlc_adapter_version=v.id "+
                         " where o.qlc_org_code ='"+orgCode+"'";
            return super.scalarBySql(sql, String.class);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return "";
        }
    }
    /**
     * 根据JobId获取Cron表达式
     */
    
    public String getCronByJobId(String jobId)
    {
        try{
            String sql = "select CRON_EXPRESSION from qrtz_cron_triggers where TRIGGER_NAME='"+jobId+"'";
            return super.scalarBySql(sql, String.class);
        }
        catch (Exception e)
        {
            return "";
        }
    }
    /**
     * 获取任务列表
     * @return
     */
    
    public DataGridResult getJobList(Map<String, Object> conditionMap, Integer page, Integer pageSize) throws Exception
    {
        StringBuilder sb = new StringBuilder();
        sb.append("from RsJobConfig t where 1=1 ");
        if (!StringUtils.isEmpty(conditionMap.get("jobName")))
        {
            sb.append(" and t.jobName like '%" + conditionMap.get("jobName") + "%'");
        }
        return getDataGridResult(sb.toString(),page,pageSize);
    }
    /**
     * 获取任务数据集
     * @return
     * @throws Exception
     */
    
    public List<RsJobDataset> getJobDataset(String jobId) throws Exception
    {
        String sql = "select * from rs_job_dataset where job_id='"+jobId+"'";
        return super.queryListBySql(sql, RsJobDataset.class);
    }
    /**
     * 获取版本名称
     */
    
    public String getSchemeAndVersion(String schemeVersionId) throws Exception
    {
        String sql = "select IFNULL( (select  CONCAT_WS(' -- ',s.name,v.name)  from adapter_scheme_version v " +
                "left join adapter_scheme s on s.id = v.scheme_id " +
                "where v.version='"+schemeVersionId+"'),'')";
        return super.scalarBySql(sql, String.class);
    }
    /**
     * 修改任务状态
     */
    
    public void validJob(String id,String valid) throws Exception
    {
        String sql = "update rs_job_config set valid='"+valid+"' where Id='"+id+"'";
        super.execute(sql);
    }
    /**
     * 删除任务关联数据集
     */
    public void deleteJobDatasetByJobId(String jobId) throws Exception
    {
        List<RsJobDataset> list = (List<RsJobDataset>) super.hibernateTemplate.find("from RsJobDataset s where s.jobId=? ", jobId);
        //判断是否存在数据
        if(list!=null && list.size()>0)
        {
            for(RsJobDataset obj :list)
            {
                super.deleteEntity(obj);
            }
        }
    }
    /**
     * 通过版本获取配置的数据集--数据源
     * @throws Exception
     */
    public List<RsDatasourceDataset> getDatasourceDataset(String stdVersion) throws Exception
    {
        String sql = "select * from rs_datasource_dataset where std_version='"+stdVersion+"'";
        return super.queryListBySql(sql, RsDatasourceDataset.class);
    }
    /**
     * 删除数据集数据源关联
     */
    public void deleteDatasourceDatasetById(String id) throws Exception
    {
        String sql = "delete from rs_datasource_dataset where id='"+id+"'";
        super.execute(sql);
    }
    /**
     * 通过任务ID获取相关数据集
     */
    public List<DtoJobDataset> getDatacollectDataset(String jobId) throws Exception
    {
        //通过jobId获取机构版本号
        String sqlVersion ="select a.adapter_std_version\n" +
                "from rs_job_config c,(SELECT s.adapter_std_version,v.version from adapter_scheme s,adapter_scheme_version v where s.id=v.scheme_id) a\n" +
                "where a.version = c.scheme_version\n" +
                "and c.id='"+jobId+"'";
        String version = super.scalarBySql(sqlVersion,String.class);
        String sql = "select d.*,\n" +
                "t.datasource_id,t.datasource_name,t.config,t.type,t.org_code\n" +
                "from rs_job_dataset d\n" +
                "LEFT JOIN (select s.dataset_id,s.datasource_id,ss.name as datasource_name,ss.config,ss.type,ss.org_code \n" +
                "\tfrom rs_datasource_dataset s,(select ds.id,ds.name,ds.config,ds.type,o.code as org_code from system_datasource ds,system_organization o where ds.org_id=o.id) ss where s.datasource_id=ss.id and s.Std_version='"+version+"') t \n" +
                "on d.job_dataset_id = t.dataset_id \n" +
                "where d.job_id='"+jobId+"'\n" +
                "order by d.sort";
        return super.queryListBySql(sql,DtoJobDataset.class);
    }
    /**
     * 获取任务详细日志列表
     */
    
    public DataGridResult getJobLogDetail(Map<String, Object> conditionMap, Integer page, Integer pageSize) throws Exception
    {
        StringBuilder sb = new StringBuilder();
        sb.append("from RsJobLogDetail where 1=1 ");
        if (!StringUtils.isEmpty(conditionMap.get("jobId"))) {
            sb.append(" and job_id ='"+conditionMap.get("jobId")+"'");
        }
        if (!StringUtils.isEmpty(conditionMap.get("jobDatasetId"))) {
            sb.append(" and job_dataset_id ='"+conditionMap.get("jobDatasetId")+"'");
        }
        if (!StringUtils.isEmpty(conditionMap.get("jobStatus"))) {
            sb.append(" and jobStatus ='"+conditionMap.get("jobStatus")+"'");
        }
        if (!StringUtils.isEmpty(conditionMap.get("jobTimeFrom"))) {
            Date time = DateConvert.toDate(conditionMap.get("jobTimeFrom").toString());
            time.setHours(0);
            time.setMinutes(0);
            time.setSeconds(0);
            sb.append(" and startTime >= '"+DateConvert.toString(time)+"'");
        }
        if (!StringUtils.isEmpty(conditionMap.get("jobTimeTo"))) {
            Date time = DateConvert.toDate(conditionMap.get("jobTimeTo").toString());
            time.setHours(0);
            time.setMinutes(0);
            time.setSeconds(0);
            GregorianCalendar gc=new GregorianCalendar();
            gc.setTime(time);
            gc.add(5, 1);
            sb.append(" and startTime < '"+DateConvert.toString(gc.getTime())+"'");
        }
        sb.append("order by startTime desc");
        return getDataGridResult(sb.toString(),page,pageSize);
    }
    /**
     * 获取任务日志列表
     */
    
    public DataGridResult getJobLog(Map<String, Object> conditionMap, Integer page, Integer pageSize) throws Exception
    {
        StringBuilder sb = new StringBuilder();
        sb.append("from RsJobLog where 1=1 ");
        if (!StringUtils.isEmpty(conditionMap.get("jobId"))) {
            sb.append(" and jobId ='"+conditionMap.get("jobId")+"'");
        }
        sb.append("order by jobStartTime desc");
        return getDataGridResult(sb.toString(),page,pageSize);
    }
    /**
     * 获取采集日志统计
     */
    public List<Map<String, Object>> getJobLogCount(String logId) throws Exception
    {
        String sql ="select d.job_log_id,sum(d.Job_dataset_rows) as count,\n" +
                "sum(case d.job_status\n" +
                "    when '1' THEN\n" +
                "         d.Job_dataset_rows\n" +
                "    ELSE\n" +
                "         0\n" +
                "    END) as success,\n" +
                "sum(case d.job_status\n" +
                "    when '3' THEN\n" +
                "         d.Job_dataset_rows\n" +
                "    ELSE\n" +
                "         0\n" +
                "    END) as repeat_num\n" +
                "from rs_job_log_detail d\n";
        if(logId!=null && logId.length()>0)
        {
            sql += "where d.job_log_id ='"+logId+"'\n";
        }
        sql+="group by d.job_log_id ";
        return super.queryListBySql(sql);
    }
    /**
     * 任务详细根据数据集分组
     */
    public List<SimpleChartItem> getJobLogDataset(String logId) throws Exception
    {
        String sql ="select d.job_dataset_name as x,sum(d.Job_dataset_rows) as y1,\n" +
                "                sum(case d.job_status\n" +
                "                    when '1' THEN\n" +
                "                         d.Job_dataset_rows\n" +
                "                    ELSE\n" +
                "                         0\n" +
                "                    END) as y2,\n" +
                "                sum(case d.job_status\n" +
                "                    when '3' THEN\n" +
                "                         d.Job_dataset_rows\n" +
                "                    ELSE\n" +
                "                         0\n" +
                "                    END) as y3\n" +
                "                from rs_job_log_detail d\n" +
                "where d.job_log_id = '"+logId+"'\n" +
                "GROUP BY d.Job_dataset_name";
        return super.queryListBySql(sql,SimpleChartItem.class);
    }
}

+ 78 - 0
src/main/java/com/yihu/hos/datacollect/dao/DatacollectLogDao.java

@ -0,0 +1,78 @@
package com.yihu.hos.datacollect.dao;
import com.yihu.hos.datacollect.model.RsDatapushLog;
import com.yihu.hos.web.framework.constant.DateConvert;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.model.DataGridResult;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
/**
 * Created by hzp on 2016/1/11.
 */
@Repository("DatacollectLogDao")
public class DatacollectLogDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "DatacollectLogDao";
    /**
     * 修改轮询字段
     */
    
    public void updateJobDatasetKeyvalue(String id,String jobDatasetKeyvalue) throws Exception
    {
        String sql = "update rs_job_dataset set job_dataset_keyvalue='"+jobDatasetKeyvalue+"' where id='"+id+"'";
        super.execute(sql);
    }
    /******************************** 推模式日志 ***************************************/
    /**
     * 推数据新增日志
     */
    
    public void addDataPushLog(String type,String success,String content) throws Exception
    {
        RsDatapushLog log = new RsDatapushLog();
        log.setType(type);
        log.setSuccess(success);
        log.setContent(content);
        log.setDatetime(new Date());
        this.saveEntity(log);
    }
    /**
     * 获取日志列表
     */
    public DataGridResult queryDataPushLog(Map<String, Object> conditionMap, Integer page, Integer pageSize) throws Exception
    {
        StringBuilder sb = new StringBuilder();
        sb.append("from RsDatapushLog where 1=1 ");
        if (!StringUtils.isEmpty(conditionMap.get("type"))) {
            sb.append(" and type ='"+conditionMap.get("type")+"'");
        }
        if (!StringUtils.isEmpty(conditionMap.get("datetimeFrom"))) {
            Date time = DateConvert.toDate(conditionMap.get("datetimeFrom").toString());
            time.setHours(0);
            time.setMinutes(0);
            time.setSeconds(0);
            sb.append(" and datetime >= '"+DateConvert.toString(time)+"'");
        }
        if (!StringUtils.isEmpty(conditionMap.get("datetimeTo"))) {
            Date time = DateConvert.toDate(conditionMap.get("datetimeTo").toString());
            time.setHours(0);
            time.setMinutes(0);
            time.setSeconds(0);
            GregorianCalendar gc=new GregorianCalendar();
            gc.setTime(time);
            gc.add(5, 1);
            sb.append(" and datetime < '"+DateConvert.toString(gc.getTime())+"'");
        }
        sb.append("order by datetime desc");
        return getDataGridResult(sb.toString(),page,pageSize);
    }
}

+ 19 - 0
src/main/java/com/yihu/hos/datacollect/dao/JobConfigDao.java

@ -0,0 +1,19 @@
package com.yihu.hos.datacollect.dao;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
 * @author Airhead
 * @created 2018-04-03
 */
@Repository
public class JobConfigDao extends SQLGeneralDAO {
    public List getData(String lastUpdate) {
        Query query = getCurrentSession().createQuery("from RsJobConfig t");
        return query.list();
    }
}

+ 19 - 0
src/main/java/com/yihu/hos/datacollect/dao/JobDataSetDao.java

@ -0,0 +1,19 @@
package com.yihu.hos.datacollect.dao;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
 * @author Airhead
 * @created 2018-04-03
 */
@Repository
public class JobDataSetDao extends SQLGeneralDAO {
    public List getData(String lastUpdate) {
        Query query = getCurrentSession().createQuery("from RsJobDataset t");
        return query.list();
    }
}

+ 48 - 0
src/main/java/com/yihu/hos/datacollect/model/DtoDatasetCol.java

@ -0,0 +1,48 @@
package com.yihu.hos.datacollect.model;
import org.json.JSONArray;
/**
 * 数据集字段
 */
public class DtoDatasetCol implements java.io.Serializable {
	private String code;
	private String text;
	private String type;
	private String dict;
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getDict() {
		return dict;
	}
	public void setDict(String dict) {
		this.dict = dict;
	}
}

+ 48 - 0
src/main/java/com/yihu/hos/datacollect/model/DtoDictCol.java

@ -0,0 +1,48 @@
package com.yihu.hos.datacollect.model;
import org.json.JSONArray;
/**
 * 数据源关联字典
 */
public class DtoDictCol implements java.io.Serializable {
    private String stdMetadataCode;
    private String adapterDataType;
    private String stdDictId;
    private JSONArray dictList;
    public String getStdMetadataCode() {
        return stdMetadataCode;
    }
    public void setStdMetadataCode(String stdMetadataCode) {
        this.stdMetadataCode = stdMetadataCode;
    }
    public String getAdapterDataType() {
        return adapterDataType;
    }
    public void setAdapterDataType(String adapterDataType) {
        this.adapterDataType = adapterDataType;
    }
    public String getStdDictId() {
        return stdDictId;
    }
    public void setStdDictId(String stdDictId) {
        this.stdDictId = stdDictId;
    }
    public JSONArray getDictList() {
        return dictList;
    }
    public void setDictList(JSONArray dictList) {
        this.dictList = dictList;
    }
}

+ 37 - 0
src/main/java/com/yihu/hos/datacollect/model/DtoJobConfig.java

@ -0,0 +1,37 @@
package com.yihu.hos.datacollect.model;
import java.sql.Timestamp;
/**
 * RsJobConfig entity. @author MyEclipse Persistence Tools
 */
public class DtoJobConfig extends RsJobConfig implements java.io.Serializable {
	private String schemeAndVersion;
	private String jobDataset;
	private String jobPlan;
	public String getSchemeAndVersion() {
		return schemeAndVersion;
	}
	public void setSchemeAndVersion(String schemeAndVersion) {
		this.schemeAndVersion = schemeAndVersion;
	}
	public String getJobDataset() {
		return jobDataset;
	}
	public void setJobDataset(String jobDataset) {
		this.jobDataset = jobDataset;
	}
	public String getJobPlan() {
		return jobPlan;
	}
	public void setJobPlan(String jobPlan) {
		this.jobPlan = jobPlan;
	}
}

+ 103 - 0
src/main/java/com/yihu/hos/datacollect/model/DtoJobDataset.java

@ -0,0 +1,103 @@
package com.yihu.hos.datacollect.model;
/**
 * RsJobDataset entity. @author MyEclipse Persistence Tools
 */
public class DtoJobDataset extends RsJobDataset implements java.io.Serializable {
	private String checked;
	private String jobDatasetCode;
	/** 数据源相关 **/
	private String orgCode;
	private String datasourceId;
	private String datasourceName;
	private String config;
	private String type;
	/**	 目标表字段信息 **/
	private String targetDataSetId;
	private String targetDataSetCode;
	private String targetDataSetName;
	public String getOrgCode() {
		return orgCode;
	}
	public void setOrgCode(String orgCode) {
		this.orgCode = orgCode;
	}
	public String getChecked() {
		return checked;
	}
	public void setChecked(String checked) {
		this.checked = checked;
	}
	public String getJobDatasetCode() {
		return jobDatasetCode;
	}
	public void setJobDatasetCode(String jobDatasetCode) {
		this.jobDatasetCode = jobDatasetCode;
	}
	public String getDatasourceId() {
		return datasourceId;
	}
	public void setDatasourceId(String datasourceId) {
		this.datasourceId = datasourceId;
	}
	public String getDatasourceName() {
		return datasourceName;
	}
	public void setDatasourceName(String datasourceName) {
		this.datasourceName = datasourceName;
	}
	public String getConfig() {
		return config;
	}
	public void setConfig(String config) {
		this.config = config;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getTargetDataSetId() {
		return targetDataSetId;
	}
	public void setTargetDataSetId(String targetDataSetId) {
		this.targetDataSetId = targetDataSetId;
	}
	public String getTargetDataSetCode() {
		return targetDataSetCode;
	}
	public void setTargetDataSetCode(String targetDataSetCode) {
		this.targetDataSetCode = targetDataSetCode;
	}
	public String getTargetDataSetName() {
		return targetDataSetName;
	}
	public void setTargetDataSetName(String targetDataSetName) {
		this.targetDataSetName = targetDataSetName;
	}
}

+ 36 - 0
src/main/java/com/yihu/hos/datacollect/model/DtoJobLog.java

@ -0,0 +1,36 @@
package com.yihu.hos.datacollect.model;
/**
 * add by hzp at 20160204
 */
public class DtoJobLog extends RsJobLog implements java.io.Serializable {
	private Integer count;
	private Integer success;
	private Integer repeatNum;
	public Integer getCount() {
		return count;
	}
	public void setCount(Integer count) {
		this.count = count;
	}
	public Integer getSuccess() {
		return success;
	}
	public void setSuccess(Integer success) {
		this.success = success;
	}
	public Integer getRepeatNum() {
		return repeatNum;
	}
	public void setRepeatNum(Integer repeatNum) {
		this.repeatNum = repeatNum;
	}
}

+ 58 - 0
src/main/java/com/yihu/hos/datacollect/model/RsDatapushLog.java

@ -0,0 +1,58 @@
package com.yihu.hos.datacollect.model;
import java.util.Date;
/**
 * RsJobLog entity. @author MyEclipse Persistence Tools
 */
public class RsDatapushLog implements java.io.Serializable {
	// Fields
	private String id;
	private String type;
	private String success;
	private String content;
	private Date datetime;
	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 getSuccess() {
		return success;
	}
	public void setSuccess(String success) {
		this.success = success;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Date getDatetime() {
		return datetime;
	}
	public void setDatetime(Date datetime) {
		this.datetime = datetime;
	}
}

+ 193 - 0
src/main/java/com/yihu/hos/datacollect/model/RsJobConfig.java

@ -0,0 +1,193 @@
package com.yihu.hos.datacollect.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
 * RsJobConfig entity. @author MyEclipse Persistence Tools
 */
public class RsJobConfig implements java.io.Serializable {
    // Fields
    private String id;
    private String jobName;
    private String jobInfo;
    private String jobType;
    private String schemeId;
    private String schemeVersion;
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'ZZ")
    private Date jobNextTime;
    private String valid;
    private String jobContent;
    private String jobContentType;
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'ZZ")
    private Date repeatStartTime;
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'ZZ")
    private Date repeatEndTime;
    private Integer delayTime;
    private Integer flowId;
    private Integer flowTempId;
    private String jobCron;
    // Constructors
    /**
     * default constructor
     */
    public RsJobConfig() {
    }
    /**
     * minimal constructor
     */
    public RsJobConfig(String jobName, String valid) {
        this.jobName = jobName;
        this.valid = valid;
    }
    /**
     * full constructor
     */
    public RsJobConfig(String jobName, String jobInfo, String jobType, String schemeId, String schemeVersion, String jobTimeInterval, Date jobNextTime, String valid) {
        this.jobName = jobName;
        this.jobInfo = jobInfo;
        this.jobType = jobType;
        this.schemeId = schemeId;
        this.schemeVersion = schemeVersion;
        this.jobNextTime = jobNextTime;
        this.valid = valid;
    }
    public Integer getFlowTempId() {
        return flowTempId;
    }
    public void setFlowTempId(Integer flowTempId) {
        this.flowTempId = flowTempId;
    }
    public Integer getFlowId() {
        return flowId;
    }
    public void setFlowId(Integer flowId) {
        this.flowId = flowId;
    }
    public String getJobContent() {
        return jobContent;
    }
    public void setJobContent(String jobContent) {
        this.jobContent = jobContent;
    }
    public String getJobContentType() {
        return jobContentType;
    }
    public void setJobContentType(String jobContentType) {
        this.jobContentType = jobContentType;
    }
    // Property accessors
    public String getId() {
        return this.id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getJobName() {
        return this.jobName;
    }
    public void setJobName(String jobName) {
        this.jobName = jobName;
    }
    public String getJobInfo() {
        return this.jobInfo;
    }
    public void setJobInfo(String jobInfo) {
        this.jobInfo = jobInfo;
    }
    public String getJobType() {
        return this.jobType;
    }
    public void setJobType(String jobType) {
        this.jobType = jobType;
    }
    public String getSchemeId() {
        return schemeId;
    }
    public void setSchemeId(String schemeId) {
        this.schemeId = schemeId;
    }
    public String getSchemeVersion() {
        return schemeVersion;
    }
    public void setSchemeVersion(String schemeVersion) {
        this.schemeVersion = schemeVersion;
    }
    public Date getJobNextTime() {
        return this.jobNextTime;
    }
    public void setJobNextTime(Date jobNextTime) {
        this.jobNextTime = jobNextTime;
    }
    public String getValid() {
        return this.valid;
    }
    public void setValid(String valid) {
        this.valid = valid;
    }
    public Date getRepeatStartTime() {
        return repeatStartTime;
    }
    public void setRepeatStartTime(Date repeatStartTime) {
        this.repeatStartTime = repeatStartTime;
    }
    public Date getRepeatEndTime() {
        return repeatEndTime;
    }
    public void setRepeatEndTime(Date repeatEndTime) {
        this.repeatEndTime = repeatEndTime;
    }
    public Integer getDelayTime() {
        return delayTime;
    }
    public void setDelayTime(Integer delayTime) {
        this.delayTime = delayTime;
    }
    public String getJobCron() {
        return jobCron;
    }
    public void setJobCron(String jobCron) {
        this.jobCron = jobCron;
    }
}

+ 117 - 0
src/main/java/com/yihu/hos/datacollect/model/RsJobDataset.java

@ -0,0 +1,117 @@
package com.yihu.hos.datacollect.model;
/**
 * RsJobDataset entity. @author MyEclipse Persistence Tools
 */
public class RsJobDataset implements java.io.Serializable {
	// Fields
	private String id;
	private String jobId;
	private String jobDatasetId;
	private String jobDatasetName;
	private String jobDatasetKey;
	private String jobDatasetKeytype;
	private String jobDatasetKeyvalue;
	private String jobDatasetCondition;
	private Integer sort;
	// Constructors
	/** default constructor */
	public RsJobDataset() {
	}
	public String getJobDatasetKey() {
		return jobDatasetKey;
	}
	public void setJobDatasetKey(String jobDatasetKey) {
		this.jobDatasetKey = jobDatasetKey;
	}
	public String getJobDatasetKeytype() {
		return jobDatasetKeytype;
	}
	public void setJobDatasetKeytype(String jobDatasetKeytype) {
		this.jobDatasetKeytype = jobDatasetKeytype;
	}
	/** minimal constructor */
	public RsJobDataset(String jobId, String jobDatasetId) {
		this.jobId = jobId;
		this.jobDatasetId = jobDatasetId;
	}
	/** full constructor */
	public RsJobDataset(String jobId, String jobDatasetId, String jobDatasetName, String jobDatasetKeyvalue, String jobDatasetCondition, Integer sort) {
		this.jobId = jobId;
		this.jobDatasetId = jobDatasetId;
		this.jobDatasetName = jobDatasetName;
		this.jobDatasetKeyvalue = jobDatasetKeyvalue;
		this.jobDatasetCondition = jobDatasetCondition;
		this.sort = sort;
	}
	// Property accessors
	public String getId() {
		return this.id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getJobId() {
		return this.jobId;
	}
	public void setJobId(String jobId) {
		this.jobId = jobId;
	}
	public String getJobDatasetId() {
		return this.jobDatasetId;
	}
	public void setJobDatasetId(String jobDatasetId) {
		this.jobDatasetId = jobDatasetId;
	}
	public String getJobDatasetName() {
		return this.jobDatasetName;
	}
	public void setJobDatasetName(String jobDatasetName) {
		this.jobDatasetName = jobDatasetName;
	}
	public String getJobDatasetKeyvalue() {
		return this.jobDatasetKeyvalue;
	}
	public void setJobDatasetKeyvalue(String jobDatasetKeyvalue) {
		this.jobDatasetKeyvalue = jobDatasetKeyvalue;
	}
	public String getJobDatasetCondition() {
		return this.jobDatasetCondition;
	}
	public void setJobDatasetCondition(String jobDatasetCondition) {
		this.jobDatasetCondition = jobDatasetCondition;
	}
	public Integer getSort() {
		return this.sort;
	}
	public void setSort(Integer sort) {
		this.sort = sort;
	}
}

+ 87 - 0
src/main/java/com/yihu/hos/datacollect/model/RsJobLog.java

@ -0,0 +1,87 @@
package com.yihu.hos.datacollect.model;
import java.sql.Timestamp;
import java.util.Date;
/**
 * RsJobLog entity. @author MyEclipse Persistence Tools
 */
public class RsJobLog implements java.io.Serializable {
	// Fields
	private String id;
	private Date jobStartTime;
	private Date jobEndTime;
	private String jobId;
	private String jobContent;
	private Integer jobDatasetCount;
	private Integer jobDatasetSuccess;
	// Constructors
	/** default constructor */
	public RsJobLog() {
	}
	// Property accessors
	public String getId() {
		return this.id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public Date getJobStartTime() {
		return jobStartTime;
	}
	public void setJobStartTime(Date jobStartTime) {
		this.jobStartTime = jobStartTime;
	}
	public Date getJobEndTime() {
		return jobEndTime;
	}
	public void setJobEndTime(Date jobEndTime) {
		this.jobEndTime = jobEndTime;
	}
	public Integer getJobDatasetCount() {
		return jobDatasetCount;
	}
	public void setJobDatasetCount(Integer jobDatasetCount) {
		this.jobDatasetCount = jobDatasetCount;
	}
	public Integer getJobDatasetSuccess() {
		return jobDatasetSuccess;
	}
	public void setJobDatasetSuccess(Integer jobDatasetSuccess) {
		this.jobDatasetSuccess = jobDatasetSuccess;
	}
	public String getJobId() {
		return this.jobId;
	}
	public void setJobId(String jobId) {
		this.jobId = jobId;
	}
	public String getJobContent() {
		return this.jobContent;
	}
	public void setJobContent(String jobContent) {
		this.jobContent = jobContent;
	}
}

+ 191 - 0
src/main/java/com/yihu/hos/datacollect/model/RsJobLogDetail.java

@ -0,0 +1,191 @@
package com.yihu.hos.datacollect.model;
import java.sql.Timestamp;
import java.util.Date;
/**
 * RsJobLogDetail entity. @author MyEclipse Persistence Tools
 */
public class RsJobLogDetail implements java.io.Serializable {
	// Fields
	private String id;
	private Date startTime;
	private Date endTime;
	private String jobLogId;
	private String jobStatus;
	private String jobContent;
	private String datasourceId;
	private String config;
	private String stdDatasetCode;
	private String jobDatasetId;
	private String jobId;
	private String jobDatasetName;
	private String jobSql;
	private Integer jobNum;
	private Date repeatStartTime;
	private Date repeatEndTime;
	private String repeatJobContent;
	private String schemeVersion;
	private Integer jobDatasetRows;
	// Constructors
	/** default constructor */
	public RsJobLogDetail() {
	}
	// Property accessors
	public String getId() {
		return this.id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public Date getStartTime() {
		return this.startTime;
	}
	public void setStartTime(Date startTime) {
		this.startTime = startTime;
	}
	public Date getEndTime() {
		return this.endTime;
	}
	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}
	public String getJobLogId() {
		return jobLogId;
	}
	public void setJobLogId(String jobLogId) {
		this.jobLogId = jobLogId;
	}
	public String getJobStatus() {
		return jobStatus;
	}
	public void setJobStatus(String jobStatus) {
		this.jobStatus = jobStatus;
	}
	public String getJobContent() {
		return this.jobContent;
	}
	public void setJobContent(String jobContent) {
		this.jobContent = jobContent;
	}
	public String getDatasourceId() {
		return datasourceId;
	}
	public void setDatasourceId(String datasourceId) {
		this.datasourceId = datasourceId;
	}
	public String getConfig() {
		return config;
	}
	public void setConfig(String config) {
		this.config = config;
	}
	public String getStdDatasetCode() {
		return stdDatasetCode;
	}
	public void setStdDatasetCode(String stdDatasetCode) {
		this.stdDatasetCode = stdDatasetCode;
	}
	public String getJobDatasetId() {
		return jobDatasetId;
	}
	public void setJobDatasetId(String jobDatasetId) {
		this.jobDatasetId = jobDatasetId;
	}
	public String getJobId() {
		return jobId;
	}
	public void setJobId(String jobId) {
		this.jobId = jobId;
	}
	public String getJobDatasetName() {
		return jobDatasetName;
	}
	public void setJobDatasetName(String jobDatasetName) {
		this.jobDatasetName = jobDatasetName;
	}
	public String getJobSql() {
		return jobSql;
	}
	public void setJobSql(String jobSql) {
		this.jobSql = jobSql;
	}
	public Integer getJobNum() {
		return jobNum;
	}
	public void setJobNum(Integer jobNum) {
		this.jobNum = jobNum;
	}
	public Date getRepeatStartTime() {
		return repeatStartTime;
	}
	public void setRepeatStartTime(Date repeatStartTime) {
		this.repeatStartTime = repeatStartTime;
	}
	public Date getRepeatEndTime() {
		return repeatEndTime;
	}
	public void setRepeatEndTime(Date repeatEndTime) {
		this.repeatEndTime = repeatEndTime;
	}
	public String getRepeatJobContent() {
		return repeatJobContent;
	}
	public void setRepeatJobContent(String repeatJobContent) {
		this.repeatJobContent = repeatJobContent;
	}
	public String getSchemeVersion() {
		return schemeVersion;
	}
	public void setSchemeVersion(String schemeVersion) {
		this.schemeVersion = schemeVersion;
	}
	public Integer getJobDatasetRows() {
		return jobDatasetRows;
	}
	public void setJobDatasetRows(Integer jobDatasetRows) {
		this.jobDatasetRows = jobDatasetRows;
	}
}

+ 586 - 0
src/main/java/com/yihu/hos/datacollect/service/DatacollectManager.java

@ -0,0 +1,586 @@
package com.yihu.hos.datacollect.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.hos.common.Services;
import com.yihu.hos.core.datatype.DateUtil;
import com.yihu.hos.datacollect.dao.DatacollectDao;
import com.yihu.hos.datacollect.model.*;
import com.yihu.hos.resource.model.RsDatasourceDataset;
import com.yihu.hos.resource.service.StdService;
import com.yihu.hos.standard.model.adapter.AdapterDatasetModel;
import com.yihu.hos.standard.model.standard.StdDataSetModel;
import com.yihu.hos.system.service.FlowManager;
import com.yihu.hos.web.framework.model.ActionResult;
import com.yihu.hos.web.framework.model.DataGridResult;
import com.yihu.hos.web.framework.model.DictItem;
import com.yihu.hos.web.framework.model.SimpleChartItem;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service(Services.Datacollect)
public class DatacollectManager{
    public static final String BEAN_ID = Services.Datacollect;
    @Resource(name = DatacollectDao.BEAN_ID)
    private DatacollectDao datacollectDao;
    @Resource(name = StdService.BEAN_ID)
    private StdService stdManager;
    @Resource(name = FlowManager.BEAN_ID)
    private FlowManager flowManage;
    @Autowired
    private ObjectMapper objectMapper;
//    @Autowired
//    private QuartzManager quartzManager;
    /*********************** 任务管理 ****************************************/
    /**
     * 根据JobId获取Cron表达式
     */
    public String getCronByJobId(String jobId) throws Exception {
        return datacollectDao.getCronByJobId(jobId);
    }
    /**
     * 根据ID获取任务详细
     *
     * @return
     */
    public RsJobConfig getJobById(String id) throws Exception {
        return datacollectDao.getEntity(RsJobConfig.class, id);
    }
    /**
     * 获取任务列表
     */
    public DataGridResult getJobList(Map<String, Object> conditionMap, int page, int rows) throws Exception {
        DataGridResult re = datacollectDao.getJobList(conditionMap, page, rows);
        //获取任务列表
        List<RsJobConfig> list = re.getDetailModelList();
        if (list != null && list.size() > 0) {
            List<DtoJobConfig> dtoList = new ArrayList<>();
            for (RsJobConfig job : list) {
                DtoJobConfig dto = new DtoJobConfig();
                dto.setId(job.getId());
                dto.setJobContent(job.getJobContent());
                dto.setJobContentType(job.getJobContentType());
                dto.setJobInfo(job.getJobInfo());
                dto.setJobName(job.getJobName());
                dto.setJobNextTime(job.getJobNextTime());
                //dto.setJobTimeInterval(job.getJobTimeInterval());
                dto.setJobType(job.getJobType());
                dto.setSchemeId(job.getSchemeId());
                dto.setValid(job.getValid());
                //获取版本名称
                String schemeAndVersion = datacollectDao.getSchemeAndVersion(job.getSchemeVersion());
                dto.setSchemeAndVersion(schemeAndVersion);
                //获取关联数据集
                List<RsJobDataset> datasetList = datacollectDao.getJobDataset(job.getId());
                if (datasetList != null && datasetList.size() > 0) {
                    String ds = "";
                    for (RsJobDataset dataset : datasetList) {
                        ds += dataset.getJobDatasetName() + ",";
                    }
                    ds = ds.substring(0, ds.length() - 1);
                    dto.setJobDataset(ds);
                }
//                String cron = datacollectDao.getCronByJobId(job.getId());
                String cron = job.getJobCron();
                String startTime = DateUtil.getUtcDate(job.getJobNextTime());
                ////执行计划翻译
                dto.setJobPlan(translationCron(cron,startTime));
                dtoList.add(dto);
            }
            re.setDetailModelList(dtoList);
        }
        return re;
    }
    /**
     * 根据适配方案获取数据集列表
     */
    public DataGridResult getSchemeDataset(String schemeId, String schemeVersion, String jobId) throws Exception {
        //获取适配数据集总和
        List<AdapterDatasetModel> datasetString = stdManager.getDatasetByScheme(schemeVersion);
        String jsonlist = objectMapper.writeValueAsString(datasetString);
        ArrayNode jsonArray = objectMapper.readValue(jsonlist, ArrayNode.class);
        //获取任务数据集
        List<RsJobDataset> jobDataset = datacollectDao.getJobDataset(jobId);
        DataGridResult re = new DataGridResult();
        List<DtoJobDataset> list = new ArrayList<>();
        for(AdapterDatasetModel jsonItem : datasetString)
        {
            String datasetId= jsonItem.getAdapterDatasetId();
            //配置完整才显示
            if(datasetId.length()>0&&jsonItem.getAdapterDatasetName().length()>0&&jsonItem.getAdapterDatasetName()!="null"&&jsonItem.getAdapterDatasetCode().length()>0&&jsonItem.getAdapterDatasetCode()!="null")
            {
                DtoJobDataset obj = new DtoJobDataset();
                obj.setJobDatasetName(jsonItem.getAdapterDatasetName());
                obj.setJobDatasetCode(jsonItem.getAdapterDatasetCode());
                obj.setJobDatasetId(datasetId);
                // 添加目标表信息  add by hzy add 2018.04.19
                obj.setTargetDataSetName(jsonItem.getStdDatasetName());
                obj.setTargetDataSetCode(jsonItem.getStdDatasetCode());
                obj.setTargetDataSetId(jsonItem.getStdDatasetId().toString());
                //是否关联任务
                if(jobDataset!=null&&jobDataset.size()>0)
                {
                    for(RsJobDataset jd :jobDataset)
                    {
                        if(jd.getJobDatasetId().equals(datasetId))
                        {
                            obj.setId(jd.getId());
                            obj.setJobId(jobId);
                            obj.setJobDatasetKeyvalue(jd.getJobDatasetKeyvalue());
                            obj.setJobDatasetKey(jd.getJobDatasetKey());
                            obj.setJobDatasetKeytype(jd.getJobDatasetKeytype());
                            obj.setChecked("1");
                            obj.setJobDatasetCondition(jd.getJobDatasetCondition());
                            break;
                        }
                    }
                }
                list.add(obj);
            }
        }
        re.setDetailModelList(list);
        return re;
    }
    /**
     * 根据适配方案获取字段列表
     */
    public DataGridResult getSchemeDatasetCol(String schemeId, String schemeVersion, String datasetId) throws Exception {
        //获取适配字段
        List datacolString = stdManager.getDatacolByScheme(schemeVersion, datasetId);
        JSONArray datacolList = JSONArray.fromObject(datacolString);
        DataGridResult re = new DataGridResult();
        List<DtoDatasetCol> list = new ArrayList<>();
        for(Object item : datacolList)
        {
            JSONObject jsonItem = JSONObject.fromObject(item);
            DtoDatasetCol obj = new DtoDatasetCol();
            obj.setCode(jsonItem.getString("adapterMetadataCode"));
            obj.setText(jsonItem.getString("adapterMetadataName"));
            obj.setType(jsonItem.getString("adapterMetadataType"));
            obj.setDict(jsonItem.getString("stdDictId"));
            list.add(obj);
        }
        re.setDetailModelList(list);
        return re;
    }
    /**
     * 根据任务Id获取相关数据集下拉数据
     */
    public DataGridResult getJobDatasetByJobId(String jobId) throws Exception {
        //获取任务数据集
        List<RsJobDataset> jobDataset = datacollectDao.getJobDataset(jobId);
        DataGridResult re = new DataGridResult();
        List<DictItem> list = new ArrayList<>();
        for (RsJobDataset obj : jobDataset) {
            DictItem item = new DictItem();
            item.setValue(obj.getJobDatasetName());
            item.setCode(obj.getJobDatasetId());
            list.add(item);
        }
        re.setDetailModelList(list);
        return re;
    }
    /**
     * 新增任务
     */
    @Transactional
    public ActionResult addJob(RsJobConfig obj, String cron, String jobDataset) throws Exception {
        datacollectDao.saveEntity(obj);//保存任务
        Integer flowId = flowManage.genCamelFile(obj.getId(),obj.getFlowTempId(),cron);
        if (flowId!=null){
            obj.setFlowId(flowId);
            datacollectDao.updateEntity(obj);
            saveJobDataset(obj.getId(), jobDataset);
            return new ActionResult(true, "新增任务成功!");
        }else {
            datacollectDao.deleteEntity(obj);
            return new ActionResult(false, "新增任务失败-关联流程环节失败!");
        }
        //quartz新增任务
//        quartzManager.addJob(obj.getId(), obj.getJobContentType(), obj.getJobContent(), obj.getJobNextTime(), cron);
    }
    /**
     * 修改任务
     */
    @Transactional
    public ActionResult updateJob(RsJobConfig obj, String cron, String jobDataset) throws Exception {
        Integer flowId = flowManage.updateCamelFile(obj.getId(),obj.getFlowTempId(), obj.getFlowId(), cron);
        if (flowId!=null){
            obj.setFlowId(flowId);
            datacollectDao.updateEntity(obj);
            saveJobDataset(obj.getId(), jobDataset);
            //quartz修改cron表达式
//        quartzManager.modifyJob(obj.getId(), obj.getJobContentType(), obj.getJobContent(), obj.getJobNextTime(), cron);
            return new ActionResult(true, "修改成功!");
        }else {
            return new ActionResult(false, "修改失败,关联流程失败!");
        }
    }
    /**
     * 修改任务
     */
    @Transactional
    public ActionResult updateJob(RsJobConfig obj) throws Exception {
        datacollectDao.updateEntity(obj);
        return new ActionResult(true, "修改成功!");
    }
    /**
     * 修改任务状态
     */
    @Transactional
    public ActionResult validJob(String jobId, String valid) throws Exception {
        datacollectDao.validJob(jobId, valid);
        //暂停Quartz任务
        if (valid.equals("0")) {
//            quartzManager.pauseJob(jobId);
        } else { //恢复Quartz任务
//            quartzManager.resumeJob(jobId);
        }
        return new ActionResult(true, "状态修改成功!");
    }
    /**
     * 删除任务
     */
    @Transactional
    public ActionResult deleteJob(String jobId) throws Exception {
        //清空任务关联数据集
        datacollectDao.deleteJobDatasetByJobId(jobId);
        //删除相关流程记录
        RsJobConfig entity = datacollectDao.getEntity(RsJobConfig.class, jobId);
        if (entity.getFlowId()!=null){
           flowManage.deleteFlow(entity.getFlowId());
        }
        datacollectDao.deleteEntity(entity);
        //删除Quartz任务
//        quartzManager.removeJob(jobId);
        return new ActionResult(true, "删除成功!");
    }
    /**
     * 数据集数据源管理列表(包含全部数据集)
     */
    public DataGridResult getDatasetSource(String stdVersion) throws Exception {
        //获取版本下全部数据集
        List<StdDataSetModel> stdDataSetModelList = stdManager.getDatasetByVersion(stdVersion);
        String jsonlist = objectMapper.writeValueAsString(stdDataSetModelList);
        ArrayNode datasetList = objectMapper.readValue(jsonlist, ArrayNode.class);
        //获取已配数据集
        List<RsDatasourceDataset> jobDataset = datacollectDao.getDatasourceDataset(stdVersion);
        DataGridResult re = new DataGridResult();
        List<JsonNode> list = new ArrayList<>();
        for (JsonNode obj : datasetList) {
            ObjectNode dd = objectMapper.createObjectNode();
            dd.put("datasetId", obj.get("id").asText());
            dd.put("datasetCode", obj.get("code").asText());
            dd.put("datasetName", obj.get("name").asText());
            dd.put("stdVersion", stdVersion);
            if (jobDataset != null && jobDataset.size() > 0) {
                for (RsDatasourceDataset rdd : jobDataset) {
                    if (rdd.getDatasetId().equals(obj.get("id").asText())) {
                        dd.put("orgId", rdd.getOrgId());
                        dd.put("datasourceId", rdd.getDatasourceId());
                        dd.put("id", rdd.getId());
                        break;
                    }
                }
            }
            list.add(dd);
        }
        re.setDetailModelList(list);
        return re;
    }
    /**
     * 保存数据集数据源配置
     */
    @Transactional
    public ActionResult saveDatasetSource(String json) throws Exception {
        //TODO: Use jackson
        JSONArray jsonList = JSONArray.fromObject(json);
        for (Object item : jsonList) {
            JSONObject obj = JSONObject.fromObject(item);
            if (obj.containsKey("id") && obj.getString("id").length() > 0) {
                String id = obj.getString("id");
                //修改
                RsDatasourceDataset dd = (RsDatasourceDataset) JSONObject.toBean(obj, RsDatasourceDataset.class);
                datacollectDao.updateEntity(dd);
//                if(obj.containsKey("datasourceId") && obj.getString("datasourceId").length()>0)
//                {
//                    RsDatasourceDataset dd = (RsDatasourceDataset)JSONObject.toBean(obj,RsDatasourceDataset.class);
//                    datacollectDao.updateEntity(dd);
//                }
//                //删除
//                else{
//                    datacollectDao.deleteEntity(RsDatasourceDataset.class,id);
//                }
            } else {
                //新增
                RsDatasourceDataset dd = (RsDatasourceDataset) JSONObject.toBean(obj, RsDatasourceDataset.class);
                datacollectDao.saveEntity(dd);
            }
        }
        return new ActionResult(true, "保存成功!");
    }
    /************************* 数据集数据源管理 ***************************************************/
    /**
     * 获取任务详细日志列表
     */
    public DataGridResult getJobLogDetail(Map<String, Object> conditionMap, int page, int rows) throws Exception {
        return datacollectDao.getJobLogDetail(conditionMap, page, rows);
    }
    /**
     * 获取任务日志列表
     */
    public DataGridResult getJobLog(Map<String, Object> conditionMap, int page, int rows) throws Exception {
        DataGridResult re = datacollectDao.getJobLog(conditionMap, page, rows);
        List<RsJobLog> logList = re.getDetailModelList();
        List<DtoJobLog> list = new ArrayList<>();
        for (RsJobLog log : logList) {
            DtoJobLog dto = new DtoJobLog();
            BeanUtils.copyProperties(log, dto);
            List<Map<String, Object>> maps = datacollectDao.getJobLogCount(log.getId());
            if (maps != null && maps.size() > 0) {
                int count = Integer.parseInt(String.valueOf(maps.get(0).get("count")));
                int success = Integer.parseInt(String.valueOf(maps.get(0).get("success")));
                int repeat_num = Integer.parseInt(String.valueOf(maps.get(0).get("repeat_num")));
                dto.setCount(count);
                dto.setSuccess(success);
                dto.setRepeatNum(repeat_num);
            } else {
                dto.setCount(0);
                dto.setSuccess(0);
                dto.setRepeatNum(0);
            }
            list.add(dto);
        }
        re.setDetailModelList(list);
        return re;
    }
    /********************** 任务日志管理 *******************************************/
    /**
     * 任务详细根据数据集分组
     *
     * @return
     */
    public DataGridResult getJobLogDataset(String logId) throws Exception {
        DataGridResult re = new DataGridResult();
        List<SimpleChartItem> maps = datacollectDao.getJobLogDataset(logId);
        re.setDetailModelList(maps);
        return re;
    }
    /**
     * 翻译Cron表达式
     *
     * @return
     */
    private String translationCron(String cron,String startTime) {
        try {
            if (cron != null && cron.length() > 0) {
                String re = "";
                String[] items = cron.split(" ");
                if (!items[5].equals("?")) //周
                {
                    String[] weekDay = items[5].split(",");
                    for (String day : weekDay) {
                        String WeekDay = day;
                        if (day.equals("1")) {
                            WeekDay = "日";
                        } else if (day.equals("2")) {
                            WeekDay = "一";
                        } else if (day.equals("3")) {
                            WeekDay = "二";
                        } else if (day.equals("4")) {
                            WeekDay = "三";
                        } else if (day.equals("5")) {
                            WeekDay = "四";
                        } else if (day.equals("6")) {
                            WeekDay = "五";
                        } else if (day.equals("7")) {
                            WeekDay = "六";
                        }
                        re += "星期" + WeekDay + ",";
                    }
                    re = re.substring(0, re.length() - 1);
                } else {
                    if (!items[4].equals("*")) {
                        String v = items[4];
                        if (v.indexOf('/') > 0)
                        {
                            //月不为通配-周期
                            if (v.equals("1")) {
                                re = "每月第一天";
                            } else if (v.equals("L")) {
                                re = "每月最后一天";
                            } else {
                                re = "每月第" + v + "天";
                            }
                        } else {
                            //月不为通配-指定月,并判断时分
                             v = items[3];
                            if(v.indexOf('/')>0) //天
                            {
                                String[] varry = v.split("/");
                                re = "每隔" + varry[1] + "天";
                            }else {
                                //设置时分
                                String v1 = items[1];
                                String v2 = items[2];
                                if (v1.indexOf('/') > 0) //分
                                {
                                    String[] varry = v1.split("/");
                                    re = "每隔" + varry[1] + "分";
                                } else { //时
                                    String[] varry = v2.split("/");
                                    re = "每隔" + varry[1] + "时";
                                }
                            }
                        }
                    } else {
                        String v1 = items[1];
                        String v2 = items[2];
                        if (v1.indexOf('/') > 0) //分
                        {
                            String[] varry = v1.split("/");
                            re = "每隔" + varry[1] + "分";
                        } else { //时
                            String[] varry = v2.split("/");
                            re = "每隔" + varry[1] + "时";
                        }
                    }
                }
                return re + "执行一次,首次执行:"+startTime;
            }
            return cron;
        } catch (Exception ex) {
            ex.printStackTrace();
            return cron;
        }
    }
    /**
     * 保存任务关联数据集
     */
    private void saveJobDataset(String jobId, String jobDataset) throws Exception {
        if(jobDataset!=null&&jobDataset.length()>0) {
            //清空任务关联数据集
            datacollectDao.deleteJobDatasetByJobId(jobId);
            ArrayNode array = objectMapper.readValue(jobDataset,ArrayNode.class);
            if (array != null && array.size() > 0) {
                for (JsonNode obj : array) {
                    RsJobDataset rs = new RsJobDataset();
                    if(obj.get("jobDatasetCondition")!=null&&obj.get("jobDatasetCondition").asText()!="null")
                    {
                        rs.setJobDatasetCondition(obj.get("jobDatasetCondition").asText());
                    }
                    if(obj.get("jobDatasetId")!=null&&obj.get("jobDatasetId").asText()!="null") {
                        rs.setJobDatasetId(obj.get("jobDatasetId").asText());
                    }
                    if(obj.get("jobDatasetKey")!=null&&obj.get("jobDatasetKey").asText()!="null") {
                        rs.setJobDatasetKey(obj.get("jobDatasetKey").asText());
                    }
                    if(obj.get("jobDatasetKeytype")!=null&&obj.get("jobDatasetKeytype").asText()!="null") {
                        rs.setJobDatasetKeytype(obj.get("jobDatasetKeytype").asText());
                    }
                    if(obj.get("jobDatasetKeyvalue")!=null&&obj.get("jobDatasetKeyvalue").asText()!="null") {
                        rs.setJobDatasetKeyvalue(obj.get("jobDatasetKeyvalue").asText());
                    }
                    if(obj.get("jobDatasetName")!=null&&obj.get("jobDatasetName").asText()!="null") {
                        rs.setJobDatasetName(obj.get("jobDatasetName").asText());
                    }
                    rs.setJobId(jobId);
                    datacollectDao.saveEntity(rs);
                }
            }
        }
        else{
            return;
        }
    }
}

+ 21 - 0
src/main/java/com/yihu/hos/datacollect/service/JobConfigService.java

@ -0,0 +1,21 @@
package com.yihu.hos.datacollect.service;
import com.yihu.hos.datacollect.dao.JobConfigDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * @author Airhead
 * @created 2018-04-03
 */
@Service
public class JobConfigService {
    @Autowired
    private JobConfigDao jobConfigDao;
    public List getData(String lastUpdate) {
        return jobConfigDao.getData(lastUpdate);
    }
}

+ 21 - 0
src/main/java/com/yihu/hos/datacollect/service/JobDataSetService.java

@ -0,0 +1,21 @@
package com.yihu.hos.datacollect.service;
import com.yihu.hos.datacollect.dao.JobDataSetDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * @author Airhead
 * @created 2018-04-03
 */
@Service
public class JobDataSetService {
    @Autowired
    private JobDataSetDao jobDataSetDao;
    public List getData(String lastUpdate) {
        return jobDataSetDao.getData(lastUpdate);
    }
}

+ 233 - 0
src/main/java/com/yihu/hos/ehr/standard/cdatype/controller/CdaTypeEndPoint.java

@ -0,0 +1,233 @@
package com.yihu.hos.ehr.standard.cdatype.controller;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.util.id.BizObject;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.hos.common.controller.EnvelopRestEndPoint;
import com.yihu.hos.model.standard.MCDAType;
import com.yihu.hos.standard.model.CDAType;
import com.yihu.hos.standard.service.cdatype.CDATypeManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/**
 * Created by linAZ
 */
@RequestMapping(ApiVersion.Version1_0)
@RestController
@Api(value = "CDA Type", description = "CDA类别服务")
public class CdaTypeEndPoint extends EnvelopRestEndPoint {
    @Autowired
    private CDATypeManager cdaTypeManager;
    @RequestMapping(value = ServiceApi.Standards.TypeChildren, method = RequestMethod.GET)
    @ApiOperation(value = "根据父级ID获取下级")
    public List<MCDAType> getChildrenByPatientId(
            @ApiParam(name = "id", value = "父级id",defaultValue = "")
            @RequestParam(value = "id",required = false) String parentId) throws Exception {
        List<CDAType> listType = cdaTypeManager.getChildrenCDATypeByParentId(parentId);
        return (List<MCDAType>)convertToModels(listType,new ArrayList<MCDAType>(listType.size()),MCDAType.class,"");
    }
    @RequestMapping(value = ServiceApi.Standards.TypesChildren, method = RequestMethod.GET)
    @ApiOperation(value = "根据父级类别获取父级类别所在以下所有子集类别(包括当前父级列表)")
    public List<MCDAType> getChildIncludeSelfByParentIdsAndKey(
            @ApiParam(name = "patient_ids", value = "父级id")
            @RequestParam(value = "patient_ids") String[] patientIds,
            @ApiParam(name = "key", value = "查询条件")
            @RequestParam(value = "key") String key) throws Exception {
        List<CDAType> parentTypes = cdaTypeManager.getCDATypeByIds(patientIds);
        String childrenIds = getChildIncludeSelfByParentsAndChildrenIds(parentTypes,"");   //递归获取
        if(childrenIds.length()>0) {
            childrenIds = childrenIds.substring(0, childrenIds.length() - 1);
        }
        List<CDAType> cdaTypeList = cdaTypeManager.getChildrenType(childrenIds,key);
        return  (List<MCDAType>)convertToModels(cdaTypeList,new ArrayList<MCDAType>(cdaTypeList.size()),MCDAType.class,"");
    }
//    @RequestMapping(value = ServiceApi.Standards.TypeList,method = RequestMethod.GET)
//    @ApiOperation(value = "根据code或者name获取CDAType列表")
//    public List<MCDAType> getCdaTypeByCodeOrName(
//            @ApiParam(name = "code", value = "代码")
//            @RequestParam(value = "code") String code,
//            @ApiParam(name = "name", value = "名称")
//            @RequestParam(value = "name") String name) {
//
//        List<CDAType> cdaTypeList = cdaTypeManager.GetCdaTypeByCodeOrName(code,name);
//        return  (List<MCDAType>)convertToModels(cdaTypeList,new ArrayList<MCDAType>(cdaTypeList.size()),MCDAType.class,"");
//    @RequestMapping(value = "/cda_types/ids/{ids}",method = RequestMethod.GET)
//    @ApiOperation(value = "根据ids获取CDAType列表")
//    public List<MCDAType> getCdaTypeByIds(
//            @ApiParam(name = "ids", value = "ids")
//            @RequestParam(value = "ids") String[] ids) {
//
//        List<CDAType> cdaTypeList = cdaTypeManager.getCDATypeByIds(ids);
//        return (List<MCDAType>)convertToModels(cdaTypeList,new ArrayList<MCDAType>(cdaTypeList.size()),MCDAType.class,"");
//    }
    @RequestMapping(value = ServiceApi.Standards.Types, method = RequestMethod.GET)
    @ApiOperation(value = "标准类别分页搜索")
    public Collection<MCDAType> searchType(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,secret,url,createTime")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List list = cdaTypeManager.search(fields, filters, sorts, page, size);
        pagedResponse(request, response, cdaTypeManager.getCount(filters), page, size);
        return convertToModels(list, new ArrayList<>(list.size()), MCDAType.class, fields);
    }
    @RequestMapping(value = ServiceApi.Standards.NoPageTypes, method = RequestMethod.GET)
    @ApiOperation(value = "标准字典不分页搜索")
    public List<MCDAType> searchSourcesWithoutPaging(
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters) throws Exception {
        List<CDAType> cdaTypes = cdaTypeManager.search(filters);
        return (List<MCDAType>) convertToModels(cdaTypes, new ArrayList<MCDAType>(cdaTypes.size()), MCDAType.class, "");
    }
    @RequestMapping(value = ServiceApi.Standards.Type, method = RequestMethod.GET)
    @ApiOperation(value = "根据id获取CDAType")
    public MCDAType getCdaTypeById(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id") String id) throws Exception {
        CDAType cdaType = cdaTypeManager.getCdaTypeById(id);
        return convertToModel(cdaType,MCDAType.class);
    }
    @RequestMapping(value = ServiceApi.Standards.Types, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "新增CDAType")
    public MCDAType saveCDAType(
            @ApiParam(name = "model", value = "model")
            @RequestBody String jsonData) throws Exception {
        CDAType cdaType =  toEntity(jsonData, CDAType.class);
        cdaType.setId(getObjectId(BizObject.CdaType));
        cdaType.setCreateDate(new Date());
        cdaType = cdaTypeManager.save(cdaType);
        return convertToModel(cdaType,MCDAType.class);
    }
    @RequestMapping(value = ServiceApi.Standards.Type,method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改CDAType")
    public MCDAType updateCDAType(
            @ApiParam(name = "id", value = "编号")
            @RequestParam(value = "id") String id,
            @ApiParam(name = "model", value = "json模型")
            @RequestBody String jsonData) throws Exception {
        CDAType cdaType =  toEntity(jsonData, CDAType.class);
        cdaType.setUpdateDate(new Date());
        cdaType.setId(id);
        cdaType = cdaTypeManager.update(cdaType);
        return convertToModel(cdaType,MCDAType.class);
    }
    @RequestMapping(value = ServiceApi.Standards.TypesCodeExistence , method = RequestMethod.GET)
    @ApiOperation(value = "判断提交的机构代码是否已经存在")
    public boolean isCDATypeExists(
            @ApiParam(name = "code", value = "code", defaultValue = "")
            @RequestParam(value = "code") String code){
        return cdaTypeManager.isCodeExist(code);
    }
    /**
     * 删除CDA类别,若该类别存在子类别,将一并删除子类别
     * 先根据当前的类别ID获取全部子类别ID,再进行删除
     */
    @RequestMapping(value = ServiceApi.Standards.Types, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除CDA类别,若该类别存在子类别,将一并删除子类别")
    public boolean deleteCDATypeByPatientIds(
            @ApiParam(name = "ids", value = "ids")
            @RequestParam(value = "ids") String[] ids) {
        List<CDAType> parentTypes = cdaTypeManager.getCDATypeByIds(ids);
        String childrenIds = getChildIncludeSelfByParentsAndChildrenIds(parentTypes, "");
        if(childrenIds.length()>0) {
            childrenIds = childrenIds.substring(0, childrenIds.length() - 1);
        }
        return cdaTypeManager.deleteCdaType(childrenIds);
    }
    @RequestMapping(value = ServiceApi.Standards.TypeOther, method = RequestMethod.GET)
    @ApiOperation(value = "获取cdaType列表(不包含本身)")
    public List<MCDAType> getOtherCDAType(
            @ApiParam(name = "id", value = "cdaType编号")
            @PathVariable(value = "id") String id) throws Exception {
        List<CDAType> listType = cdaTypeManager.getOtherCDAType(id);
        return (List<MCDAType>)convertToModels(listType,new ArrayList<MCDAType>(listType.size()),MCDAType.class,"");
    }
    @RequestMapping(value = ServiceApi.Standards.TypeParent, method = RequestMethod.GET)
    @ApiOperation(value = "根据当前类别获取自己的父级以及同级以及同级所在父级类别列表")
    public List<MCDAType> getCdaTypeExcludeSelfAndChildren(
            @ApiParam(name = "id", value = "id")
            @RequestParam(value = "id") String id) throws Exception {
        List<CDAType> parentTypes = cdaTypeManager.getCDATypeByIds(new String[]{id});
        String childrenIds = getChildIncludeSelfByParentsAndChildrenIds(parentTypes,"");   //递归获取
        List<CDAType> cdaTypes = cdaTypeManager.getCdaTypeExcludeSelfAndChildren(childrenIds);
        return  (List<MCDAType>)convertToModels(cdaTypes,new ArrayList<MCDAType>(cdaTypes.size()),MCDAType.class,"");
    }
    /**
     * 根据父级类别获取父级类别所在以下所有子集类别(包括当前父级列表)
     * @param parentTypes 父级信息
     * @param childrenIds   子级ID
     */
    public String getChildIncludeSelfByParentsAndChildrenIds(List<CDAType> parentTypes,String childrenIds) {
        for (int i = 0; i < parentTypes.size(); i++) {
            CDAType typeInfo = parentTypes.get(i);
            childrenIds+=typeInfo.getId()+",";
            List<CDAType> listChild = cdaTypeManager.getChildrenCDATypeByParentId(typeInfo.getId());
            if(listChild.size()>0){
                childrenIds = getChildIncludeSelfByParentsAndChildrenIds(listChild,childrenIds);
            }
        }
        return childrenIds;
    }
}

+ 229 - 0
src/main/java/com/yihu/hos/ehr/standard/cdaversion/controller/VersionEndPoint.java

@ -0,0 +1,229 @@
package com.yihu.hos.ehr.standard.cdaversion.controller;
import com.yihu.hos.common.controller.ExtendEndPoint;
import com.yihu.hos.core.constants.MicroServices;
import com.yihu.hos.core.constants.ServiceApi;
import com.yihu.hos.model.standard.MSTDVersion;
import com.yihu.hos.standard.model.standard.STDVersion;
import com.yihu.hos.standard.service.standard.STDVersionService;
import com.yihu.hos.web.framework.constant.ErrorCode;
import com.yihu.hos.web.framework.exception.EsbApiException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/**
 * @author lincl
 * @version 1.0
 * @created 2016.2.3
 */
@RestController
@RequestMapping(MicroServices.ApiVersion.Version1_0)
@Api(value = "version", description = "版本服务")
public class VersionEndPoint extends ExtendEndPoint<MSTDVersion> {
    @Autowired
    private STDVersionService versionService;
//    @Autowired
//    private DispatchService dispatchService;
    protected EsbApiException errNotFound(String version) {
        return errNotFound("标准版本", version);
    }
    private STDVersion findVersion(String version) throws ParseException {
        STDVersion cdaVersion = versionService.getVersion(version);
        if (cdaVersion == null)
            throw errNotFound(version);
        return cdaVersion;
    }
    private STDVersion findVersionInstage(String version) throws ParseException {
        STDVersion cdaVersion = findVersion(version);
        if (!cdaVersion.isInStage()) {
            throw new EsbApiException(ErrorCode.InValidCDAVersionStage);
        }
        return cdaVersion;
    }
    @RequestMapping(value = ServiceApi.Standards.Versions, method = RequestMethod.GET)
    @ApiOperation(value = "适配采集标准")
    public Collection<MSTDVersion> searchCDAVersions(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "version,versionName,commitTime,baseVersion,inStage")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+version")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List versions = versionService.search(fields, filters, sorts, page, size);
        Long dataSetInt = versionService.getCount(filters);
        pagedResponse(request, response, dataSetInt, page, size);
        return convertToModels(versions, new ArrayList<>(versions.size()), MSTDVersion.class, fields);
    }
    @RequestMapping(value = ServiceApi.Standards.VersionLatestExistence, method = RequestMethod.GET)
    @ApiOperation(value = "判断是否最新版本")
    public boolean isLatestVersion(
            @ApiParam(name = "version", value = "版本号", defaultValue = "")
            @PathVariable(value = "version") String version) throws Exception {
        STDVersion cdaVersion = versionService.getLatestVersion();
        String latestVersion = cdaVersion.getVersion();
        return latestVersion != null && latestVersion.equals(version);
    }
    //新增标准版本的最新版本信息
    @RequestMapping(value = ServiceApi.Standards.Versions, method = RequestMethod.POST)
    @ApiOperation(value = "新增cda版本")
    public MSTDVersion addVersion(
            @ApiParam(name = "userLoginCode", value = "用户登录名")
            @RequestParam(value = "userLoginCode") String userLoginCode) throws Exception {
        STDVersion baseVersion = versionService.getLatestVersion();
        STDVersion xcdaVersion = versionService.createStageVersion(baseVersion, userLoginCode);
        if (xcdaVersion != null)
            return getModel(xcdaVersion);
        return null;
    }
    @RequestMapping(value = ServiceApi.Standards.Version, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除版本")
    public boolean dropCDAVersion(
            @ApiParam(name = "version", value = "版本号", defaultValue = "")
            @PathVariable(value = "version") String version) throws Exception {
        versionService.dropVersion(findVersion(version));
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.VersionRevert, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除编辑状态的版本")
    public boolean revertVersion(
            @ApiParam(name = "version", value = "版本号", defaultValue = "")
            @PathVariable(value = "version") String version) throws Exception {
        versionService.revertVersion(findVersionInstage(version));
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.VersionCommit, method = RequestMethod.PUT)
    @ApiOperation(value = "发布新版本")
    public boolean commitVersion(
            @ApiParam(name = "version", value = "版本号", defaultValue = "")
            @PathVariable(value = "version") String version) throws Exception {
        STDVersion cdaVersion = findVersionInstage(version);
//        Map<String, Object> mapResult = dispatchService.createFullVersionFile(cdaVersion.getVersion());
//        if (mapResult == null) return false;
        versionService.commitVersion(cdaVersion);
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.VersionBackStage, method = RequestMethod.PUT)
    @ApiOperation(value = "将最新的已发布版本回滚为编辑状态")
    public boolean rollbackToStage(
            @ApiParam(name = "version", value = "版本号", defaultValue = "")
            @PathVariable(value = "version") String version) throws Exception {
        STDVersion cdaVersion = versionService.getVersion(version);
        versionService.rollbackToStage(cdaVersion);
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.Version, method = RequestMethod.PUT)
    @ApiOperation(value = "修改版本信息")
    public MSTDVersion updateVersion(
            @ApiParam(name = "version", value = "版本号", defaultValue = "")
            @PathVariable(value = "version") String version,
            @ApiParam(name = "versionName", value = "版本名称", defaultValue = "")
            @RequestParam(value = "versionName") String versionName,
            @ApiParam(name = "userCode", value = "操作者", defaultValue = "")
            @RequestParam(value = "userCode") String userCode,
            @ApiParam(name = "inStage", value = "编辑状态", defaultValue = "")
            @RequestParam(value = "inStage") int inStage,
            @ApiParam(name = "baseVersion", value = "父版本", defaultValue = "")
            @RequestParam(value = "baseVersion") String baseVersion) throws Exception {
        STDVersion cdaVersion = findVersion(version);
        cdaVersion.setVersionName(versionName);
        cdaVersion.setAuthor(userCode);
        cdaVersion.setCommitTime(new Date());
        cdaVersion.setInStage(inStage == 1);
        cdaVersion.setBaseVersion(baseVersion);
        versionService.saveEntity(cdaVersion);
        return getModel(cdaVersion);
    }
    @RequestMapping(value = ServiceApi.Standards.VersionNameExistence, method = RequestMethod.GET)
    @ApiOperation(value = "判断版本名称是否已存在")
    public boolean checkVersionName(
            @ApiParam(name = "versionName", value = "版本名称", defaultValue = "")
            @RequestParam(value = "versionName") String versionName) throws Exception {
        int num = versionService.checkVersionName(versionName);
        return num > 0;
    }
    @RequestMapping(value = ServiceApi.Standards.VersionInStageExist, method = RequestMethod.GET)
    @ApiOperation(value = "检查是否存在处于编辑状态的版本")
    public boolean existInStage() throws Exception {
        int num = versionService.searchInStage();
        return num > 0;
    }
    @RequestMapping(value = ServiceApi.Standards.Version, method = RequestMethod.GET)
    @ApiOperation(value = "获取版本信息")
    public MSTDVersion getVersion(
            @ApiParam(name = "version", value = "版本号", defaultValue = "")
            @PathVariable(value = "version") String version) throws Exception {
        STDVersion cdaVersion = versionService.getVersion(version);
        return getModel(cdaVersion);
    }
    @RequestMapping(value = ServiceApi.Standards.VersionCache, method = RequestMethod.PUT)
    @ApiOperation(value = "向Redis中缓存标准数据")
    public void cache(
            @ApiParam(name = "version", value = "版本号", defaultValue = "")
            @PathVariable(value = "version") String version) {
    }
    @RequestMapping(value = ServiceApi.Standards.VersionLatest, method = RequestMethod.GET)
    @ApiOperation(value = "获取最新版本")
    public MSTDVersion getLatestVersion()throws Exception {
        STDVersion cdaVersion = versionService.getLatestVersion();
        return getModel(cdaVersion);
    }
}

+ 208 - 0
src/main/java/com/yihu/hos/ehr/standard/datasets/controller/DataSetEndPoint.java

@ -0,0 +1,208 @@
package com.yihu.hos.ehr.standard.datasets.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yihu.hos.common.controller.ExtendEndPoint;
import com.yihu.hos.core.constants.MicroServices;
import com.yihu.hos.core.constants.ServiceApi;
import com.yihu.hos.model.standard.MStdDataSet;
import com.yihu.hos.standard.model.standard.StdDataSetModel;
import com.yihu.hos.standard.service.standard.StdDatasetService;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.model.standard.StandardVersion;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
 * @author lincl
 * @version 1.0
 * @created 2016.2.15
 */
@RestController
@RequestMapping(MicroServices.ApiVersion.Version1_0)
@Api(value = "Dataset", description = "数据集服务")
public class DataSetEndPoint extends ExtendEndPoint<MStdDataSet> {
    @Autowired
    private StdDatasetService dataSetService;
    @RequestMapping(value = ServiceApi.Standards.DataSets, method = RequestMethod.GET)
    @ApiOperation(value = "查询数据集的方法")
    public Collection<MStdDataSet> searchDataSets(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        List ls = dataSetService.searchPage(StdDataSetModel.class, StandardVersion.DataSetTable,version, filters, sorts, page, size,true);
        List all = dataSetService.searchPage(StdDataSetModel.class, StandardVersion.DataSetTable, version, filters, sorts, null, null,true);
        long total = Long.valueOf(all.size());
        pagedResponse(request, response, total, page, size);
        return convertToModels(ls, new ArrayList<>(ls.size()), MStdDataSet.class, fields);
    }
    @RequestMapping(value = ServiceApi.Standards.NoPageDataSets, method = RequestMethod.GET)
    @ApiOperation(value = "标准数据集不分页搜索")
    public Collection<MStdDataSet> searchSourcesWithoutPaging(
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception {
        List dataSetList = dataSetService.searchVersionData(StdDataSetModel.class,version,StandardVersion.DataSetTable,filters);
        return convertToModels(dataSetList, new ArrayList<>(dataSetList.size()), MStdDataSet.class, "");
    }
    @RequestMapping(value = ServiceApi.Standards.DataSet, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除数据集信息")
    public boolean deleteDataSet(
            @ApiParam(name = "id", value = "数据集编号", defaultValue = "")
            @PathVariable(value = "id") long id,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception{
        dataSetService.delete(version,id);
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.DataSets, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除数据集信息")
    public boolean deleteDataSet(
            @ApiParam(name = "ids", value = "数据集编号", defaultValue = "")
            @RequestParam(value = "ids") String ids,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception{
        if(StringUtils.isNotEmpty(ids)){
            for(String id:ids.split(",")){
                Long id_ = Long.valueOf(id);
                dataSetService.delete(version,id_);
            }
        }
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.DataSet, method = RequestMethod.GET)
    @ApiOperation(value = "获取数据集信息")
    public MStdDataSet getDataSet(
            @ApiParam(name = "id", value = "数据集编号", defaultValue = "")
            @PathVariable(value = "id") long id,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version) {
        StandardVersion ver = new StandardVersion(version);
        return getModel(dataSetService.retrieve(StdDataSetModel.class,ver.getDataSetTableName() ,id));
    }
    @RequestMapping(value = ServiceApi.Standards.DataSetsIds, method = RequestMethod.GET)
    @ApiOperation(value = "根据数据集ids(用逗号隔开)获取数据集信息")
    public Collection<MStdDataSet> getDataSets(
            @ApiParam(name = "ids", value = "数据集编号", defaultValue = "")
            @PathVariable(value = "ids") String ids,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version) throws IOException {
        List<StdDataSetModel> list = dataSetService.searchVersionData(StdDataSetModel.class,version,StandardVersion.DataSetTable, "id="+ids);
        return convertToModels(list, new ArrayList<>(list.size()), MStdDataSet.class, "");
    }
    @RequestMapping(value = ServiceApi.Standards.DataSets, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "新增数据集信息")
    public MStdDataSet saveDataSet(
            @ApiParam(name = "version", value = "标准版本", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "model", value = "json数据模型", defaultValue = "")
            @RequestBody String model) throws Exception{
        StdDataSetModel dataSet =  jsonToObj(model, StdDataSetModel.class);
        Result result = dataSetService.add(version, model);
        if(result.isSuccessFlg()){
            return getModel(dataSet);
        }
        return null;
    }
    @RequestMapping(value = ServiceApi.Standards.DataSet, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改数据集信息")
    public MStdDataSet updateDataSet(
            @ApiParam(name = "version", value = "标准版本", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "id", value = "数据集编号", defaultValue = "")
            @PathVariable(value = "id") long id,
            @ApiParam(name = "model", value = "json数据模型", defaultValue = "")
            @RequestBody String model) throws Exception{
        StdDataSetModel dataSetModel =  jsonToObj(model, StdDataSetModel.class);
//        StdDataSetModel dataSet = dataSetService.retrieve(id, entityClass);
//        if(!dataSet.getInnerCode().equals(dataSetModel.getInnerCode())){
//            if(dataSetService.isExistByField("code", dataSetModel.getInnerCode(), entityClass))
//                throw new ApiException(ErrorCode.RapeatDataSetCode, "代码重复!");
//        }
        dataSetModel.setId(id);
        Result result = dataSetService.update(version, toJson(dataSetModel));
        if(result.isSuccessFlg()){
            return getModel(dataSetModel);
        }
        return null;
    }
    @RequestMapping(value = ServiceApi.Standards.DataSetsName, method = RequestMethod.GET)
    @ApiOperation(value = "获取数据集 id-name : map集")
    public Map<Long,String> getDataSetMapByIds(
            @ApiParam(name = "version", value = "版本号", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "ids", value = "数据集编号", defaultValue = "")
            @RequestParam(value = "ids",required = false) String ids) throws Exception{
        return dataSetService.getDataSetMapByIds(ids==null || ids.trim().length()==0? new String[]{} : ids.split(","), version);
    }
    @RequestMapping(value = ServiceApi.Standards.DataSetCodeIsExist,method = RequestMethod.GET)
    public boolean isExistCode(
            @RequestParam(value = "code")String code,
            @RequestParam(value = "version_code")String versionCode) throws IOException {
        return dataSetService.isExistByField(StdDataSetModel.class,versionCode,StandardVersion.DataSetTable,"code", code);
    }
    @RequestMapping(value = ServiceApi.Standards.DataSetsBatch, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "批量创建标准数据集以及数据元", notes = "批量创建标准数据集以及数据元")
    public boolean createDictAndEntries(
            @RequestParam(value = "version") String version,
            @RequestBody String jsonData) throws Exception {
        List models = objectMapper.readValue(jsonData, new TypeReference<List>() {});
        dataSetService.batchInsertDictsAndEntry(models, version);
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.AdaptMeta, method = RequestMethod.GET)
    @ApiOperation(value = "获取ehr适配的数据元", notes = "获取ehr适配的数据元")
    public List<Map<String, Object>> getEhrAdapterMetadata( @RequestParam(value = "version")String version){
        return dataSetService.getEhrAdapterMetadata(version);
    }
}

+ 324 - 0
src/main/java/com/yihu/hos/ehr/standard/datasets/controller/MetaDataEndPoint.java

@ -0,0 +1,324 @@
package com.yihu.hos.ehr.standard.datasets.controller;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.hos.common.controller.ExtendEndPoint;
import com.yihu.hos.crawler.model.standard.StdMetaData;
import com.yihu.hos.model.standard.MStdMetaData;
import com.yihu.hos.standard.model.standard.StdDataSetModel;
import com.yihu.hos.standard.model.standard.StdDictionaryModel;
import com.yihu.hos.standard.model.standard.StdMetaDataModel;
import com.yihu.hos.standard.service.standard.StdDatasetService;
import com.yihu.hos.standard.service.standard.StdDictService;
import com.yihu.hos.standard.service.standard.StdMetadataService;
import com.yihu.hos.web.framework.model.standard.StandardVersion;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.*;
/**
 * @author lincl
 * @version 1.0
 * @created 2016.2.3
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "Meta data", description = "数据元服务")
public class MetaDataEndPoint extends ExtendEndPoint<MStdMetaData> {
    @Autowired
    private StdMetadataService metaDataService;
    @RequestMapping(value = ServiceApi.Standards.MetaDatas, method = RequestMethod.GET)
    @ApiOperation(value = "查询数据元")
    public Collection<MStdMetaData> searchMetaDatas(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List ls;
        if (size == -1){
            ls = metaDataService.searchVersionData(StdMetaDataModel.class, version, StandardVersion.MetaDataTable, filters);
        } else {
            ls = metaDataService.searchPage(StdMetaDataModel.class,  StandardVersion.MetaDataTable,version, filters, sorts, page, size,true);
            List all = metaDataService.searchPage(StdMetaDataModel.class, StandardVersion.MetaDataTable, version, filters, sorts, null, null,true);
            long total = Long.valueOf(all.size());
            pagedResponse(request, response, total, page, size);
        }
        return convertToModels(ls, new ArrayList<>(ls.size()), MStdMetaData.class, fields);
    }
    @RequestMapping(value = ServiceApi.Standards.MetaDatas, method = RequestMethod.DELETE)
    @ApiOperation(value = "批量删除数据元")
    public boolean deleteMetaDatas(
            @ApiParam(name = "ids", value = "编号集", defaultValue = "")
            @RequestParam(value = "ids") String ids,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception {
        metaDataService.delete(StdMetaDataModel.class, strToLongArr(ids), StandardVersion.MetaDataTable, version);
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.MetaDatasWithDataSet, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除数据集关联的数据元")
    public boolean deleteMetaDataByDataSet(
            @ApiParam(name = "data_set_id", value = "数据集编号", defaultValue = "")
            @PathVariable(value = "data_set_id") long dataSetId,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception {
        return metaDataService.deleteByField("dataSetId", new Object[]{dataSetId}, StandardVersion.MetaDataTable, version);
    }
    @RequestMapping(value = ServiceApi.Standards.MetaData, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除数据元")
    public boolean deleteMetaData(
            @ApiParam(name = "id", value = "编号集", defaultValue = "")
            @PathVariable(value = "id") long id,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception {
        metaDataService.delete(StdMetaData.class, new Object[]{id}, StandardVersion.MetaDataTable, version);
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.MetaData, method = RequestMethod.GET)
    @ApiOperation(value = "获取数据元")
    public MStdMetaData getMetaData(
            @ApiParam(name = "id", value = "数据元编号", defaultValue = "")
            @PathVariable(value = "id") long id,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception {
        StandardVersion ver = new StandardVersion(version);
        return getModel(metaDataService.retrieve(StdMetaDataModel.class,ver.getMetaDataTableName(),id));
    }
    @RequestMapping(value = ServiceApi.Standards.MetaDatasWithDataSet, method = RequestMethod.GET)
    @ApiOperation(value = "根据数据集id获取数据元")
    public Collection<MStdMetaData> getMetaDataByDataSetId(
            @ApiParam(name = "data_set_id", value = "数据元编号", defaultValue = "")
            @PathVariable(value = "data_set_id") long dataSetIs,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception {
        List<StdMetaDataModel> list = metaDataService.searchVersionData(StdMetaDataModel.class,version,StandardVersion.MetaDataTable, "dataSetId=" + dataSetIs);
        return convertToModels(list, new ArrayList<>(list.size()), MStdMetaData.class, "");
    }
    @RequestMapping(value = ServiceApi.Standards.MetaData, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "更新数据元")
    public MStdMetaData updataMetaSet(
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "id", value = "数据元编号", defaultValue = "")
            @PathVariable(value = "id") long id,
            @ApiParam(name = "model", value = "数据源模型", defaultValue = "")
            @RequestBody String model) throws Exception {
        StdMetaDataModel metaDataModel =  jsonToObj(model, StdMetaDataModel.class);
//        StdMetaDataModel metaData = metaDataService.retrieve(id, entityClass);
//        if(metaData.getId()==0)
//            throw errNotFound("数据元", metaDataModel.getId());
        metaDataModel.setId(id);
        metaDataService.saveEntity(metaDataModel);
        return getModel(metaDataModel);
    }
    @RequestMapping(value = ServiceApi.Standards.MetaDatas, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "新增数据元")
    public MStdMetaData saveMetaSet(
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "model", value = "数据源模型", defaultValue = "")
            @RequestBody String model) throws Exception {
        StdMetaDataModel metaData =  jsonToObj(model,StdMetaDataModel.class);
        StandardVersion standardVersion = new StandardVersion(version);
        return getModel(metaDataService.add(standardVersion,metaData));
    }
    @RequestMapping(value = ServiceApi.Standards.MetaDataCodeExistence, method = RequestMethod.GET)
    @ApiOperation(value = "验证数据元代码是否重复")
    public boolean validateInnerCode(
            @ApiParam(name = "version", value = "版本号", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "data_set_id", value = "数据集编号", defaultValue = "")
            @PathVariable(value = "data_set_id") long dataSetId,
            @ApiParam(name = "inner_code", value = "查询代码", defaultValue = "")
            @RequestParam(value = "inner_code") String innerCode) throws Exception {
        return metaDataService.isColumnValExsit(dataSetId, "innerCode", innerCode,StdMetaDataModel.class,version,StandardVersion.MetaDataTable);
    }
    @RequestMapping(value = ServiceApi.Standards.MetaDataNameExistence, method = RequestMethod.GET)
    @ApiOperation(value = "验证数据元名称是否重复")
    public boolean validatorName(
            @ApiParam(name = "version", value = "版本号", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "data_set_id", value = "数据集编号", defaultValue = "")
            @RequestParam(value = "data_set_id") long dataSetId,
            @ApiParam(name = "name", value = "查询名称", defaultValue = "")
            @RequestParam(value = "name") String name) throws Exception {
        return metaDataService.isColumnValExsit(dataSetId, "name", name, StdMetaDataModel.class,version,StandardVersion.MetaDataTable);
    }
    @RequestMapping(value = ServiceApi.Standards.MetaDatasName, method = RequestMethod.POST)
    @ApiOperation(value = "获取数据元 id-name : map集")
    public Map<Long,Object> getMetaDataMapByIds(
            @ApiParam(name = "parmModel", value = "参数模型", defaultValue = "")
            @RequestBody String parmModel) throws IOException {
        parmModel = URLDecoder.decode(parmModel, "UTF-8");
        Map<String, Object> parms = jsonToObj(parmModel, Map.class);
        List<String> metaIds = (List) parms.get("metaIds");
        Object[] rs = null;
        if (metaIds != null && metaIds.size() > 0) {
            rs = new Object[metaIds.size()];
            for (int i = 0; i < metaIds.size(); i++) {
                rs[i] = metaIds.get(i);
            }
        }
        return metaDataService.getMetaDataMapByIds(rs, parms.get("version")+"");
    }
    @Autowired
    private StdDatasetService dataSetService;
    @Autowired
    private StdDictService dictService;
    @RequestMapping(value = "importMetadata", method = RequestMethod.GET)
    @ApiOperation(value = "导入数据元啊")
    public boolean importFile() throws IOException {
        File file = new File("D:/aa.xls.");
        InputStream inputStream = new FileInputStream(file);
        //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
        Workbook workbook = new HSSFWorkbook(inputStream);
        Iterator<Sheet> sheets = workbook.sheetIterator();
        int jj=0;
        while (sheets.hasNext()) {
            Sheet sheet = sheets.next();
            int rows = sheet.getLastRowNum();
            for(int i=1;i<rows;i++){
                Cell cell = sheet.getRow(i).getCell(0);
                String datasetCode = cell.getStringCellValue();
                cell = sheet.getRow(i).getCell(1);
                String metadataCode = cell.getStringCellValue();
                //通过 这2个code值查找是否存在在当前标准中,存在则不存,不存在则存入数据库中
                List<StdDataSetModel> datasets = dataSetService.searchPage(StdDataSetModel.class, StandardVersion.DataSetTable, "59083976eebd", "code="+datasetCode, null, null, null,true);
                if(CollectionUtils.isEmpty(datasets)){
                    throw new RuntimeException("查找不到数据集:"+datasetCode);
                }
                if(datasets.size()>1){
                    throw new RuntimeException("查找到多个数据集:"+datasetCode+",个数为:"+datasets.size());
                }
                Long id = datasets.get(0).getId();
                List all = metaDataService.searchPage(StdMetaDataModel.class, StandardVersion.MetaDataTable, "59083976eebd", "innerCode="+metadataCode+";dataSetId="+id, null, null, null,true);
                boolean needAdd = false;
                if(all==null || all.size()==0){
                    needAdd=true;
                }else if(all.size()==1){
                    needAdd=false;
                }else if(all.size()>1){
                    throw new RuntimeException("查找出来的数据元多个datasetCode:"+datasetCode+",metadatacode:"+metadataCode);
                }
                if(needAdd){
                    //查找eip版本
                    List<StdDataSetModel> _datasets = dataSetService.searchPage(StdDataSetModel.class, StandardVersion.DataSetTable, "5a619250f719", "code="+datasetCode, null, null, null,true);
                    if(CollectionUtils.isEmpty(_datasets) && !"HDSB05_81".equalsIgnoreCase(datasetCode)){
                        throw new RuntimeException("eip查找不到数据集:"+datasetCode);
                    }
                    if(datasets.size()>1){
                        throw new RuntimeException("eip查找到多个数据集:"+datasetCode+",个数为:"+datasets.size());
                    }
                    Long _id = null;
                    if("HDSB05_81".equalsIgnoreCase(datasetCode)){
                        _id=11111L;
                    }else{
                        _id = _datasets.get(0).getId();
                    }
                    List<StdMetaDataModel> _all = metaDataService.searchPage(StdMetaDataModel.class, StandardVersion.MetaDataTable, "5a619250f719", "innerCode="+metadataCode+";dataSetId="+_id, null, null, null,true);
                    if("JDSA00_01_001".equalsIgnoreCase(metadataCode) && CollectionUtils.isEmpty(_all)){
                        _all = metaDataService.searchPage(StdMetaDataModel.class, StandardVersion.MetaDataTable, "5a619250f719", "innerCode="+metadataCode+";dataSetId=64", null, null, null,true);
                    }
                    if(CollectionUtils.isEmpty(_all)){
                        throw new RuntimeException("异常了啊.........dataset:"+datasetCode+",metadacode:"+metadataCode);
                    }else if(_all.size()==1){
                        StdMetaDataModel metaData =  _all.get(0);
                        metaData.setId(null);
                        metaData.setStandardId(10L);
                        metaData.setDataSetId(id);
                        Long _dictId = metaData.getDictId();
                        if(_dictId!=null && _dictId==0){
                            //通过此dictId查找对应的dictCode,
                            List<StdDictionaryModel> _is = dictService.searchPage(StdDictionaryModel.class, StandardVersion.DictTable,"5a619250f719", "id="+_dictId, null, null, null,true);
                            if(CollectionUtils.isEmpty(_is) || _is.size()>1){
                                throw new RuntimeException("eip错了啊.......查找出了多条字典");
                            }
                            String dictCode = _is.get(0).getCode();
                            //通过dictCode查找ehr版本的dictid
                            List<StdDictionaryModel> is = dictService.searchPage(StdDictionaryModel.class, StandardVersion.DictTable,"5a619250f719", "id="+_dictId, null, null, null,true);
                            if(CollectionUtils.isEmpty(is) || is.size()>1){
                                throw new RuntimeException("错了啊.......查找出了多条字典");
                            }
                            Long dictId = is.get(0).getId();
                            metaData.setDictId(dictId);
                        }
                        StandardVersion standardVersion = new StandardVersion("59083976eebd");
                        metaDataService.add(standardVersion,metaData);
                        jj++;
                    }else if(_all.size()>1){
                        throw new RuntimeException("异常了啊.........dataset:"+datasetCode+",metadacode:"+metadataCode+"=========多条啊");
                    }
                }
            }
        }
        System.out.println("插入了辣么多条的数据啊:"+jj);
        return true;
    }
}

+ 265 - 0
src/main/java/com/yihu/hos/ehr/standard/dict/controller/DictEndPoint.java

@ -0,0 +1,265 @@
package com.yihu.hos.ehr.standard.dict.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yihu.hos.common.controller.ExtendEndPoint;
import com.yihu.hos.core.constants.MicroServices;
import com.yihu.hos.core.constants.ServiceApi;
import com.yihu.hos.model.standard.MStdDict;
import com.yihu.hos.standard.model.standard.StdDictionaryModel;
import com.yihu.hos.standard.service.standard.StdDictService;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.model.standard.StandardVersion;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
 * @author lincl
 * @version 1.0
 * @created 2016.2.1
 */
@RestController
@RequestMapping(MicroServices.ApiVersion.Version1_0)
@Api(value = "Dictionary", description = "字典服务")
public class DictEndPoint extends ExtendEndPoint<MStdDict> {
    @Autowired
    private StdDictService dictService;
    @RequestMapping(value = ServiceApi.Standards.Dictionaries, method = RequestMethod.GET)
    @ApiOperation(value = "查询字典")
    public Collection<MStdDict> searchDict(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        List<StdDictionaryModel> ls = dictService.searchPage(StdDictionaryModel.class, StandardVersion.DictTable,version, filters, sorts, page, size,true);
        List list = dictService.searchPage(StdDictionaryModel.class, StandardVersion.DictTable, version, filters, sorts, null, null,true);
        long count  =(long)list.size();
        pagedResponse(request, response, count, page, size);
        return convertToModels(ls, new ArrayList<>(ls.size()), MStdDict.class, fields);
    }
    @RequestMapping(value = ServiceApi.Standards.NoPageDictionaries, method = RequestMethod.GET)
    @ApiOperation(value = "标准字典不分页搜索")
    public Collection<MStdDict> searchSourcesWithoutPaging(
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception {
        List dictList = dictService.searchVersionData(StdDictionaryModel.class,version,StandardVersion.DictTable,filters);
        return convertToModels(dictList, new ArrayList<>(dictList.size()), MStdDict.class, "");
    }
    @RequestMapping(value = ServiceApi.Standards.Dictionaries, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "新增字典")
    public MStdDict addDict(
            @ApiParam(name = "version", value = "标准版本", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "model", value = "json数据模型", defaultValue = "")
            @RequestBody String model) throws Exception{
        StdDictionaryModel dict =  jsonToObj(model, StdDictionaryModel.class);
//        if(dictService.isExistByField("code", dict.getInnerCode(), entityClass))
//            throw errRepeatCode();
        Result result = dictService.add(version, model);
        if(result.isSuccessFlg()){
            return getModel(dict);
        }
        return null;
    }
    @RequestMapping(value = ServiceApi.Standards.Dictionary, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改字典")
    public MStdDict updateDict(
            @ApiParam(name = "version", value = "标准版本", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "id", value = "编号", defaultValue = "")
            @PathVariable(value = "id") Long id,
            @ApiParam(name = "model", value = "json数据模型", defaultValue = "")
            @RequestBody String model) throws Exception{
        StdDictionaryModel dictModel =  jsonToObj(model, StdDictionaryModel.class);
//        StdDictionaryModel dict = dictService.retrieve(id, entityClass);
//        if(!dict.getInnerCode().equals(dictModel.getInnerCode()) &&
//                dictService.isExistByField("code", dictModel.getInnerCode(), entityClass))
//            throw errRepeatCode();
        dictModel.setId(id);
        Result result = dictService.update(version, toJson(dictModel));
        if(result.isSuccessFlg()){
            return getModel(dictModel);
        }
        return null;
    }
    @RequestMapping(value = ServiceApi.Standards.Dictionary, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除字典")
    public boolean deleteDict(
            @ApiParam(name = "version", value = "cda版本号", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "id", value = "编号", defaultValue = "")
            @PathVariable(value = "id") long id) throws Exception{
        dictService.delete(version,id);
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.Dictionaries, method = RequestMethod.DELETE)
    @ApiOperation(value = "批量删除字典")
    public boolean deleteDicts(
            @ApiParam(name = "version", value = "cda版本号", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "ids", value = "编号", defaultValue = "")
            @RequestParam(value = "ids") String ids) throws Exception{
        if(StringUtils.isNotEmpty(ids)){
            for(String id:ids.split(",")){
                Long id_ = Long.valueOf(id);
                dictService.delete(version,id_);
            }
        }
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.Dictionary, method = RequestMethod.GET)
    @ApiOperation(value = "获取字典详细信息")
    public MStdDict getCdaDictInfo(
            @ApiParam(name = "id", value = "字典编号", defaultValue = "")
            @PathVariable(value = "id") long id,
            @ApiParam(name = "version", value = "版本编号", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception{
        Result result =  dictService.get(version, id);
        if(result.isSuccessFlg()){
            //StdDictionaryModel re = (StdDictionaryModel)result;
            //MStdDict mStdDict = convertToModel(re, MStdDict.class, "");
            return getModel(result);
            //return mStdDict;
        }
        return null;
    }
    @RequestMapping(value = ServiceApi.Standards.DictionaryCode, method = RequestMethod.GET)
    @ApiOperation(value = "获取字典详细信息")
    public MStdDict getDictByCode(
            @ApiParam(name = "code", value = "字典代码", defaultValue = "")
            @RequestParam(value = "code") String code,
            @ApiParam(name = "version", value = "版本编号", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception{
        StdDictionaryModel baseDict = dictService.getByCode(code, version);
        return baseDict==null? null : getModel(baseDict);
    }
    @RequestMapping(value = ServiceApi.Standards.MetaDataWithDict, method = RequestMethod.GET)
    @ApiOperation(value = "获取字典 map集")
    public Map getDictMapByIds(
            @ApiParam(name = "version", value = "版本号", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "data_set_id", value = "数据集编号", defaultValue = "")
            @PathVariable(value = "data_set_id") Long dataSetId,
            @ApiParam(name = "meta_data_id", value = "数据元编号", defaultValue = "")
            @PathVariable(value = "meta_data_id") Long metaDataId) {
        return dictService.getDictMapByIds(version, dataSetId, metaDataId);
    }
    @RequestMapping(value = ServiceApi.Standards.DictCodeIsExist,method = RequestMethod.GET)
    public boolean isExistDictCode(
            @RequestParam(value = "dict_code")String dictCode,
            @RequestParam("version_code")String versionCode) throws IOException {
        return dictService.isExistByField(StdDictionaryModel.class, versionCode,StandardVersion.DictTable,"code",dictCode);
    }
    @RequestMapping(value = ServiceApi.Standards.DictParent, method = RequestMethod.GET)
    @ApiOperation(value = "根据当前类别获取自己的父级以及同级以及同级所在父级类别列表")
    public List<MStdDict> getCdaTypeExcludeSelfAndChildren(
            @ApiParam(name = "id", value = "id")
            @RequestParam(value = "id") long id,
            @ApiParam(name = "version", value = "版本编号", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception {
        List<StdDictionaryModel> dicts = new ArrayList<>();
        StandardVersion ver = new StandardVersion(version);
        StdDictionaryModel dict = dictService.retrieve(StdDictionaryModel.class,ver.getDictTableName(), id);
        dicts.add(dict);
        String childrenIds = getChildIncludeSelfByParentsAndChildrenIds(dicts,"",version);   //递归获取
        List<StdDictionaryModel> returnDicts = dictService.getCdaTypeExcludeSelfAndChildren(childrenIds,version);
        return  (List<MStdDict>)convertToModels(returnDicts,new ArrayList<MStdDict>(returnDicts.size()),MStdDict.class,"");
    }
    /**
     * 根据父级类别获取父级类别所在以下所有子集类别(包括当前父级列表)
     * @param parents 父级信息
     * @param childrenIds   子级ID
     */
    public String getChildIncludeSelfByParentsAndChildrenIds(List<StdDictionaryModel> parents, String childrenIds, String version) {
        for (int i = 0; i < parents.size(); i++) {
            StdDictionaryModel dict = parents.get(i);
            childrenIds+=dict.getId()+",";
            List<StdDictionaryModel> listChild = dictService.getChildrensByParentId(dict.getId(),version);
            if(listChild.size()>0){
                childrenIds = getChildIncludeSelfByParentsAndChildrenIds(listChild,childrenIds,version);
            }
        }
        return childrenIds;
    }
    @RequestMapping(value = ServiceApi.Standards.DictEntryBatch, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "批量创建标准字典以及字典项", notes = "批量创建标准字典以及字典项")
    public boolean createDictAndEntries(
            @RequestBody String jsonData, @RequestParam(value = "version")String version) throws Exception {
        List models = objectMapper.readValue(jsonData, new TypeReference<List>() {});
        dictService.batchInsertDictsAndEntry(models,version);
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.DictCodesExistence,method = RequestMethod.POST)
    @ApiOperation("获取已存在字典编码")
    public List<String> codeExistence(
            @RequestBody String codes, @RequestParam(value = "version")String version) throws Exception {
        List existCodes = dictService.codeExist(toEntity(codes, String[].class),version);
        return existCodes;
    }
    @RequestMapping(value = ServiceApi.Standards.AdaptDict, method = RequestMethod.GET)
    @ApiOperation(value = "获取ehr适配的数据元", notes = "获取ehr适配的数据元")
    public List<Map<String, Object>> getEhrAdapterMetadata( @RequestParam(value = "version")String version){
        return dictService.getEhrAdapterDict(version);
    }
}

+ 175 - 0
src/main/java/com/yihu/hos/ehr/standard/dict/controller/DictEntryEndPoint.java

@ -0,0 +1,175 @@
package com.yihu.hos.ehr.standard.dict.controller;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.hos.common.controller.ExtendEndPoint;
import com.yihu.hos.model.standard.MStdDictEntry;
import com.yihu.hos.standard.model.standard.StdDictionaryEntryModel;
import com.yihu.hos.standard.service.standard.StdDictEntryService;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.model.standard.StandardVersion;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 * @author lincl
 * @version 1.0
 * @created 2016.2.1
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "Entry", description = "字典项服务")
public class DictEntryEndPoint extends ExtendEndPoint<MStdDictEntry> {
    @Autowired
    private StdDictEntryService dictEntryService;
    @RequestMapping(value = ServiceApi.Standards.Entry, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改字典项")
    public MStdDictEntry updateDictEntry(
            @ApiParam(name = "version", value = "标准版本", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "id", value = "标准版本", defaultValue = "")
            @PathVariable(value = "id") Long id,
            @ApiParam(name = "model", value = "json数据模型", defaultValue = "")
            @RequestBody String model) throws Exception{
        StdDictionaryEntryModel dictEntryModel =  jsonToObj(model, StdDictionaryEntryModel.class);
//        StdDictionaryEntryModel dictEntry = dictEntryService.retrieve(id, entityClass);
//        if(!dictEntry.getInnerCode().equals(dictEntryModel.getInnerCode())
//                && dictEntryService.isExistByField("code", dictEntryModel.getInnerCode(), entityClass))
//            throw errRepeatCode();
        dictEntryModel.setId(id);
        Result result = dictEntryService.update(version, toJson(dictEntryModel));
        if(result.isSuccessFlg()){
            return getModel(version);
        }
        return null;
    }
    @RequestMapping(value = ServiceApi.Standards.Entries, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "新增字典项")
    public MStdDictEntry addDictEntry(
            @ApiParam(name = "version", value = "cda版本号", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "model", value = "json数据模型", defaultValue = "")
            @RequestBody String model) throws Exception{
        StdDictionaryEntryModel dictEntry =  jsonToObj(model, StdDictionaryEntryModel.class);
//        if(dictEntryService.isExistByField("code", dictEntry.getInnerCode(), entityClass))
//            throw errRepeatCode();
        Result result = dictEntryService.add(version, model);
        if(result.isSuccessFlg()){
            return getModel(dictEntry);
        }
        return null;
    }
    @RequestMapping(value = ServiceApi.Standards.Entry, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除字典项")
    public boolean deleteDictEntry(
            @ApiParam(name = "version", value = "cda版本号", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "id", value = "字典项编号", defaultValue = "")
            @PathVariable(value = "id") long id) throws Exception{
        dictEntryService.delete(version,id);
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.Entries, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除字典项")
    public boolean deleteDictEntrys(
            @ApiParam(name = "version", value = "cda版本号", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "ids", value = "字典项编号", defaultValue = "")
            @RequestParam(value = "ids") String ids) throws Exception{
        if(StringUtils.isNotEmpty(ids)){
            for(String id:ids.split(",")){
                Long id_ = Long.valueOf(id);
                dictEntryService.delete(version,id_);
            }
        }
        return true;
    }
    @RequestMapping(value = ServiceApi.Standards.EntriesWithDictionary, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除字典关联的所有字典项")
    public boolean deleteDictEntryList(
            @ApiParam(name = "version", value = "cda版本号", defaultValue = "")
            @RequestParam(value = "version") String version,
            @ApiParam(name = "dict_id", value = "字典编号", defaultValue = "")
            @PathVariable(value = "dict_id") long dictId) throws Exception{
        return dictEntryService.deleteByField("dictId", new Object[]{dictId}, StandardVersion.DictEntryTable,version);
    }
    @RequestMapping(value = ServiceApi.Standards.Entries, method = RequestMethod.GET)
    @ApiOperation(value = "查询字典项")
    public Collection<MStdDictEntry> searchDictEntry(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "version", value = "版本", defaultValue = "")
            @RequestParam(value = "version") String version,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        List ls = dictEntryService.searchPage(StdDictionaryEntryModel.class,StandardVersion.DictEntryTable,version, filters, sorts, page, size,true);
        List list = dictEntryService.searchPage(StdDictionaryEntryModel.class,StandardVersion.DictEntryTable,version, filters, null, null, null,true);
        long count =(long) list.size();
        pagedResponse(request, response, count, page, size);
        return convertToModels(ls, new ArrayList<>(ls.size()), MStdDictEntry.class, fields);
    }
    @RequestMapping(value = ServiceApi.Standards.Entry, method = RequestMethod.GET)
    @ApiOperation(value = "获取字典项")
    public MStdDictEntry getDictEntry(
            @ApiParam(name = "id", value = "字典项编号", defaultValue = "")
            @PathVariable(value = "id") long id,
            @ApiParam(name = "version", value = "版本编号", defaultValue = "")
            @RequestParam(value = "version") String version) throws Exception{
        Result result =  dictEntryService.get(version, id);
        if(result.isSuccessFlg()){
            return getModel(result);
        }
        return null;
    }
    @RequestMapping(value = ServiceApi.Standards.EntryCodeIsExist,method = RequestMethod.GET)
    public boolean isExistEntryCode(
            @RequestParam(value = "dict_id")long dictId,
            @RequestParam(value = "code")String code,
            @RequestParam(value = "version_code")String versionCode) throws IOException {
        return dictEntryService.isExistByFields(StdDictionaryEntryModel.class,versionCode,StandardVersion.DictEntryTable,new String[]{"dictId","code"}, new Object[]{dictId,code});
    }
}

+ 0 - 0
src/main/java/com/yihu/hos/ehr/standard/dict/model/Dict.java


Неке датотеке нису приказане због велике количине промена