diff --git a/deliverables/auto/pom.xml b/deliverables/auto/pom.xml index 292ddf9d6..831bfe4c9 100644 --- a/deliverables/auto/pom.xml +++ b/deliverables/auto/pom.xml @@ -18,6 +18,6 @@ goojia-auto - ../../projects/goojia-auto + diff --git a/projects/fangjia-bkoff/pom.xml b/projects/fangjia-bkoff/pom.xml index 41b8a352d..69e2d3b60 100644 --- a/projects/fangjia-bkoff/pom.xml +++ b/projects/fangjia-bkoff/pom.xml @@ -178,6 +178,11 @@ 1.0.0 jdk18 + + com.alibaba + easyexcel + 4.0.1 + diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/ApiUserController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/ApiUserController.java index 7c782d610..691eb9427 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/ApiUserController.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/ApiUserController.java @@ -46,67 +46,67 @@ import java.util.*; /** * api用户开通等管理controller - * + * * @author */ public class ApiUserController { - private ApiUserService apiUserService; - private UserService userService; - private ApiUserAuthorityService apiUserAuthorityService; - private OpenResourceService openResourceService; - private ServerAreaService serverAreaService; - private OpenResourceCountService openResourceCountService; - private OpenUriAnalyService openUriAnalyService; - private ApiUserCfgService apiUserCfgService; - private ApiInvokeStatisticalService apiInvokeStatisticalService; - private ApiVisitCountService apiVisitCountService; - private ApiCountCityService apiCountCityService; + private ApiUserService apiUserService; + private UserService userService; + private ApiUserAuthorityService apiUserAuthorityService; + private OpenResourceService openResourceService; + private ServerAreaService serverAreaService; + private OpenResourceCountService openResourceCountService; + private OpenUriAnalyService openUriAnalyService; + private ApiUserCfgService apiUserCfgService; + private ApiInvokeStatisticalService apiInvokeStatisticalService; + private ApiVisitCountService apiVisitCountService; + private ApiCountCityService apiCountCityService; + /** + * 所有api用户的信息展示 + * + * @param model + * @return + */ + public Object listAction(ApiUserModel model) { + /** + * open中公开出的接口资源 ApiUserAuthority 用户的权限信息 + * + * @param ApiUser + * :用户的资料信息 + * @param ApiUser + * :用户的appKey username、等资料 + */ + List apiUsers = this.apiUserService.findApiUsersByParamsSortDate(null); + List apiUserBoList = new ArrayList(); + for (ApiUser apiUser : apiUsers) { + User user = this.userService.findById(apiUser.getId()); + if (user == null) { + continue; + } + ApiUserBo bo = new ApiUserBo(); + bo.setAppKey(apiUser.getAppKey()); + if (null != user) { + bo.setUserId(user.getId()); + bo.setPassword(user.getPassword()); + bo.setUserName(user.getUserName()); + bo.setDisplayName(user.getDisplayName()); + } - /** - * 所有api用户的信息展示 - * - * @param model - * @return - */ - public Object listAction(ApiUserModel model) { - /** - * open中公开出的接口资源 ApiUserAuthority 用户的权限信息 - * - * @param ApiUser - * :用户的资料信息 - * @param ApiUser - * :用户的appKey username、等资料 - */ - List apiUsers = this.apiUserService.findApiUsersByParamsSortDate(null); - List apiUserBoList = new ArrayList(); - for (ApiUser apiUser : apiUsers) { - User user = this.userService.findById(apiUser.getId()); - if (user == null) { - continue; - } - ApiUserBo bo = new ApiUserBo(); - bo.setAppKey(apiUser.getAppKey()); - if(null != user){ - bo.setUserId(user.getId()); - bo.setPassword(user.getPassword()); - bo.setUserName(user.getUserName()); - bo.setDisplayName(user.getDisplayName()); - } - - bo.setSiteName(apiUser.getSiteName()); - bo.setStatus(apiUser.getStatus()); + bo.setSiteName(apiUser.getSiteName()); + bo.setStatus(apiUser.getStatus()); bo.setCompany(apiUser.getCompany()); - bo.setIsTest(apiUser.getIsTest()); - bo.setPurpose(apiUser.getPurpose()); - bo.setDeadTime(apiUser.getDeadTime()); - bo.setManager(apiUser.getManager()); + bo.setIsTest(apiUser.getIsTest()); + bo.setPurpose(apiUser.getPurpose()); + bo.setDeadTime(apiUser.getDeadTime()); + bo.setManager(apiUser.getManager()); + bo.setIsMonitor(apiUser.getIsMonitor()); - apiUserBoList.add(bo); - } + apiUserBoList.add(bo); + } - Collections.sort(apiUserBoList, new Comparator() { + Collections.sort(apiUserBoList, new Comparator() { @Override public int compare(ApiUserBo o1, ApiUserBo o2) { if (o1.getStatus() == 0) { @@ -117,479 +117,537 @@ public class ApiUserController { }); - model.setApiUserBoList(apiUserBoList); - return model; - } - - public Object openlistAction(ApiUserModel model) { - return model; - } - - public Object resetPwdAction(ApiUserModel model) { - JsonModel ret = new JsonModel(); - Map dataMap = new HashMap(); - dataMap.put("status", 0); - if (model.getUserId() != null) { - Map data = new HashMap(); - data.put("password", DigestUtils.md5Hex("123456")); - userService.updateById(data, model.getUserId()); - dataMap.put("status", 1); - } - ret.setJsonModel(dataMap); - return ret; - } + model.setApiUserBoList(apiUserBoList); + return model; + } - /** - * 新增api用户的信息 - * - * @param model - * @return - */ - public Object addAction(ApiUserModel model) { - return model; - } + public Object openlistAction(ApiUserModel model) { + return model; + } - public Object doAddAction(ApiUserModel model) throws Exception { - if (StringUtils.isBlank(model.getDisplayName()) || StringUtils.isBlank(model.getUserName()) - || StringUtils.isBlank(model.getPassword())) { - model.setMsg("昵称,用户名,密码不能为空"); - model.forward("/apiUser/add"); - return model; - } + public Object resetPwdAction(ApiUserModel model) { + JsonModel ret = new JsonModel(); + Map dataMap = new HashMap(); + dataMap.put("status", 0); + if (model.getUserId() != null) { + Map data = new HashMap(); + data.put("password", DigestUtils.md5Hex("123456")); + userService.updateById(data, model.getUserId()); + dataMap.put("status", 1); + } + ret.setJsonModel(dataMap); + return ret; + } - try { - List users = new ArrayList(); - User user = new User(); - user.setUserName(model.getUserName()); - user.setPassword(DigestUtils.md5Hex(model.getPassword())); - user.setDisplayName(model.getDisplayName()); - users.add(user); - Map userMap = this.userService.saveUser(users); - Long id = userMap.get(model.getUserName()); + /** + * 新增api用户的信息 + * + * @param model + * @return + */ + public Object addAction(ApiUserModel model) { + return model; + } - String appkey = DigestUtils.md5Hex(String.valueOf(id)) + DigestUtils.md5Hex(DigestUtils.md5Hex(String.valueOf(id))); - Date date = new Date(); - ApiUser apiUser = new ApiUser(); - apiUser.setId(id); - apiUser.setAppKey(appkey.toUpperCase()); - apiUser.setCreationDate(date); - apiUser.setSiteName(model.getSiteName()); + public Object doAddAction(ApiUserModel model) throws Exception { + if (StringUtils.isBlank(model.getDisplayName()) || StringUtils.isBlank(model.getUserName()) + || StringUtils.isBlank(model.getPassword())) { + model.setMsg("昵称,用户名,密码不能为空"); + model.forward("/apiUser/add"); + return model; + } + + try { + List users = new ArrayList(); + User user = new User(); + user.setUserName(model.getUserName()); + user.setPassword(DigestUtils.md5Hex(model.getPassword())); + user.setDisplayName(model.getDisplayName()); + users.add(user); + Map userMap = this.userService.saveUser(users); + Long id = userMap.get(model.getUserName()); + + String appkey = DigestUtils.md5Hex(String.valueOf(id)) + DigestUtils.md5Hex(DigestUtils.md5Hex(String.valueOf(id))); + Date date = new Date(); + ApiUser apiUser = new ApiUser(); + apiUser.setId(id); + apiUser.setAppKey(appkey.toUpperCase()); + apiUser.setCreationDate(date); + apiUser.setSiteName(model.getSiteName()); apiUser.setCompany(model.getCompany()); - apiUser.setStatus(0); - apiUser.setIsTest(model.getIsTest()); - apiUser.setPurpose(model.getPurpose()); - apiUser.setIp(model.getIp()); - apiUser.setEmail(model.getEmail()); - apiUser.setModificationDate(date); - apiUser.setDeadTime(model.getDeadTime()); - apiUser.setManager(model.getManager()); - this.apiUserService.save(apiUser); - if(model.getEvaluateRate() != null && model.getEvaluateRate() != 0){ - ApiUserCfg apiUserCfg = new ApiUserCfg(); - apiUserCfg.setUserId(apiUser.getId()); - apiUserCfg.setCfgValue(model.getEvaluateRate()); - this.apiUserCfgService.save(apiUserCfg, ApiUserCfg.ApiUserCfgKey.EVALUATE_RATE); - } - model.setMsg("新建成功!"); - } catch (Exception e) { - e.printStackTrace(); - model.setMsg("新建失败!"); - } - model.redirect("/apiUser/add?msg=" + URLEncoder.encode(model.getMsg(), "UTF-8")); - return model; - } + apiUser.setStatus(0); + apiUser.setIsTest(model.getIsTest()); + apiUser.setPurpose(model.getPurpose()); + apiUser.setIp(model.getIp()); + apiUser.setEmail(model.getEmail()); + apiUser.setModificationDate(date); + apiUser.setDeadTime(model.getDeadTime()); + apiUser.setManager(model.getManager()); + apiUser.setIsMonitor(model.getIsMonitor()); + this.apiUserService.save(apiUser); + // 新增用户,默认挂牌价改为默认评估价 + model.setPriceType("evaluate"); + modifyUserCfg(id, ApiUserCfg.ApiUserCfgKey.PRICE_TYPE, model.getPriceType()); + if (model.getEvaluateRate() != null && model.getEvaluateRate() != 0) { + ApiUserCfg apiUserCfg = new ApiUserCfg(); + apiUserCfg.setUserId(apiUser.getId()); + apiUserCfg.setCfgValue(model.getEvaluateRate()); + this.apiUserCfgService.save(apiUserCfg, ApiUserCfg.ApiUserCfgKey.EVALUATE_RATE); + } + model.setMsg("新建成功!"); + } catch (Exception e) { + e.printStackTrace(); + model.setMsg("新建失败!"); + } + model.redirect("/apiUser/add?msg=" + URLEncoder.encode(model.getMsg(), "UTF-8")); + return model; + } - /** - * 编辑api用户信息 - * - * @param model - * @return - */ - public Object editAction(ApiUserModel model) { - ApiUser apiUser = this.apiUserService.findApiUserById(model.getUserId()); - User user = this.userService.findById(model.getUserId()); - ApiUserBo bo = new ApiUserBo(); - bo.setUserName(user.getUserName()); - bo.setAppKey(apiUser.getAppKey()); - bo.setUserId(user.getId()); - bo.setSiteName(user.getUserName()); - bo.setDisplayName(user.getDisplayName()); - bo.setIsTest(apiUser.getIsTest()); - bo.setPurpose(apiUser.getPurpose()); - bo.setSiteName(apiUser.getSiteName()); - bo.setIp(apiUser.getIp()); + /** + * 编辑api用户信息 + * + * @param model + * @return + */ + public Object editAction(ApiUserModel model) { + ApiUser apiUser = this.apiUserService.findApiUserById(model.getUserId()); + User user = this.userService.findById(model.getUserId()); + ApiUserBo bo = new ApiUserBo(); + bo.setUserName(user.getUserName()); + bo.setAppKey(apiUser.getAppKey()); + bo.setUserId(user.getId()); + bo.setSiteName(user.getUserName()); + bo.setDisplayName(user.getDisplayName()); + bo.setIsTest(apiUser.getIsTest()); + bo.setPurpose(apiUser.getPurpose()); + bo.setSiteName(apiUser.getSiteName()); + bo.setIp(apiUser.getIp()); bo.setCompany(apiUser.getCompany()); - bo.setEmail(apiUser.getEmail()); - bo.setDeadTime(apiUser.getDeadTime()); - bo.setManager(apiUser.getManager()); - ApiUserCfg apiUserCfg_rate = apiUserCfgService.findByUserId(apiUser.getId(), ApiUserCfg.ApiUserCfgKey.EVALUATE_RATE); - if(apiUserCfg_rate != null){ - bo.setEvaluateRate((Double) apiUserCfg_rate.getCfgValue()); - } + bo.setEmail(apiUser.getEmail()); + bo.setDeadTime(apiUser.getDeadTime()); + bo.setManager(apiUser.getManager()); + bo.setIsMonitor(apiUser.getIsMonitor()); + ApiUserCfg apiUserCfg_rate = apiUserCfgService.findByUserId(apiUser.getId(), ApiUserCfg.ApiUserCfgKey.EVALUATE_RATE); + if (apiUserCfg_rate != null) { + bo.setEvaluateRate((Double) apiUserCfg_rate.getCfgValue()); + } - ApiUserCfg apiUserCfg_pt = apiUserCfgService.findByUserId(apiUser.getId(), ApiUserCfg.ApiUserCfgKey.PRICE_TYPE); - if(apiUserCfg_pt != null && apiUserCfg_pt.getCfgValue() != null){ - bo.setPriceType(apiUserCfg_pt.getCfgValue().toString()); - } + ApiUserCfg apiUserCfg_pt = apiUserCfgService.findByUserId(apiUser.getId(), ApiUserCfg.ApiUserCfgKey.PRICE_TYPE); + if (apiUserCfg_pt != null && apiUserCfg_pt.getCfgValue() != null) { + bo.setPriceType(apiUserCfg_pt.getCfgValue().toString()); + } - model.setApiUserBo(bo); - if (StringUtils.isNotBlank(model.getMsg()) && model.getMsg().equals("success")) { - model.setMsg("更新成功!"); - } - return model; - } + model.setApiUserBo(bo); + if (StringUtils.isNotBlank(model.getMsg()) && model.getMsg().equals("success")) { + model.setMsg("更新成功!"); + } + return model; + } - /** - * 修改用户登录状态 - * - * @param model - * @return - */ - public Object statusAction(ApiUserModel model) { - ApiUser apiUser = this.apiUserService.findApiUserById(model.getUserId()); - apiUser.setStatus(model.getStatus()); - apiUserService.update(apiUser); - model.setViewType("redirect"); - apiUserAuthorityService.clearApiUserAuthorityCache(apiUser.getId()); - model.setViewParam("location", "/apiUser/list"); - return model; - } + /** + * 修改用户登录状态 + * + * @param model + * @return + */ + public Object statusAction(ApiUserModel model) { + ApiUser apiUser = this.apiUserService.findApiUserById(model.getUserId()); + apiUser.setStatus(model.getStatus()); + apiUserService.update(apiUser); + model.setViewType("redirect"); + apiUserAuthorityService.clearApiUserAuthorityCache(apiUser.getId()); + model.setViewParam("location", "/apiUser/list"); + return model; + } - /** - * 手动修改api用户appkey值 - * - * @param model - * @return - */ - public Object updateAction(ApiUserModel model) { - Long userId = model.getUserId(); - Map dataApiUser = new HashMap(); - dataApiUser.put("email", model.getEmail()); - dataApiUser.put("siteName", model.getSiteName()); - dataApiUser.put("ip", model.getIp()); + /** + * 手动修改api用户appkey值 + * + * @param model + * @return + */ + public Object updateAction(ApiUserModel model) { + Long userId = model.getUserId(); + Map dataApiUser = new HashMap(); +// Map user = new HashMap(); + dataApiUser.put("email", model.getEmail()); +// user.put("password", DigestUtils.md5Hex(model.getPassword())); + dataApiUser.put("siteName", model.getSiteName()); + dataApiUser.put("ip", model.getIp()); dataApiUser.put("company", model.getCompany()); - dataApiUser.put("isTest", model.getIsTest()); - dataApiUser.put("purpose", model.getPurpose()); - dataApiUser.put("deadTime", model.getDeadTime()); - dataApiUser.put("manager", model.getManager()); - this.apiUserService.update(dataApiUser, userId); + dataApiUser.put("isTest", model.getIsTest()); + dataApiUser.put("purpose", model.getPurpose()); + dataApiUser.put("deadTime", model.getDeadTime()); + dataApiUser.put("manager", model.getManager()); + dataApiUser.put("isMonitor", model.getIsMonitor()); + this.apiUserService.update(dataApiUser, userId); + // 更改用户密码 +// this.userService.updateById(user,userId); + // 刷新缓存 +// this.apiUserService.clearApiUserAuthorityCache(userId); - //ApiUserCfg.ApiUserCfgKey.EVALUATE_RATE - modifyUserCfg(userId, ApiUserCfg.ApiUserCfgKey.EVALUATE_RATE, model.getEvaluateRate()); - modifyUserCfg(userId, ApiUserCfg.ApiUserCfgKey.PRICE_TYPE, model.getPriceType()); - model.setViewType("redirect"); - //model.setViewParam("location", "/apiUser/edit?msg=sucess&userId=" + model.getUserId()); - model.setViewParam("location", "/apiUser/list"); - return model; - } + //ApiUserCfg.ApiUserCfgKey.EVALUATE_RATE + modifyUserCfg(userId, ApiUserCfg.ApiUserCfgKey.EVALUATE_RATE, model.getEvaluateRate()); + modifyUserCfg(userId, ApiUserCfg.ApiUserCfgKey.PRICE_TYPE, model.getPriceType()); - void modifyUserCfg(Long userId, ApiUserCfg.ApiUserCfgKey cfgKey, Object val) { - if(userId != null && cfgKey != null){ - ApiUserCfg apiUserCfg = this.apiUserCfgService.findByUserId(userId, cfgKey); - if(val == null || StringUtils.isEmpty(val.toString())) { - if(null != apiUserCfg){ - apiUserCfgService.delete(apiUserCfg, cfgKey); - } - return; - } + model.setViewType("redirect"); + //model.setViewParam("location", "/apiUser/edit?msg=sucess&userId=" + model.getUserId()); + model.setViewParam("location", "/apiUser/list"); + return model; + } - if(cfgKey == ApiUserCfg.ApiUserCfgKey.EVALUATE_RATE) { - try{ - double rate = Double.parseDouble(val.toString()); - if(Double.compare(rate, 0) == 0){ - if(null != apiUserCfg){ - apiUserCfgService.delete(apiUserCfg, cfgKey); - return; - } - } - }catch(Exception e){ - e.printStackTrace(); - } - } + public Object doEditPwdAction(ApiUserModel model) { + Long userId = model.getUserId(); + Map user = new HashMap(); + user.put("password", DigestUtils.md5Hex(model.getPassword())); +// +// // 更改用户密码 + this.userService.updateById(user,userId); + // 刷新缓存 + this.apiUserService.clearApiUserAuthorityCache(userId); - if(null == apiUserCfg){ - apiUserCfg = new ApiUserCfg(); - } - apiUserCfg.setUserId(userId); - apiUserCfg.setCreatedDate(new Date()); - apiUserCfg.setCfgValue(val); - apiUserCfgService.save(apiUserCfg, cfgKey); - } - } + model.setViewType("redirect"); + model.setViewParam("location", "/apiUser/edit?userId="+userId); + return model; + } + public Object editPwdAction(ApiUserModel model) { + Long userId = model.getUserId(); + User user = this.userService.findById(userId); + ApiUserBo bo = new ApiUserBo(); + bo.setUserName(user.getUserName()); + bo.setDisplayName(user.getDisplayName()); + model.setApiUserBo(bo); + return model; + } - /** - * 重置appkey值,默认为userid md5加上useridmd5再md5, 64位 - * - * @param model - * @return - */ - public Object resetAction(ApiUserModel model) { - String appkey = DigestUtils.md5Hex(String.valueOf(model.getUserId())) - + DigestUtils.md5Hex(DigestUtils.md5Hex(String.valueOf(model.getUserId()))); + void modifyUserCfg(Long userId, ApiUserCfg.ApiUserCfgKey cfgKey, Object val) { + if (userId != null && cfgKey != null) { + ApiUserCfg apiUserCfg = this.apiUserCfgService.findByUserId(userId, cfgKey); + if (val == null || StringUtils.isEmpty(val.toString())) { + if (null != apiUserCfg) { + apiUserCfgService.delete(apiUserCfg, cfgKey); + } + return; + } - Map data = new HashMap(); - data.put("appKey", appkey.toUpperCase()); - this.apiUserService.update(data, model.getUserId()); - model.setViewType("redirect"); - model.setViewParam("location", "/apiUser/edit?userId=" + model.getUserId()); - return model; - } + if (cfgKey == ApiUserCfg.ApiUserCfgKey.EVALUATE_RATE) { + try { + double rate = Double.parseDouble(val.toString()); + if (Double.compare(rate, 0) == 0) { + if (null != apiUserCfg) { + apiUserCfgService.delete(apiUserCfg, cfgKey); + return; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } - public Object checkUserNameAction(ApiUserModel model) { - model.setViewType("json"); - model.setViewParam("config", null); - User user = userService.findByUserName(model.getUserName()); - if (user != null) { - model.setMsg("此用户名已经存在!"); - return model; - } - return model; - } + if (null == apiUserCfg) { + apiUserCfg = new ApiUserCfg(); + } + apiUserCfg.setUserId(userId); + apiUserCfg.setCreatedDate(new Date()); + apiUserCfg.setCfgValue(val); + apiUserCfgService.save(apiUserCfg, cfgKey); + } + } - public Object loadConfigAction(@Param(name="uri") String uri, @Param(name="userId") long userId){ - JsonModel json = new JsonModel(); - ApiJsonViewConfig config = apiUserAuthorityService.findViewConfig(userId, uri); - json.setJsonModel(config); - return json; - } + /** + * 重置appkey值,默认为userid md5加上useridmd5再md5, 64位 + * + * @param model + * @return + */ + public Object resetAction(ApiUserModel model) { + String appkey = DigestUtils.md5Hex(String.valueOf(model.getUserId())) + + DigestUtils.md5Hex(DigestUtils.md5Hex(String.valueOf(model.getUserId()))); - public Object saveConfigAction(ApiJsonViewConfig config,@Param(name="fields") String fields){ - if(StringUtils.isNotBlank(fields)){ - List availableFields = new ArrayList(); - for(String field : fields.split("\r\n")){ - field = DataUtil.trim(field); - if(StringUtils.isNotBlank(field)){ - availableFields.add(field); - } - } - config.setFields(availableFields); - } - apiUserAuthorityService.saveViewConfig(config); - return new JsonModel(); - } + Map data = new HashMap(); + data.put("appKey", appkey.toUpperCase()); + this.apiUserService.update(data, model.getUserId()); + model.setViewType("redirect"); + model.setViewParam("location", "/apiUser/edit?userId=" + model.getUserId()); + return model; + } - public Object cityAction(ApiUserModel model) throws IllegalAccessException { - ApiUser apiUser = this.apiUserService.findApiUserById(model.getUserId()); - User user = this.userService.findById(apiUser.getId()); - ApiUserAuthority apiUserAuthority=apiUserAuthorityService.findByUserId(model.getUserId()); - Map cityCreditMap=apiUserAuthority.getCityCreditMap(); - model.setDisplayName(user.getDisplayName() == null ? "" : user.getDisplayName()); - model.setCityFirstLetters(Arrays.asList(getCityFirstLetter())); - List serverAreaList = serverAreaService.findAll();// Load城市列表 - if (StringUtils.isBlank(model.getType()) || "all".equals(model.getType())) {// 字母分组列表 - model.setServerAreaList(null); - } else { // 首字母查询 - List> serverAreaLetterList = new ArrayList>();// Load城市列表 - for (ServerArea serverArea : serverAreaList) { - if (serverArea.getSpell().substring(0, 1).toUpperCase().equals(model.getType())) { - Map map=new HashMap (); - if(null!=cityCreditMap && cityCreditMap.get(serverArea.getDisplay())!=null){ - map.put("key0",serverArea); - java.text.DecimalFormat df =new java.text.DecimalFormat("######0.00"); - String rate=df.format(cityCreditMap.get(serverArea.getDisplay())); - map.put("key1",rate); - }else { - map.put("key0",serverArea); - map.put("key1",null); - } - serverAreaLetterList.add(map); - } - } - model.setServerAreaList(serverAreaLetterList); - } + public Object checkUserNameAction(ApiUserModel model) { + model.setViewType("json"); + model.setViewParam("config", null); + User user = userService.findByUserName(model.getUserName()); + if (user != null) { + model.setMsg("此用户名已经存在!"); + return model; + } + return model; + } - StringBuffer openCitys = new StringBuffer();// Load城市列表 - if (StringUtils.isBlank(apiUser.getCity())) { - } else if ("all".equals(apiUser.getCity())) { - openCitys.append("全部城市"); - } else { - int cnt = 0; - if(StringUtils.isNotBlank(apiUser.getCity()) && !apiUser.getCity().endsWith(",")){ - apiUser.setCity(apiUser.getCity() + ","); - } - for (ServerArea serverArea : serverAreaList) { - if (apiUser.getCity().indexOf(serverArea.getSpell() + ",") > -1) { - cnt++; - if (cnt == 1) { - openCitys.append(serverArea.getDisplay()); - } else { - openCitys.append(","); - openCitys.append(serverArea.getDisplay()); - } - } - } - openCitys.append(";
共" + cnt + "个城市"); - } - model.setOpenCitys(openCitys.toString()); - model.setCitys(apiUser.getCity()); - return model; - } + public Object loadConfigAction(@Param(name = "uri") String uri, @Param(name = "userId") long userId) { + JsonModel json = new JsonModel(); + ApiJsonViewConfig config = apiUserAuthorityService.findViewConfig(userId, uri); + json.setJsonModel(config); + return json; + } - public Object citySaveAction(ApiUserModel model) throws IllegalAccessException { - model.setViewType("json"); - model.setViewParam("config", null); - List serverAreaList = serverAreaService.findAll(); - ApiUser apiUser = this.apiUserService.findApiUserById(model.getUserId()); - ApiUserAuthority apiUserAuthority=apiUserAuthorityService.findByUserId(model.getUserId()); - Map cityCreditMap=apiUserAuthority.getCityCreditMap(); - if(null==cityCreditMap){ - cityCreditMap=new HashMap(); - } - if (model.getCitys().equals("all")) { - apiUser.setCity("all"); - apiUser.setCreationDate(apiUser.getCreationDate() == null ? new Date() : apiUser.getCreationDate()); - this.apiUserService.update(apiUser); - } else if (model.getCitys().equals("disAll")) { - apiUser.setCity(null); - apiUser.setCreationDate(apiUser.getCreationDate() == null ? new Date() : apiUser.getCreationDate()); - this.apiUserService.update(apiUser); - } else { - String _check_citys = model.getCitys() == null ? "" : model.getCitys(); - String _un_check_citys = model.getUnCheckCitys() == null ? "" : model.getUnCheckCitys(); - String displayNames= model.getDisplayName() == null ? "" : model.getDisplayName(); - String credits=model.getCredits() == null ? "" : model.getCredits(); - String uncitys=model.getUncitys() == null ? "" : model.getUncitys(); - String[] uncity = StringUtils.split(uncitys,"|"); - for(int i=0;i availableFields = new ArrayList(); + for (String field : fields.split("\r\n")) { + field = DataUtil.trim(field); + if (StringUtils.isNotBlank(field)) { + availableFields.add(field); + } + } + config.setFields(availableFields); + } + apiUserAuthorityService.saveViewConfig(config); + return new JsonModel(); + } - String[] newCitys = StringUtils.split(_check_citys, ","); - for (String city : newCitys) { - if (citys.indexOf("," + city + ",") == -1) { - citys = citys + city + ","; - } - } - String[] delCitys = StringUtils.split(_un_check_citys, ","); - for (String city : delCitys) { - if (citys.indexOf("," + city + ",") > -1) { - citys = citys.replace(city + ",", ""); - } - } - citys = citys.replaceAll("^,","").replaceAll(",$",""); - apiUser.setCity(citys); - } - apiUser.setCreationDate(apiUser.getCreationDate() == null ? new Date() : apiUser.getCreationDate()); - this.apiUserService.update(apiUser); - - apiUserAuthorityService.update(apiUserAuthority); - } - return model; - } + public Object cityAction(ApiUserModel model) throws IllegalAccessException { + ApiUser apiUser = this.apiUserService.findApiUserById(model.getUserId()); + User user = this.userService.findById(apiUser.getId()); + ApiUserAuthority apiUserAuthority = apiUserAuthorityService.findByUserId(model.getUserId()); + Map cityCreditMap = apiUserAuthority.getCityCreditMap(); + model.setDisplayName(user.getDisplayName() == null ? "" : user.getDisplayName()); + model.setCityFirstLetters(Arrays.asList(getCityFirstLetter())); + List serverAreaList = serverAreaService.findAll();// Load城市列表 + if (StringUtils.isBlank(model.getType()) || "all".equals(model.getType())) {// 字母分组列表 + model.setServerAreaList(null); + } else { // 首字母查询 + List> serverAreaLetterList = new ArrayList>();// Load城市列表 + for (ServerArea serverArea : serverAreaList) { + if (serverArea.getSpell().substring(0, 1).toUpperCase().equals(model.getType())) { + Map map = new HashMap(); + if (null != cityCreditMap && cityCreditMap.get(serverArea.getDisplay()) != null) { + map.put("key0", serverArea); + java.text.DecimalFormat df = new java.text.DecimalFormat("######0.00"); + String rate = df.format(cityCreditMap.get(serverArea.getDisplay())); + map.put("key1", rate); + } else { + map.put("key0", serverArea); + map.put("key1", null); + } + serverAreaLetterList.add(map); + } + } + model.setServerAreaList(serverAreaLetterList); + } - /** - * 所有api用户的信息展示 - * - * @param model - * @return - */ - public Object authAction(ApiUserModel model) throws IllegalAccessException { - /** - * OpenResource open中公开出的接口资源 User 本地user ApiUserAuthority 用户的权限信息 - * - * @param ApiUser - * :用户的资料信息 - * @param AuthorityBo - * :用户的appKey username、等资料 - */ - List openResourceList = openResourceService.findAll(); - List authorityBoList = new ArrayList(); - ApiUserAuthority authority = apiUserAuthorityService.findByUserId(model.getUserId()); - if(authority == null){ - authority = new ApiUserAuthority(); - authority.setOpenResourseUris(new ArrayList()); - apiUserAuthorityService.save(authority); - } - User user = this.userService.findById(model.getUserId()); - model.setDisplayName(user.getDisplayName() == null ? "" : user.getDisplayName()); - Map urisMap = authority.getOpenResourseUrisMap(); - for (OpenResource openResource : openResourceList) { - AuthorityBo bo = new AuthorityBo(); - BeanUtils.copyProperties(openResource, bo); - if (authority != null) { - bo.setHasAuth(authority.getOpenResourseUris().contains(bo.getUri())); - model.setSupportLatLng(authority.isSupportLatLng()); - bo.setLimitCountMap(authority.getLimitCountMap()); - bo.setTotalCountMap(authority.getTotalCountMap()); - bo.setIsCheckCount(urisMap==null?0:(urisMap.get(bo.getUri())==null?0:urisMap.get(bo.getUri()))); - } - //apiVisitCountService.findApiVisitAllCount(user.getUserId(), null); - if(bo.isHasAuth()){ - long curVistedCount = apiVisitCountService.findApiVisitCountByDay(model.getUserId(), openResource.getUri(), DateUtil.truncateDay(new Date())); - long total = apiVisitCountService.findApiVisitAllCount(model.getUserId(), openResource.getUri(), DateUtil.truncateDay(new Date())); - bo.setCurVisitedCount(curVistedCount); - bo.setTotalVisitedCount(total); - } - - authorityBoList.add(bo); - } - model.setAuthority(authority); - model.setAuthorityBoList(authorityBoList); - return model; - } + StringBuffer openCitys = new StringBuffer();// Load城市列表 + if (StringUtils.isBlank(apiUser.getCity())) { + } else if ("all".equals(apiUser.getCity())) { + openCitys.append("全部城市"); + } else { + int cnt = 0; + if (StringUtils.isNotBlank(apiUser.getCity()) && !apiUser.getCity().endsWith(",")) { + apiUser.setCity(apiUser.getCity() + ","); + } + for (ServerArea serverArea : serverAreaList) { + if (apiUser.getCity().indexOf(serverArea.getSpell() + ",") > -1) { + cnt++; + if (cnt == 1) { + openCitys.append(serverArea.getDisplay()); + } else { + openCitys.append(","); + openCitys.append(serverArea.getDisplay()); + } + } + } + openCitys.append(";
共" + cnt + "个城市"); + } + model.setOpenCitys(openCitys.toString()); + model.setCitys(apiUser.getCity()); + return model; + } - public Object openuriAction(ApiUserModel model){ - List authorityBoList = new ArrayList(); - List openResourceList = openResourceService.findAll(); - String userId=model.getUserId().toString(); - for(OpenResource openResource:openResourceList){ - String uri=openResource.getUri(); - AuthorityBo bo = new AuthorityBo(); - BeanUtils.copyProperties(openResource, bo); - OpenResourceCount open= openResourceCountService.findByUserId(userId, uri); - Long count=0L; - if(open!=null && open.getCount()!=null){ - count=open.getCount(); - } - bo.setCount(count); - authorityBoList.add(bo); - } - Collections.sort(authorityBoList, new Comparator() { + public Object citySaveAction(ApiUserModel model) throws IllegalAccessException { + model.setViewType("json"); + model.setViewParam("config", null); + List serverAreaList = serverAreaService.findAll(); + ApiUser apiUser = this.apiUserService.findApiUserById(model.getUserId()); + ApiUserAuthority apiUserAuthority = apiUserAuthorityService.findByUserId(model.getUserId()); + Map cityCreditMap = apiUserAuthority.getCityCreditMap(); + if (null == cityCreditMap) { + cityCreditMap = new HashMap(); + } + if (model.getCitys().equals("all")) { + apiUser.setCity("all"); + apiUser.setCreationDate(apiUser.getCreationDate() == null ? new Date() : apiUser.getCreationDate()); + this.apiUserService.update(apiUser); + } else if (model.getCitys().equals("disAll")) { + apiUser.setCity(null); + apiUser.setCreationDate(apiUser.getCreationDate() == null ? new Date() : apiUser.getCreationDate()); + this.apiUserService.update(apiUser); + } else { + String _check_citys = model.getCitys() == null ? "" : model.getCitys(); + String _un_check_citys = model.getUnCheckCitys() == null ? "" : model.getUnCheckCitys(); + String displayNames = model.getDisplayName() == null ? "" : model.getDisplayName(); + String credits = model.getCredits() == null ? "" : model.getCredits(); + String uncitys = model.getUncitys() == null ? "" : model.getUncitys(); + String[] uncity = StringUtils.split(uncitys, "|"); + for (int i = 0; i < uncity.length; i++) { + if (cityCreditMap.containsKey(uncity[i])) { + cityCreditMap.remove(uncity[i]); + } + } + if (StringUtils.isNotBlank(displayNames)) { + String[] display = StringUtils.split(displayNames, "|"); + String[] cre = StringUtils.split(credits, "|"); + for (int k = 0; k < display.length; k++) { + if (cre[k].equals("null")) { + cityCreditMap.remove(display[k]); + } else { + cityCreditMap.put(display[k], Double.parseDouble(cre[k])); + } + } + } + apiUserAuthority.setCityCreditMap(cityCreditMap); + + if (StringUtils.isBlank(apiUser.getCity())) { + apiUser.setCity(model.getCitys()); + } else if (apiUser.getCity().equals("all")) { + StringBuffer citys = new StringBuffer(); + int _all = 0; + for (ServerArea serverArea : serverAreaList) { + if (_un_check_citys.indexOf(serverArea.getSpell()) == -1) { + _all++; + if (_all == 1) { + citys.append(serverArea.getSpell()); + } else { + citys.append(","); + citys.append(serverArea.getSpell()); + } + } + } + apiUser.setCity(citys.toString()); + } else { + String citys = apiUser.getCity(); + if (StringUtils.isBlank(citys)) { + citys = ","; + } else { + if (!citys.endsWith(",")) { + citys += ","; + } + if (!citys.startsWith(",")) { + citys = "," + citys; + } + } + + String[] newCitys = StringUtils.split(_check_citys, ","); + for (String city : newCitys) { + if (citys.indexOf("," + city + ",") == -1) { + citys = citys + city + ","; + } + } + String[] delCitys = StringUtils.split(_un_check_citys, ","); + for (String city : delCitys) { + if (citys.indexOf("," + city + ",") > -1) { + citys = citys.replace(city + ",", ""); + } + } + citys = citys.replaceAll("^,", "").replaceAll(",$", ""); + apiUser.setCity(citys); + } + apiUser.setCreationDate(apiUser.getCreationDate() == null ? new Date() : apiUser.getCreationDate()); + this.apiUserService.update(apiUser); + + apiUserAuthorityService.update(apiUserAuthority); + } + return model; + } + + /** + * 所有api用户的信息展示 + * + * @param model + * @return + */ + public Object authAction(ApiUserModel model) throws IllegalAccessException { + /** + * OpenResource open中公开出的接口资源 User 本地user ApiUserAuthority 用户的权限信息 + * + * @param ApiUser + * :用户的资料信息 + * @param AuthorityBo + * :用户的appKey username、等资料 + */ + List openResourceList = openResourceService.findAll(); + List authorityBoList = new ArrayList(); + ApiUserAuthority authority = apiUserAuthorityService.findByUserId(model.getUserId()); + if (authority == null) { + authority = new ApiUserAuthority(); + authority.setOpenResourseUris(new ArrayList()); + apiUserAuthorityService.save(authority); + } + User user = this.userService.findById(model.getUserId()); + model.setDisplayName(user.getDisplayName() == null ? "" : user.getDisplayName()); + Map urisMap = authority.getOpenResourseUrisMap(); + + // 用户有的uri + String flag = model.getMsg(); + List userResources = new ArrayList(); + + if ("0".equals(flag)) { + for (OpenResource openResource : openResourceList) { + if (!authority.getOpenResourseUris().contains(openResource.getUri())) { + userResources.add(openResource); + } + } + } else { + for (OpenResource openResource : openResourceList) { + if (authority.getOpenResourseUris().contains(openResource.getUri())) { + userResources.add(openResource); + } + } + } + + // 改成遍历用户有的uri + for (OpenResource openResource : userResources) { + AuthorityBo bo = new AuthorityBo(); + BeanUtils.copyProperties(openResource, bo); + if (authority != null) { + bo.setHasAuth(authority.getOpenResourseUris().contains(bo.getUri())); + bo.setHasAuth(authority.getOpenResourseUris().contains(bo.getUri())); + model.setSupportLatLng(authority.isSupportLatLng()); + bo.setLimitCountMap(authority.getLimitCountMap()); + bo.setTotalCountMap(authority.getTotalCountMap()); + bo.setIsCheckCount(urisMap == null ? 0 : (urisMap.get(bo.getUri()) == null ? 0 : urisMap.get(bo.getUri()))); + } + //apiVisitCountService.findApiVisitAllCount(user.getUserId(), null); + if (bo.isHasAuth()) { + long curVistedCount = apiVisitCountService.findApiVisitCountByDay(model.getUserId(), openResource.getUri(), DateUtil.truncateDay(new Date())); + long total = apiVisitCountService.findApiVisitAllCount(model.getUserId(), openResource.getUri(), DateUtil.truncateDay(new Date())); + bo.setCurVisitedCount(curVistedCount); + bo.setTotalVisitedCount(total); + } + + authorityBoList.add(bo); + } + model.setAuthority(authority); + model.setAuthorityBoList(authorityBoList); + return model; + } + + public Object openuriAction(ApiUserModel model) { + List authorityBoList = new ArrayList(); + List openResourceList = openResourceService.findAll(); + String userId = model.getUserId().toString(); + for (OpenResource openResource : openResourceList) { + String uri = openResource.getUri(); + AuthorityBo bo = new AuthorityBo(); + BeanUtils.copyProperties(openResource, bo); + OpenResourceCount open = openResourceCountService.findByUserId(userId, uri); + Long count = 0L; + if (open != null && open.getCount() != null) { + count = open.getCount(); + } + bo.setCount(count); + authorityBoList.add(bo); + } + Collections.sort(authorityBoList, new Comparator() { @Override public int compare(AuthorityBo o1, AuthorityBo o2) { if (o1.getCount() > o2.getCount()) { @@ -601,9 +659,9 @@ public class ApiUserController { } }); - model.setAuthorityBoList(authorityBoList); - return model; - } + model.setAuthorityBoList(authorityBoList); + return model; + } public Object saveAuthAction(ApiUserModel model, HttpServletRequest request) throws IllegalAccessException { @@ -636,13 +694,13 @@ public class ApiUserController { totalCountMap.put(model.getUri(), model.getSum()); authority.setTotalCountMap(totalCountMap); } - if(model.getIsCheckCount() !=null) { - Map urisMap = authority.getOpenResourseUrisMap(); - if(urisMap==null) { - urisMap = new HashMap(); - } - urisMap.put(model.getUri(), model.getIsCheckCount()); - authority.setOpenResourseUrisMap(urisMap); + if (model.getIsCheckCount() != null) { + Map urisMap = authority.getOpenResourseUrisMap(); + if (urisMap == null) { + urisMap = new HashMap(); + } + urisMap.put(model.getUri(), model.getIsCheckCount()); + authority.setOpenResourseUrisMap(urisMap); } if (model.isHasAuth() && !authority.getOpenResourseUris().contains(model.getUri())) { authority.getOpenResourseUris().add(model.getUri()); @@ -671,17 +729,17 @@ public class ApiUserController { List openResourceList = openResourceService.findAll(); boolean save = false; - if (authority == null) { + if (authority == null) { save = true; authority = new ApiUserAuthority(); } authority.setUserId(userId); authority.setSupportLatLng(model.isSupportLatLng()); - Map limit = string2map(model.getLimitCountMap()); - Map total = string2map(model.getTotalCountMap()); - Map uriMap = string2map(model.getOpenResourseUrisMap()); - authority.setLimitCountMap(limit); - authority.setTotalCountMap(total); + Map limit = string2map(model.getLimitCountMap()); + Map total = string2map(model.getTotalCountMap()); + Map uriMap = string2map(model.getOpenResourseUrisMap()); + authority.setLimitCountMap(limit); + authority.setTotalCountMap(total); List uris = new ArrayList(); for (OpenResource openResource : openResourceList) { if (model.getUri().indexOf(openResource.getUri()) > -1) { @@ -689,13 +747,13 @@ public class ApiUserController { } } authority.setOpenResourseUris(uris); - Map openResourseUrisMap = authority.getOpenResourseUrisMap(); - if(null!=uriMap&&!uriMap.isEmpty()) { - for(String url : uriMap.keySet()) { - openResourseUrisMap.put(url, uriMap.get(url)); + Map openResourseUrisMap = authority.getOpenResourseUrisMap(); + if (null != uriMap && !uriMap.isEmpty()) { + for (String url : uriMap.keySet()) { + openResourseUrisMap.put(url, uriMap.get(url)); } } - + if (save) { apiUserAuthorityService.update(authority); } else { @@ -704,1002 +762,1002 @@ public class ApiUserController { return model; } - public Object clickStatAction(ApiUserModel model) { - return model; - } - - public Object pandectAction(ApiUserModel model) throws Throwable{ - Date startDate = null; - Date endDate = null; - - if(model.getWay()==null){ - model.setWay(0); - } - if(StringUtils.isNotBlank(model.getQuery())){ - - startDate = DateUtil.add(DateUtil.formatToYYYYMMDD(new Date()), Integer.parseInt(model.getQuery())); - endDate = DateUtil.parseStringToDate(DateUtil.formatToYYYYMMDD(new Date())); - } - - if(StringUtils.isNotBlank(model.getBegDate())){ - startDate = DateUtil.parseStringToDate(model.getBegDate()); - } - if(StringUtils.isNotBlank(model.getEndDate())){ - endDate = DateUtil.parseStringToDate(model.getEndDate()); - } - - - if(startDate == null && endDate==null){ - startDate = DateUtil.add(DateUtil.formatToYYYYMMDD(new Date()), -8); - endDate = DateUtil.parseStringToDate(DateUtil.formatToYYYYMMDD(new Date())); - model.setQuery("-8"); - } - - - List analys = openUriAnalyService.findOpenUriAnalyLogs(model.getUserId(), null, startDate, endDate); - - if(startDate!= null && endDate!=null && startDate!=endDate && !model.getQuery().equals("-1")){ - Map map = new HashMap(); - List list = new ArrayList(); - for(OpenUriAnaly bo : analys){ - Integer count = (Integer) map.get(DateUtil.formatToYYYYMMDD(bo.getStatDate())); - if(count == null){ - if(!list.contains(bo.getStatDate())){ - list.add(bo.getStatDate()); - } - map.put(DateUtil.formatToYYYYMMDD(bo.getStatDate()), bo.getUrlClickCount()); - }else{ - map.put(DateUtil.formatToYYYYMMDD(bo.getStatDate()), count + bo.getUrlClickCount()); - } - - } - - Collections.sort(list); - if(model.getQuery().equals("-14")){ - List> ret = new ArrayList>(); - String d1 = DateUtil.formatToYYYYMMDD(startDate); - List times = null; - String d2 = DateUtil.formatToYYYYMMDD(endDate); - while(!d1.equals(d2)){ - if(ret.size()==0 ||times.size()==7){ - times = new ArrayList(); - ret.add(times); - } - times.add(d1); - d1 = DateUtil.formatToYYYYMMDD(DateUtil.add(DateUtil.parseStringToDate(d1), 1)); - } - List dates = ret.get(0); - List weeks = new ArrayList(); - for(String date : dates){ - String day = DateUtil.getWeekOfDate(date, new SimpleDateFormat("yyyy-MM-dd")); - weeks.add(day); - } - model.setxAxis(toXAxis2(weeks)); - model.setChartSeries(toSeries2(map, ret)); - - }else{ - model.setxAxis(toXAxis(list)); - model.setChartSeries(toSeries(map, list)); - } + public Object clickStatAction(ApiUserModel model) { + return model; + } - }else{ - int totalCount = 0; - for(OpenUriAnaly bo : analys){ - totalCount = totalCount + bo.getUrlClickCount(); - } - model.setTotalCount(totalCount); - } - - return model; - } - - private String toSeries(Map map, List list){ - String s = ""; - for(int i=0;i map, List> dates){ - String s = ""; - for(int k=0; k dateList = dates.get(k); - String temp = ""; - for(int i=0;i bos, List list){ - JSONArray ja = new JSONArray(); - for(Date temp : list){ - String tempStr = DateUtil.formatToYYYYMMDD(temp); - for(StatAnalyBo bo : bos){ - String dateStr = bo.getKey(); - if(dateStr.equals(tempStr)){ - ja.put(bo.getCount()); - break; - } - } - - } - return ja.toString(); - } - - - private String toXAxis(List list){ - String categories = ""; - for(int i=0;i list){ - String categories = ""; - for(int i=0;i cities; - if(StringUtils.isNotBlank(citys)){ - cities = Arrays.asList(StringUtils.split(citys,"|")); - }else{ - cities = new ArrayList(); - } - List analys = openUriAnalyService.findOpenUriAnalyLogs(model.getUserId(), null, startDate, endDate); - List bos = null; - List eachCityBos=null; - if(model.getWay() == null){ - model.setWay(1); - } + if (model.getWay() == null) { + model.setWay(0); + } + if (StringUtils.isNotBlank(model.getQuery())) { - if(model.getWay()==1){ - bos = createAnalyBosByUser(analys); - }else if(model.getWay() == 2){ - bos = createAnalyBosByLink(analys); - }else if(model.getWay() == 3){ - if(cities.size()!=0) { - List apiCountCities = apiCountCityService.findApiCountCity(cities, startDate, endDate); - eachCityBos = getEachCityBos(apiCountCities); - } - bos = createAnalyBosByLink(analys); - } - if(model.getWay()==1){ - long date = DateUtil.parseStringToDate("2016-11-23").getTime(); - if(startDate.getTime()>=date && endDate.getTime()>date){ - List apiInvokeStatisticalList = apiInvokeStatisticalService.findApiInvokeStatisticalList(model.getUserId(), startDate, endDate); - if(bos!=null){ - for (StatAnalyBo boTemp : bos) { - Integer userId = boTemp.getUserId(); - Integer successEffectiveTime=0; - Integer successInvalidTime=0; - Integer defeatTime=0; - for (ApiInvokeStatistical apiInvokeStatistical : apiInvokeStatisticalList) { - if(apiInvokeStatistical.getUserId().equals(userId.toString())){ - successEffectiveTime=successEffectiveTime+apiInvokeStatistical.getSuccessEffectiveTime(); - successInvalidTime=successInvalidTime+apiInvokeStatistical.getSuccessInvalidTime(); - defeatTime=defeatTime+apiInvokeStatistical.getDefeatTime(); - } - } - boTemp.setSuccessEffectiveTime(successEffectiveTime); - boTemp.setSuccessInvalidTime(successInvalidTime); - boTemp.setDefeatTime(defeatTime); - } - } - } - List userIds = new ArrayList(); - for (StatAnalyBo boTemp : bos) { - userIds.add(Long.valueOf(boTemp.getUserId())); - List apiVisitCounts = apiVisitCountService.findAllApiVisitCount(Long.valueOf(boTemp.getUserId()), null, startDate, endDate); - int total = 0; - for(ApiVisitCount apiVisitCount : apiVisitCounts){ - total += apiVisitCount.getVisitCount(); - } - boTemp.setBillingCount(total); - } + startDate = DateUtil.add(DateUtil.formatToYYYYMMDD(new Date()), Integer.parseInt(model.getQuery())); + endDate = DateUtil.parseStringToDate(DateUtil.formatToYYYYMMDD(new Date())); + } + + if (StringUtils.isNotBlank(model.getBegDate())) { + startDate = DateUtil.parseStringToDate(model.getBegDate()); + } + if (StringUtils.isNotBlank(model.getEndDate())) { + endDate = DateUtil.parseStringToDate(model.getEndDate()); + } + + + if (startDate == null && endDate == null) { + startDate = DateUtil.add(DateUtil.formatToYYYYMMDD(new Date()), -8); + endDate = DateUtil.parseStringToDate(DateUtil.formatToYYYYMMDD(new Date())); + model.setQuery("-8"); + } + + + List analys = openUriAnalyService.findOpenUriAnalyLogs(model.getUserId(), null, startDate, endDate); + + if (startDate != null && endDate != null && startDate != endDate && !model.getQuery().equals("-1")) { + Map map = new HashMap(); + List list = new ArrayList(); + for (OpenUriAnaly bo : analys) { + Integer count = (Integer) map.get(DateUtil.formatToYYYYMMDD(bo.getStatDate())); + if (count == null) { + if (!list.contains(bo.getStatDate())) { + list.add(bo.getStatDate()); + } + map.put(DateUtil.formatToYYYYMMDD(bo.getStatDate()), bo.getUrlClickCount()); + } else { + map.put(DateUtil.formatToYYYYMMDD(bo.getStatDate()), count + bo.getUrlClickCount()); + } + + } + + Collections.sort(list); + if (model.getQuery().equals("-14")) { + List> ret = new ArrayList>(); + String d1 = DateUtil.formatToYYYYMMDD(startDate); + List times = null; + String d2 = DateUtil.formatToYYYYMMDD(endDate); + while (!d1.equals(d2)) { + if (ret.size() == 0 || times.size() == 7) { + times = new ArrayList(); + ret.add(times); + } + times.add(d1); + d1 = DateUtil.formatToYYYYMMDD(DateUtil.add(DateUtil.parseStringToDate(d1), 1)); + } + List dates = ret.get(0); + List weeks = new ArrayList(); + for (String date : dates) { + String day = DateUtil.getWeekOfDate(date, new SimpleDateFormat("yyyy-MM-dd")); + weeks.add(day); + } + model.setxAxis(toXAxis2(weeks)); + model.setChartSeries(toSeries2(map, ret)); + + } else { + model.setxAxis(toXAxis(list)); + model.setChartSeries(toSeries(map, list)); + } + + } else { + int totalCount = 0; + for (OpenUriAnaly bo : analys) { + totalCount = totalCount + bo.getUrlClickCount(); + } + model.setTotalCount(totalCount); + } + + return model; + } + + private String toSeries(Map map, List list) { + String s = ""; + for (int i = 0; i < list.size(); i++) { + Date date = list.get(i); + int count = (Integer) map.get(DateUtil.formatToYYYYMMDD(date)); + if (i + 1 == list.size()) { + s = s + String.valueOf(count); + } else { + s = s + String.valueOf(count) + ","; + } + } + + return "{name:'访问量',data:[" + s + "]}"; + } + + private String toSeries2(Map map, List> dates) { + String s = ""; + for (int k = 0; k < dates.size(); k++) { + List dateList = dates.get(k); + String temp = ""; + for (int i = 0; i < dateList.size(); i++) { + String date = dateList.get(i); + int count = (Integer) map.get(date); + + if (i + 1 == dateList.size()) { + String name = "上周"; + if (k == 1) { + name = "最近7天"; + } + temp = "{name:'" + name + "',data:[" + temp + String.valueOf(count) + "]}"; + } else { + temp = temp + String.valueOf(count) + ","; + } + } + if (k == 1) { + s = s + "," + temp; + } else { + s = temp; + } + + } + + return s; + } + + private String toSeries(List bos, List list) { + JSONArray ja = new JSONArray(); + for (Date temp : list) { + String tempStr = DateUtil.formatToYYYYMMDD(temp); + for (StatAnalyBo bo : bos) { + String dateStr = bo.getKey(); + if (dateStr.equals(tempStr)) { + ja.put(bo.getCount()); + break; + } + } + + } + return ja.toString(); + } + + + private String toXAxis(List list) { + String categories = ""; + for (int i = 0; i < list.size(); i++) { + Date date = list.get(i); + //ja.put(DateUtil.formatToYYYYMMDD(date)); + if (i + 1 == list.size()) { + categories = categories + "'" + DateUtil.formatToYYYYMMDD(date) + "'"; + } else { + categories = categories + "'" + DateUtil.formatToYYYYMMDD(date) + "',"; + } + } + + return categories; + } + + private String toXAxis2(List list) { + String categories = ""; + for (int i = 0; i < list.size(); i++) { + String value = list.get(i); + //ja.put(DateUtil.formatToYYYYMMDD(date)); + if (i + 1 == list.size()) { + categories = categories + "'" + value + "'"; + } else { + categories = categories + "'" + value + "',"; + } + } + + return categories; + } + + public Object apiVisitStatAction(ApiUserModel model) { + Date startDate = null; + Date endDate = null; + if (StringUtils.isBlank(model.getBegDate()) && StringUtils.isBlank(model.getEndDate())) { + startDate = DateUtil.add(DateUtil.formatToYYYYMMDD(new Date()), -7); + endDate = DateUtil.parseStringToDate(DateUtil.formatToYYYYMMDD(new Date())); + } else { + if (StringUtils.isNotBlank(model.getBegDate())) { + startDate = DateUtil.parseStringToDate(model.getBegDate()); + } + if (StringUtils.isNotBlank(model.getEndDate())) { + endDate = DateUtil.parseStringToDate(model.getEndDate()); + } + + } + if (startDate != null) { + model.setBegDate(DateUtil.formatToYYYYMMDD(startDate)); + } + + if (endDate != null) { + model.setEndDate(DateUtil.formatToYYYYMMDD(endDate)); + } + + String citys = model.getCitys(); + List cities; + if (StringUtils.isNotBlank(citys)) { + cities = Arrays.asList(StringUtils.split(citys, "|")); + } else { + cities = new ArrayList(); + } + List analys = openUriAnalyService.findOpenUriAnalyLogs(model.getUserId(), null, startDate, endDate); + List bos = null; + List eachCityBos = null; + if (model.getWay() == null) { + model.setWay(1); + } + + if (model.getWay() == 1) { + bos = createAnalyBosByUser(analys); + } else if (model.getWay() == 2) { + bos = createAnalyBosByLink(analys); + } else if (model.getWay() == 3) { + if (cities.size() != 0) { + List apiCountCities = apiCountCityService.findApiCountCity(cities, startDate, endDate); + eachCityBos = getEachCityBos(apiCountCities); + } + bos = createAnalyBosByLink(analys); + } + if (model.getWay() == 1) { + long date = DateUtil.parseStringToDate("2016-11-23").getTime(); + if (startDate.getTime() >= date && endDate.getTime() > date) { + List apiInvokeStatisticalList = apiInvokeStatisticalService.findApiInvokeStatisticalList(model.getUserId(), startDate, endDate); + if (bos != null) { + for (StatAnalyBo boTemp : bos) { + Integer userId = boTemp.getUserId(); + Integer successEffectiveTime = 0; + Integer successInvalidTime = 0; + Integer defeatTime = 0; + for (ApiInvokeStatistical apiInvokeStatistical : apiInvokeStatisticalList) { + if (apiInvokeStatistical.getUserId().equals(userId.toString())) { + successEffectiveTime = successEffectiveTime + apiInvokeStatistical.getSuccessEffectiveTime(); + successInvalidTime = successInvalidTime + apiInvokeStatistical.getSuccessInvalidTime(); + defeatTime = defeatTime + apiInvokeStatistical.getDefeatTime(); + } + } + boTemp.setSuccessEffectiveTime(successEffectiveTime); + boTemp.setSuccessInvalidTime(successInvalidTime); + boTemp.setDefeatTime(defeatTime); + } + } + } + List userIds = new ArrayList(); + for (StatAnalyBo boTemp : bos) { + userIds.add(Long.valueOf(boTemp.getUserId())); + List apiVisitCounts = apiVisitCountService.findAllApiVisitCount(Long.valueOf(boTemp.getUserId()), null, startDate, endDate); + int total = 0; + for (ApiVisitCount apiVisitCount : apiVisitCounts) { + total += apiVisitCount.getVisitCount(); + } + boTemp.setBillingCount(total); + } + + List apiUsers = apiUserService.findApiUserByIds(userIds); + Map idUserMap = new HashMap(); + for (ApiUser apiUser : apiUsers) { + idUserMap.put(apiUser.getId(), apiUser); + } + for (StatAnalyBo boTemp : bos) { + ApiUser apiUser = idUserMap.get(Long.valueOf(boTemp.getUserId())); + if (apiUser != null) { + boTemp.setPurpose(apiUser.getPurpose()); + } + } + } + if (model.getWay() != 3) { + model.setStatAnalyBoList(sortStatAnaly(bos)); + model.setChartSeries(toChartString(bos)); + } else { + model.setChartSeries(toChartString(bos)); + model.setEachCityBoList(eachCityBos); + } + List resources = openResourceService.findOpenResource(null); + model.setResourceMap(converMapData(resources)); + return model; + } + + + public Object userVisitStatAction(ApiUserModel model) { + Date startDate = null; + Date endDate = null; + if (StringUtils.isNotBlank(model.getBegDate())) { + startDate = DateUtil.parseStringToDate(model.getBegDate()); + } + if (StringUtils.isNotBlank(model.getEndDate())) { + endDate = DateUtil.parseStringToDate(model.getEndDate()); + } + + List analys = openUriAnalyService.findOpenUriAnalyLogs(model.getUserId(), model.getUri(), startDate, endDate); + List bos = null; + + if (StringUtils.isBlank(model.getQuery()) && model.getWay() == 2) { + model.setQuery("uri"); + } else if (StringUtils.isBlank(model.getQuery()) && model.getWay() == 1) { + model.setQuery("user"); + } - List apiUsers = apiUserService.findApiUserByIds(userIds); - Map idUserMap = new HashMap(); - for(ApiUser apiUser : apiUsers){ - idUserMap.put(apiUser.getId(), apiUser); - } - for (StatAnalyBo boTemp : bos) { - ApiUser apiUser = idUserMap.get(Long.valueOf(boTemp.getUserId())); - if(apiUser != null){ - boTemp.setPurpose(apiUser.getPurpose()); - } - } - } - if(model.getWay()!=3) { - model.setStatAnalyBoList(sortStatAnaly(bos)); - model.setChartSeries(toChartString(bos)); - } - else { - model.setChartSeries(toChartString(bos)); - model.setEachCityBoList(eachCityBos); - } - List resources = openResourceService.findOpenResource(null); - model.setResourceMap(converMapData(resources)); - return model; - } - - - public Object userVisitStatAction(ApiUserModel model){ - Date startDate = null; - Date endDate = null; - if(StringUtils.isNotBlank(model.getBegDate())){ - startDate = DateUtil.parseStringToDate(model.getBegDate()); - } - if(StringUtils.isNotBlank(model.getEndDate())){ - endDate = DateUtil.parseStringToDate(model.getEndDate()); - } - - List analys = openUriAnalyService.findOpenUriAnalyLogs(model.getUserId(), model.getUri(), startDate, endDate); - List bos = null; - - if(StringUtils.isBlank(model.getQuery())&&model.getWay()==2){ - model.setQuery("uri"); - }else if(StringUtils.isBlank(model.getQuery())&&model.getWay()==1){ - model.setQuery("user"); - } - // if(model.getWay()==1){ // bos = createAnalyBosByUser(analys); // model.setChartSeries(toChartString(bos)); // }else if(model.getWay() == 2){ - if(model.getWay() == 2){ - User user = userService.findById(model.getUserId()); - if(user!=null){ - model.setUserName(user.getDisplayName()); - } - } - - if(model.getQuery().equals("uri")){ - bos = createAnalyBosByLink(analys); - model.setChartSeries(toChartString(bos)); - }if(model.getQuery().equals("day")){ - bos = createAnalyByCity(analys, "day"); - - List list = new ArrayList(); - - for(OpenUriAnaly bo : analys){ - if(!list.contains(bo.getStatDate())){ - list.add(bo.getStatDate()); - } - } - Collections.sort(list); - model.setxAxis(toXAxis(list)); - model.setChartSeries(toSeries(bos, list)); - - }else if(model.getQuery().equals("time")){ - bos = createAnalyByCity(analys, "time"); - model.setChartSeries(toChartString(bos)); - }else if(model.getQuery().equals("user")){ - bos = createAnalyBosByUser(analys); - model.setChartSeries(toChartString(bos)); - } - + if (model.getWay() == 2) { + User user = userService.findById(model.getUserId()); + if (user != null) { + model.setUserName(user.getDisplayName()); + } + } + + if (model.getQuery().equals("uri")) { + bos = createAnalyBosByLink(analys); + model.setChartSeries(toChartString(bos)); + } + if (model.getQuery().equals("day")) { + bos = createAnalyByCity(analys, "day"); + + List list = new ArrayList(); + + for (OpenUriAnaly bo : analys) { + if (!list.contains(bo.getStatDate())) { + list.add(bo.getStatDate()); + } + } + Collections.sort(list); + model.setxAxis(toXAxis(list)); + model.setChartSeries(toSeries(bos, list)); + + } else if (model.getQuery().equals("time")) { + bos = createAnalyByCity(analys, "time"); + model.setChartSeries(toChartString(bos)); + } else if (model.getQuery().equals("user")) { + bos = createAnalyBosByUser(analys); + model.setChartSeries(toChartString(bos)); + } + // } - - long date = DateUtil.parseStringToDate("2016-11-23").getTime(); - if("uri".equals(model.getQuery()) && startDate.getTime()>=date && endDate.getTime()>date){ - List apiInvokeStatisticalList = apiInvokeStatisticalService.findApiInvokeStatisticalList(model.getUserId(), startDate, endDate); - if(bos!=null && apiInvokeStatisticalList.size()>0){ - Map> resultMap = getCountByUri(apiInvokeStatisticalList); - for (StatAnalyBo boTemp : bos) { - String url = boTemp.getKey(); - boTemp.setSuccessEffectiveTime(resultMap.get(url).get("successEffectiveCount")); - boTemp.setSuccessInvalidTime(resultMap.get(url).get("successInvalidCount")); - boTemp.setDefeatTime(resultMap.get(url).get("defeatCount")); - } - } - } - for (StatAnalyBo boTemp : bos) { - List apiVisitCounts = apiVisitCountService.findAllApiVisitCount(model.getUserId(), boTemp.getKey(), startDate, endDate); - int total = 0; - for(ApiVisitCount apiVisitCount : apiVisitCounts){ - total += apiVisitCount.getVisitCount(); - } - boTemp.setBillingCount(total); - } - - List resources = openResourceService.findOpenResource(null); - model.setResourceMap(converMapData(resources)); - model.setStatAnalyBoList(sortStatAnaly(bos)); - - return model; - } - - public Object detailVisitStatAction(ApiUserModel model){ - Date startDate = null; - Date endDate = null; - if(StringUtils.isNotBlank(model.getBegDate())){ - startDate = DateUtil.parseStringToDate(model.getBegDate()); - } - if(StringUtils.isNotBlank(model.getEndDate())){ - endDate = DateUtil.parseStringToDate(model.getEndDate()); - } - - - List analys = openUriAnalyService.findOpenUriAnalyLogs(model.getUserId(), model.getUri(), startDate, endDate); - if(StringUtils.isBlank(model.getQuery())){ - model.setQuery("city"); - } - - List bos = null; - if(model.getQuery().equals("city")){ - bos = createAnalyByCity(analys, "city"); - }else if(model.getQuery().equals("time")){ - bos = createAnalyByCity(analys, "time"); - } - - model.setStatAnalyBoList(sortStatAnaly(bos)); - model.setChartSeries(toChartString(bos)); - - User user = userService.findById(model.getUserId()); - if(user!=null){ - model.setUserName(user.getDisplayName()); - }else{ - model.setUserName(model.getUserId().toString()); - } - return model; - } - public Object importExcelAction(HttpServletRequest request,ApiUserModel model){ - String citys=request.getParameter("city"); - String begDate=request.getParameter("begDate"); - String enDate=request.getParameter("endDate"); - Date startDate = null; - Date endDate = null; - if(StringUtils.isBlank(begDate) && StringUtils.isBlank(enDate)){ - startDate = DateUtil.add(DateUtil.formatToYYYYMMDD(new Date()), -7); - endDate = DateUtil.parseStringToDate(DateUtil.formatToYYYYMMDD(new Date())); - }else{ - if(StringUtils.isNotBlank(begDate)){ - startDate = DateUtil.parseStringToDate(begDate); - } - if(StringUtils.isNotBlank(enDate)){ - endDate = DateUtil.parseStringToDate(enDate); - } + long date = DateUtil.parseStringToDate("2016-11-23").getTime(); + if ("uri".equals(model.getQuery()) && startDate.getTime() >= date && endDate.getTime() > date) { + List apiInvokeStatisticalList = apiInvokeStatisticalService.findApiInvokeStatisticalList(model.getUserId(), startDate, endDate); + if (bos != null && apiInvokeStatisticalList.size() > 0) { + Map> resultMap = getCountByUri(apiInvokeStatisticalList); + for (StatAnalyBo boTemp : bos) { + String url = boTemp.getKey(); + boTemp.setSuccessEffectiveTime(resultMap.get(url).get("successEffectiveCount")); + boTemp.setSuccessInvalidTime(resultMap.get(url).get("successInvalidCount")); + boTemp.setDefeatTime(resultMap.get(url).get("defeatCount")); + } + } + } + for (StatAnalyBo boTemp : bos) { + List apiVisitCounts = apiVisitCountService.findAllApiVisitCount(model.getUserId(), boTemp.getKey(), startDate, endDate); + int total = 0; + for (ApiVisitCount apiVisitCount : apiVisitCounts) { + total += apiVisitCount.getVisitCount(); + } + boTemp.setBillingCount(total); + } - } - String Array[]=StringUtils.split(citys,"|"); - List cities=new ArrayList(); - if(Array!=null) { - for (int i = 0; i < Array.length; i++) { - cities.add(Array[i]); - } - } - List apiCountCities =null; - List eachCityBos=null; - if(cities.size()!=0) { - apiCountCities=apiCountCityService.findApiCountCity(cities, startDate, endDate); - eachCityBos = getEachCityBos(apiCountCities); - } + List resources = openResourceService.findOpenResource(null); + model.setResourceMap(converMapData(resources)); + model.setStatAnalyBoList(sortStatAnaly(bos)); - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFCellStyle cellStyle = workbook.createCellStyle(); - cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); - cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); - HSSFSheet sheet = workbook.createSheet("数据导出"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell0 = row.createCell(0); - HSSFCell cell1 = row.createCell(1); - HSSFCell cell2 = row.createCell(2); - HSSFCell cell3= row.createCell(3); - HSSFCell cell4= row.createCell(4); - HSSFCell cell5= row.createCell(5); - cell0.setCellValue("城市"); - cell1.setCellValue("调用总量"); - cell2.setCellValue("成功调用次数"); - cell3.setCellValue("占比"); - cell4.setCellValue("失败调用次数"); - cell5.setCellValue("占比"); - if(null!=eachCityBos) { - for (int i = 0; i < eachCityBos.size(); i++) { - HSSFRow rows = sheet.createRow(i + 1); - HSSFCell cel0 = rows.createCell(0); - HSSFCell cel1 = rows.createCell(1); - HSSFCell cel2 = rows.createCell(2); - HSSFCell cel3 = rows.createCell(3); - HSSFCell cel4 = rows.createCell(4); - HSSFCell cel5 = rows.createCell(5); - cel0.setCellValue(eachCityBos.get(i).getCity()); - cel1.setCellValue(eachCityBos.get(i).getSumTime()); - cel2.setCellValue(eachCityBos.get(i).getSuccessTime()); - cel3.setCellValue(getFour(eachCityBos.get(i).getSuccessRate()) * 100 + "%"); - cel4.setCellValue(eachCityBos.get(i).getFailTime()); - cel5.setCellValue(getFour(eachCityBos.get(i).getFailRate()) * 100 + "%"); - } - } - HttpServletResponse response = ActionContext.getContext().getResponse(); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/x-download;charset=UTF-8"); - response.setHeader( "Content-Disposition", "attachment;filename=daochu.xls"); - try { - OutputStream os=response.getOutputStream(); - workbook.write(os); - os.flush(); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - private List sortApiBo(List bos){ - Collections.sort(bos, new Comparator() { - @Override - public int compare(OpenUriAnalyBo o1, OpenUriAnalyBo o2) { - if(o1.getUrlClickCount() > o2.getUrlClickCount()) { - return -1; - }else if(o1.getUrlClickCount() < o2.getUrlClickCount()) { - return 1; - } - return 0; - } - }); - - return bos; - } - private List sortStatAnaly(List bos){ - Collections.sort(bos, new Comparator() { - @Override - public int compare(StatAnalyBo o1, StatAnalyBo o2) { - if(o1.getCount() > o2.getCount()) { - return -1; - }else if(o1.getCount() < o2.getCount()) { - return 1; - } - return 0; - } - }); - - return bos; - } - private Map converMapData(List resources){ - Map map = new HashMap(); - for(OpenResource resource : resources){ - map.put(resource.getUri(), resource.getName()); - } - return map; - } - - - private List createAnalyBosByLink(List analys){ + return model; + } + + public Object detailVisitStatAction(ApiUserModel model) { + Date startDate = null; + Date endDate = null; + if (StringUtils.isNotBlank(model.getBegDate())) { + startDate = DateUtil.parseStringToDate(model.getBegDate()); + } + if (StringUtils.isNotBlank(model.getEndDate())) { + endDate = DateUtil.parseStringToDate(model.getEndDate()); + } - Map ret = new HashMap(); - Map> urlCodeMap = new HashMap>(); - int total = 0; - for(OpenUriAnaly openUriAnaly : analys){ - Integer temp = ret.get(openUriAnaly.getUrl()); - if(temp == null){ - ret.put(openUriAnaly.getUrl(), openUriAnaly.getUrlClickCount()); - }else{ - ret.put(openUriAnaly.getUrl(), temp + openUriAnaly.getUrlClickCount()); - } - Map codeMap = urlCodeMap.get(openUriAnaly.getUrl()); - if(codeMap == null){ - codeMap = new HashMap(); - urlCodeMap.put(openUriAnaly.getUrl(), codeMap); - } - Map analyCodeMap = openUriAnaly.getCodeMap(); - for(String code : analyCodeMap.keySet()){ - Integer count = (Integer) analyCodeMap.get(code); - if("200".equals(code)){ - Integer successCount = codeMap.get("successCount"); - if(successCount == null){ - codeMap.put("successCount", count); - }else{ - codeMap.put("successCount", successCount + count); - } - }else{ - Integer defeatCount = codeMap.get("defeatCount"); - if(defeatCount == null){ - codeMap.put("defeatCount", count); - }else{ - codeMap.put("defeatCount", defeatCount + count); - } - } - } - total = total + openUriAnaly.getUrlClickCount(); - } + List analys = openUriAnalyService.findOpenUriAnalyLogs(model.getUserId(), model.getUri(), startDate, endDate); + if (StringUtils.isBlank(model.getQuery())) { + model.setQuery("city"); + } - List bos = new ArrayList(); - int index = 0; - double totalPercent = 0; - for(String url : ret.keySet()){ - Integer count = ret.get(url); - double percent = 0; - if(index+1==ret.size()){ - percent = 100 - totalPercent; - }else{ - double a1 = count; - double val = a1*10000/(double)total; - percent = DataUtil.roundDouble(val/100, 2); - totalPercent = totalPercent + percent; - } - StatAnalyBo bo = new StatAnalyBo(); - bo.setKey(url); - bo.setCount(count); - bo.setPercent(percent); - Map codeMap = urlCodeMap.get(url); - bo.setSuccessTime(codeMap.get("successCount")); - bo.setDefeatTime(codeMap.get("defeatCount")); - if(codeMap.get("successCount") != null){ - bo.setSuccessRate(DataUtil.roundDouble((codeMap.get("successCount") * 100)/(double)count, 2)); - } - bos.add(bo); + List bos = null; + if (model.getQuery().equals("city")) { + bos = createAnalyByCity(analys, "city"); + } else if (model.getQuery().equals("time")) { + bos = createAnalyByCity(analys, "time"); + } - } - return bos; - } + model.setStatAnalyBoList(sortStatAnaly(bos)); + model.setChartSeries(toChartString(bos)); - private List getEachCityBos(List list){ - List eachCityBos=new ArrayList(); - Map> map=new HashMap>(); - for(ApiCountCity apiCountCity:list){ - if(map.containsKey(apiCountCity.getCity())){ - List list1=new ArrayList(); - List list2=map.get(apiCountCity.getCity()); - list1.add(list2.get(0)+apiCountCity.getSuccess()); - list1.add(list2.get(1)+apiCountCity.getFail()); - map.put(apiCountCity.getCity(),list1); - } - else { - List list1=new ArrayList(); - list1.add(apiCountCity.getSuccess()); - list1.add(apiCountCity.getFail()); - map.put(apiCountCity.getCity(),list1); - } - } - for(Object o:map.keySet()){ - List listm=map.get(o); - String city=o.toString(); - int success=listm.get(0); - int fail=listm.get(1); - int sum=success+fail; - double successTimeRate=getFour((double)success/(double)sum); - double failTimeRate=getFour((double)fail/(double)sum); - EachCityBo eachCityBo=new EachCityBo(); - eachCityBo.setCity(city); - eachCityBo.setSumTime(sum); - eachCityBo.setSuccessTime(success); - eachCityBo.setFailTime(fail); - eachCityBo.setSuccessRate(successTimeRate); - eachCityBo.setFailRate(failTimeRate); - eachCityBos.add(eachCityBo); - } - return eachCityBos; - } + User user = userService.findById(model.getUserId()); + if (user != null) { + model.setUserName(user.getDisplayName()); + } else { + model.setUserName(model.getUserId().toString()); + } + return model; + } - private double getFour(double m){ - BigDecimal b = new BigDecimal(m); - double f1 = b.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue(); - return f1; - } - - private List createAnalyByCity(List analys, String field){ - Map> ret = new HashMap>(); - int total = 0; - for(OpenUriAnaly openUriAnaly : analys){ - Map resultMap = null; - if(field.equals("day")){ - resultMap = (Map) ret.get(DateUtil.formatToYYYYMMDD(openUriAnaly.getStatDate())); - if(resultMap == null){ - resultMap = new HashMap(); - ret.put(DateUtil.formatToYYYYMMDD(openUriAnaly.getStatDate()), resultMap); - } - Integer count = (Integer) resultMap.get("count"); - if(count == null){ - resultMap.put("count", openUriAnaly.getUrlClickCount()); - }else{ - resultMap.put("count", count + openUriAnaly.getUrlClickCount()); - } - total = total + openUriAnaly.getUrlClickCount(); - }else{ - if(field.equals("city")){ - resultMap = openUriAnaly.getCityMap(); - }else if(field.equals("time")){ - resultMap = openUriAnaly.getTimeMap(); - } - Iterator it = resultMap.keySet().iterator(); - while(it.hasNext()){ - String key = it.next(); - int count = (Integer) resultMap.get(key); - Map dataMap = (Map) ret.get(key); - if(dataMap == null){ - dataMap = new HashMap(); - ret.put(key, dataMap); - dataMap.put("count", count); - }else{ - dataMap.put("count", (Integer) dataMap.get("count")+count); - } - total = total + count; - } - } - } - - - Iterator it = ret.keySet().iterator(); - - List bos = new ArrayList(); - int index = 0; - double totalPercent = 0; - while(it.hasNext()){ - String key = (String) it.next(); - Map detailMap = ret.get(key); - - int count = (Integer) detailMap.get("count"); - double percent = 0; - - if(index+1==ret.size()){ - percent = 100 - totalPercent; - }else{ - double a1 = count; - double val = a1*10000/(double)total; - int scale = 2; - percent = DataUtil.roundDouble(val/100, scale); - totalPercent = totalPercent + percent; - } - index++; - - StatAnalyBo bo = new StatAnalyBo(); - bo.setKey(key); - bo.setPercent(percent); - bo.setCount(count); - bos.add(bo); - } - - - return bos; - } - - private List createAnalyBosByUser(List analys){ - Map ret = new HashMap(); - - int total = 0; - for(OpenUriAnaly openUriAnaly : analys){ - OpenUriAnaly temp = ret.get(openUriAnaly.getApiUserId()); - if(temp == null){ - ret.put(openUriAnaly.getApiUserId(), openUriAnaly); - }else{ - temp.setUrlClickCount(temp.getUrlClickCount()+openUriAnaly.getUrlClickCount()); - ret.put(openUriAnaly.getApiUserId(), temp); - } - - total = total + openUriAnaly.getUrlClickCount(); - } - List bos = new ArrayList(); - Iterator it = ret.keySet().iterator(); - - List users = this.userService.findAllUsers(); - - int index = 0; - double totalPercent = 0; - while(it.hasNext()){ - OpenUriAnaly openUriAnaly = ret.get(it.next()); - - double percent = 0; - - if(index+1==ret.size()){ - percent = 100 - totalPercent; - }else{ - double a1 = openUriAnaly.getUrlClickCount(); - double val = a1*10000/(double)total; - int scale = 2; - percent = DataUtil.roundDouble(val/100, scale); - //percent = getPercent(percent, scale, val); - totalPercent = totalPercent + percent; - } - index++; - - String name = null; - for(User user : users){ - if(openUriAnaly.getApiUserId()==user.getId()){ - name = user.getDisplayName(); - break; - } - } - - StatAnalyBo bo = new StatAnalyBo(); - if(StringUtils.isNotBlank(name)){ - bo.setKey(name); - }else{ - bo.setKey(openUriAnaly.getApiUserId().toString()); - } - - bo.setCount(openUriAnaly.getUrlClickCount()); - bo.setPercent(percent); - bo.setUserId(openUriAnaly.getApiUserId()); - bos.add(bo); - } - return bos; - } - - private double getPercent(double percent, int scale, double val){ - if(percent==0){ - while(scale<=8){ - if(percent==0){ - scale = scale+1; - percent = DataUtil.roundDouble(val/100, scale); - }else{ - break; - } - } - } - return percent; - } - - private String toChartString(List bos, int way) { - JSONArray ja = new JSONArray(); - for (OpenUriAnalyBo bo : bos) { + public Object importExcelAction(HttpServletRequest request, ApiUserModel model) { + String citys = request.getParameter("city"); + String begDate = request.getParameter("begDate"); + String enDate = request.getParameter("endDate"); + Date startDate = null; + Date endDate = null; + if (StringUtils.isBlank(begDate) && StringUtils.isBlank(enDate)) { + startDate = DateUtil.add(DateUtil.formatToYYYYMMDD(new Date()), -7); + endDate = DateUtil.parseStringToDate(DateUtil.formatToYYYYMMDD(new Date())); + } else { + if (StringUtils.isNotBlank(begDate)) { + startDate = DateUtil.parseStringToDate(begDate); + } + if (StringUtils.isNotBlank(enDate)) { + endDate = DateUtil.parseStringToDate(enDate); + } + + } + String Array[] = StringUtils.split(citys, "|"); + List cities = new ArrayList(); + if (Array != null) { + for (int i = 0; i < Array.length; i++) { + cities.add(Array[i]); + } + } + List apiCountCities = null; + List eachCityBos = null; + if (cities.size() != 0) { + apiCountCities = apiCountCityService.findApiCountCity(cities, startDate, endDate); + eachCityBos = getEachCityBos(apiCountCities); + } + + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFCellStyle cellStyle = workbook.createCellStyle(); + cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); + cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); + HSSFSheet sheet = workbook.createSheet("数据导出"); + HSSFRow row = sheet.createRow(0); + HSSFCell cell0 = row.createCell(0); + HSSFCell cell1 = row.createCell(1); + HSSFCell cell2 = row.createCell(2); + HSSFCell cell3 = row.createCell(3); + HSSFCell cell4 = row.createCell(4); + HSSFCell cell5 = row.createCell(5); + cell0.setCellValue("城市"); + cell1.setCellValue("调用总量"); + cell2.setCellValue("成功调用次数"); + cell3.setCellValue("占比"); + cell4.setCellValue("失败调用次数"); + cell5.setCellValue("占比"); + if (null != eachCityBos) { + for (int i = 0; i < eachCityBos.size(); i++) { + HSSFRow rows = sheet.createRow(i + 1); + HSSFCell cel0 = rows.createCell(0); + HSSFCell cel1 = rows.createCell(1); + HSSFCell cel2 = rows.createCell(2); + HSSFCell cel3 = rows.createCell(3); + HSSFCell cel4 = rows.createCell(4); + HSSFCell cel5 = rows.createCell(5); + cel0.setCellValue(eachCityBos.get(i).getCity()); + cel1.setCellValue(eachCityBos.get(i).getSumTime()); + cel2.setCellValue(eachCityBos.get(i).getSuccessTime()); + cel3.setCellValue(getFour(eachCityBos.get(i).getSuccessRate()) * 100 + "%"); + cel4.setCellValue(eachCityBos.get(i).getFailTime()); + cel5.setCellValue(getFour(eachCityBos.get(i).getFailRate()) * 100 + "%"); + } + } + HttpServletResponse response = ActionContext.getContext().getResponse(); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/x-download;charset=UTF-8"); + response.setHeader("Content-Disposition", "attachment;filename=daochu.xls"); + try { + OutputStream os = response.getOutputStream(); + workbook.write(os); + os.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + private List sortApiBo(List bos) { + Collections.sort(bos, new Comparator() { + @Override + public int compare(OpenUriAnalyBo o1, OpenUriAnalyBo o2) { + if (o1.getUrlClickCount() > o2.getUrlClickCount()) { + return -1; + } else if (o1.getUrlClickCount() < o2.getUrlClickCount()) { + return 1; + } + return 0; + } + }); + + return bos; + } + + private List sortStatAnaly(List bos) { + Collections.sort(bos, new Comparator() { + @Override + public int compare(StatAnalyBo o1, StatAnalyBo o2) { + if (o1.getCount() > o2.getCount()) { + return -1; + } else if (o1.getCount() < o2.getCount()) { + return 1; + } + return 0; + } + }); + + return bos; + } + + private Map converMapData(List resources) { + Map map = new HashMap(); + for (OpenResource resource : resources) { + map.put(resource.getUri(), resource.getName()); + } + return map; + } + + + private List createAnalyBosByLink(List analys) { + + + Map ret = new HashMap(); + Map> urlCodeMap = new HashMap>(); + int total = 0; + for (OpenUriAnaly openUriAnaly : analys) { + Integer temp = ret.get(openUriAnaly.getUrl()); + if (temp == null) { + ret.put(openUriAnaly.getUrl(), openUriAnaly.getUrlClickCount()); + } else { + ret.put(openUriAnaly.getUrl(), temp + openUriAnaly.getUrlClickCount()); + } + Map codeMap = urlCodeMap.get(openUriAnaly.getUrl()); + if (codeMap == null) { + codeMap = new HashMap(); + urlCodeMap.put(openUriAnaly.getUrl(), codeMap); + } + Map analyCodeMap = openUriAnaly.getCodeMap(); + for (String code : analyCodeMap.keySet()) { + Integer count = (Integer) analyCodeMap.get(code); + if ("200".equals(code)) { + Integer successCount = codeMap.get("successCount"); + if (successCount == null) { + codeMap.put("successCount", count); + } else { + codeMap.put("successCount", successCount + count); + } + } else { + Integer defeatCount = codeMap.get("defeatCount"); + if (defeatCount == null) { + codeMap.put("defeatCount", count); + } else { + codeMap.put("defeatCount", defeatCount + count); + } + } + } + total = total + openUriAnaly.getUrlClickCount(); + } + + List bos = new ArrayList(); + int index = 0; + double totalPercent = 0; + for (String url : ret.keySet()) { + Integer count = ret.get(url); + double percent = 0; + if (index + 1 == ret.size()) { + percent = 100 - totalPercent; + } else { + double a1 = count; + double val = a1 * 10000 / (double) total; + percent = DataUtil.roundDouble(val / 100, 2); + totalPercent = totalPercent + percent; + } + StatAnalyBo bo = new StatAnalyBo(); + bo.setKey(url); + bo.setCount(count); + bo.setPercent(percent); + Map codeMap = urlCodeMap.get(url); + bo.setSuccessTime(codeMap.get("successCount")); + bo.setDefeatTime(codeMap.get("defeatCount")); + if (codeMap.get("successCount") != null) { + bo.setSuccessRate(DataUtil.roundDouble((codeMap.get("successCount") * 100) / (double) count, 2)); + } + bos.add(bo); + + } + return bos; + } + + private List getEachCityBos(List list) { + List eachCityBos = new ArrayList(); + Map> map = new HashMap>(); + for (ApiCountCity apiCountCity : list) { + if (map.containsKey(apiCountCity.getCity())) { + List list1 = new ArrayList(); + List list2 = map.get(apiCountCity.getCity()); + list1.add(list2.get(0) + apiCountCity.getSuccess()); + list1.add(list2.get(1) + apiCountCity.getFail()); + map.put(apiCountCity.getCity(), list1); + } else { + List list1 = new ArrayList(); + list1.add(apiCountCity.getSuccess()); + list1.add(apiCountCity.getFail()); + map.put(apiCountCity.getCity(), list1); + } + } + for (Object o : map.keySet()) { + List listm = map.get(o); + String city = o.toString(); + int success = listm.get(0); + int fail = listm.get(1); + int sum = success + fail; + double successTimeRate = getFour((double) success / (double) sum); + double failTimeRate = getFour((double) fail / (double) sum); + EachCityBo eachCityBo = new EachCityBo(); + eachCityBo.setCity(city); + eachCityBo.setSumTime(sum); + eachCityBo.setSuccessTime(success); + eachCityBo.setFailTime(fail); + eachCityBo.setSuccessRate(successTimeRate); + eachCityBo.setFailRate(failTimeRate); + eachCityBos.add(eachCityBo); + } + return eachCityBos; + } + + private double getFour(double m) { + BigDecimal b = new BigDecimal(m); + double f1 = b.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue(); + return f1; + } + + private List createAnalyByCity(List analys, String field) { + Map> ret = new HashMap>(); + int total = 0; + for (OpenUriAnaly openUriAnaly : analys) { + Map resultMap = null; + if (field.equals("day")) { + resultMap = (Map) ret.get(DateUtil.formatToYYYYMMDD(openUriAnaly.getStatDate())); + if (resultMap == null) { + resultMap = new HashMap(); + ret.put(DateUtil.formatToYYYYMMDD(openUriAnaly.getStatDate()), resultMap); + } + Integer count = (Integer) resultMap.get("count"); + if (count == null) { + resultMap.put("count", openUriAnaly.getUrlClickCount()); + } else { + resultMap.put("count", count + openUriAnaly.getUrlClickCount()); + } + total = total + openUriAnaly.getUrlClickCount(); + } else { + if (field.equals("city")) { + resultMap = openUriAnaly.getCityMap(); + } else if (field.equals("time")) { + resultMap = openUriAnaly.getTimeMap(); + } + Iterator it = resultMap.keySet().iterator(); + while (it.hasNext()) { + String key = it.next(); + int count = (Integer) resultMap.get(key); + Map dataMap = (Map) ret.get(key); + if (dataMap == null) { + dataMap = new HashMap(); + ret.put(key, dataMap); + dataMap.put("count", count); + } else { + dataMap.put("count", (Integer) dataMap.get("count") + count); + } + total = total + count; + } + } + } + + + Iterator it = ret.keySet().iterator(); + + List bos = new ArrayList(); + int index = 0; + double totalPercent = 0; + while (it.hasNext()) { + String key = (String) it.next(); + Map detailMap = ret.get(key); + + int count = (Integer) detailMap.get("count"); + double percent = 0; + + if (index + 1 == ret.size()) { + percent = 100 - totalPercent; + } else { + double a1 = count; + double val = a1 * 10000 / (double) total; + int scale = 2; + percent = DataUtil.roundDouble(val / 100, scale); + totalPercent = totalPercent + percent; + } + index++; + + StatAnalyBo bo = new StatAnalyBo(); + bo.setKey(key); + bo.setPercent(percent); + bo.setCount(count); + bos.add(bo); + } + + + return bos; + } + + private List createAnalyBosByUser(List analys) { + Map ret = new HashMap(); + + int total = 0; + for (OpenUriAnaly openUriAnaly : analys) { + OpenUriAnaly temp = ret.get(openUriAnaly.getApiUserId()); + if (temp == null) { + ret.put(openUriAnaly.getApiUserId(), openUriAnaly); + } else { + temp.setUrlClickCount(temp.getUrlClickCount() + openUriAnaly.getUrlClickCount()); + ret.put(openUriAnaly.getApiUserId(), temp); + } + + total = total + openUriAnaly.getUrlClickCount(); + } + List bos = new ArrayList(); + Iterator it = ret.keySet().iterator(); + + List users = this.userService.findAllUsers(); + + int index = 0; + double totalPercent = 0; + while (it.hasNext()) { + OpenUriAnaly openUriAnaly = ret.get(it.next()); + + double percent = 0; + + if (index + 1 == ret.size()) { + percent = 100 - totalPercent; + } else { + double a1 = openUriAnaly.getUrlClickCount(); + double val = a1 * 10000 / (double) total; + int scale = 2; + percent = DataUtil.roundDouble(val / 100, scale); + //percent = getPercent(percent, scale, val); + totalPercent = totalPercent + percent; + } + index++; + + String name = null; + for (User user : users) { + if (openUriAnaly.getApiUserId() == user.getId()) { + name = user.getDisplayName(); + break; + } + } + + StatAnalyBo bo = new StatAnalyBo(); + if (StringUtils.isNotBlank(name)) { + bo.setKey(name); + } else { + bo.setKey(openUriAnaly.getApiUserId().toString()); + } + + bo.setCount(openUriAnaly.getUrlClickCount()); + bo.setPercent(percent); + bo.setUserId(openUriAnaly.getApiUserId()); + bos.add(bo); + } + return bos; + } + + private double getPercent(double percent, int scale, double val) { + if (percent == 0) { + while (scale <= 8) { + if (percent == 0) { + scale = scale + 1; + percent = DataUtil.roundDouble(val / 100, scale); + } else { + break; + } + } + } + return percent; + } + + private String toChartString(List bos, int way) { + JSONArray ja = new JSONArray(); + for (OpenUriAnalyBo bo : bos) { JSONArray array = new JSONArray(); array.put(way == 1 ? bo.getName() : bo.getUrl()); array.put(bo.getPercent()); ja.put(array); - } - return ja.toString(); - } - - private String toChartString(List bos) { - JSONArray ja = new JSONArray(); - for (StatAnalyBo bo : bos) { - JSONArray array = new JSONArray(); - if(StringUtils.isNotBlank(bo.getKey())){ - if(bo.getKey().equals("level_0")){ - array.put("0s"); - }else if(bo.getKey().equals("level_1")){ - array.put("1s以下"); - }else if(bo.getKey().equals("level_2")){ - array.put("1-2s以下"); - }else if(bo.getKey().equals("level_3")){ - array.put("2-3s以下"); - }else if(bo.getKey().equals("level_4")){ - array.put("3s以上"); - }else if(bo.getKey().equals("level_100")){ - array.put("暂无数据"); - }else{ - array.put(bo.getKey()); - } - }else{ - array.put(bo.getUserId()); - } - - array.put(bo.getPercent()); - ja.put(array); - } - return ja.toString(); - } + } + return ja.toString(); + } - /** - * 页面查询条件 - * - * @return - */ - private String[] getCityFirstLetter() { - String[] cityFirstLetter = { "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", - "T", "W", "X", "Y", "Z" }; - return cityFirstLetter; - } + private String toChartString(List bos) { + JSONArray ja = new JSONArray(); + for (StatAnalyBo bo : bos) { + JSONArray array = new JSONArray(); + if (StringUtils.isNotBlank(bo.getKey())) { + if (bo.getKey().equals("level_0")) { + array.put("0s"); + } else if (bo.getKey().equals("level_1")) { + array.put("1s以下"); + } else if (bo.getKey().equals("level_2")) { + array.put("1-2s以下"); + } else if (bo.getKey().equals("level_3")) { + array.put("2-3s以下"); + } else if (bo.getKey().equals("level_4")) { + array.put("3s以上"); + } else if (bo.getKey().equals("level_100")) { + array.put("暂无数据"); + } else { + array.put(bo.getKey()); + } + } else { + array.put(bo.getUserId()); + } - - private Map> getCountByUri(List apiInvokeStatisticalList){ - Map> resultMap = new HashMap>(); - for (ApiInvokeStatistical apiInvokeStatistical : apiInvokeStatisticalList) { - Map detailMap = resultMap.get(apiInvokeStatistical.getRequestURI()); - if(detailMap == null){ - detailMap = new HashMap(); - resultMap.put(apiInvokeStatistical.getRequestURI(), detailMap); - } - Integer successEffectiveCount = detailMap.get("successEffectiveCount"); - Integer successInvalidCount = detailMap.get("successInvalidCount"); - Integer defeatCount = detailMap.get("defeatCount"); - if(successEffectiveCount != null){ - successEffectiveCount = successEffectiveCount + apiInvokeStatistical.getSuccessEffectiveTime(); - }else{ - successEffectiveCount = apiInvokeStatistical.getSuccessEffectiveTime(); - } - if(successInvalidCount != null){ - successInvalidCount = successInvalidCount + apiInvokeStatistical.getSuccessInvalidTime(); - }else{ - successInvalidCount = apiInvokeStatistical.getSuccessInvalidTime();; - } - if(defeatCount != null){ - defeatCount = defeatCount + apiInvokeStatistical.getDefeatTime(); - }else{ - defeatCount = apiInvokeStatistical.getDefeatTime(); - } - - detailMap.put("successEffectiveCount", successEffectiveCount); - detailMap.put("successInvalidCount", successInvalidCount); - detailMap.put("defeatCount", defeatCount); - } - - return resultMap; - } - public void setApiUserService(ApiUserService apiUserService) { - this.apiUserService = apiUserService; - } + array.put(bo.getPercent()); + ja.put(array); + } + return ja.toString(); + } - public UserService getUserService() { - return userService; - } + /** + * 页面查询条件 + * + * @return + */ + private String[] getCityFirstLetter() { + String[] cityFirstLetter = {"A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", + "T", "W", "X", "Y", "Z"}; + return cityFirstLetter; + } - public void setUserService(UserService userService) { - this.userService = userService; - } - public void setApiUserAuthorityService(ApiUserAuthorityService apiUserAuthorityService) { - this.apiUserAuthorityService = apiUserAuthorityService; - } + private Map> getCountByUri(List apiInvokeStatisticalList) { + Map> resultMap = new HashMap>(); + for (ApiInvokeStatistical apiInvokeStatistical : apiInvokeStatisticalList) { + Map detailMap = resultMap.get(apiInvokeStatistical.getRequestURI()); + if (detailMap == null) { + detailMap = new HashMap(); + resultMap.put(apiInvokeStatistical.getRequestURI(), detailMap); + } + Integer successEffectiveCount = detailMap.get("successEffectiveCount"); + Integer successInvalidCount = detailMap.get("successInvalidCount"); + Integer defeatCount = detailMap.get("defeatCount"); + if (successEffectiveCount != null) { + successEffectiveCount = successEffectiveCount + apiInvokeStatistical.getSuccessEffectiveTime(); + } else { + successEffectiveCount = apiInvokeStatistical.getSuccessEffectiveTime(); + } + if (successInvalidCount != null) { + successInvalidCount = successInvalidCount + apiInvokeStatistical.getSuccessInvalidTime(); + } else { + successInvalidCount = apiInvokeStatistical.getSuccessInvalidTime(); + ; + } + if (defeatCount != null) { + defeatCount = defeatCount + apiInvokeStatistical.getDefeatTime(); + } else { + defeatCount = apiInvokeStatistical.getDefeatTime(); + } - public void setOpenResourceService(OpenResourceService openResourceService) { - this.openResourceService = openResourceService; - } + detailMap.put("successEffectiveCount", successEffectiveCount); + detailMap.put("successInvalidCount", successInvalidCount); + detailMap.put("defeatCount", defeatCount); + } - public void setServerAreaService(ServerAreaService serverAreaService) { - this.serverAreaService = serverAreaService; - } + return resultMap; + } - public void setApiVisitCountService(ApiVisitCountService apiVisitCountService) { - this.apiVisitCountService = apiVisitCountService; - } + public void setApiUserService(ApiUserService apiUserService) { + this.apiUserService = apiUserService; + } - public void setOpenResourceCountService( - OpenResourceCountService openResourceCountService) { - this.openResourceCountService = openResourceCountService; - } - - - public void setOpenUriAnalyService(OpenUriAnalyService openUriAnalyService) { - this.openUriAnalyService = openUriAnalyService; - } + public UserService getUserService() { + return userService; + } - public void setApiUserCfgService(ApiUserCfgService apiUserCfgService) { - this.apiUserCfgService = apiUserCfgService; - } + public void setUserService(UserService userService) { + this.userService = userService; + } - public ApiInvokeStatisticalService getApiInvokeStatisticalService() { - return apiInvokeStatisticalService; - } + public void setApiUserAuthorityService(ApiUserAuthorityService apiUserAuthorityService) { + this.apiUserAuthorityService = apiUserAuthorityService; + } - public void setApiInvokeStatisticalService( - ApiInvokeStatisticalService apiInvokeStatisticalService) { - this.apiInvokeStatisticalService = apiInvokeStatisticalService; - } + public void setOpenResourceService(OpenResourceService openResourceService) { + this.openResourceService = openResourceService; + } - public void setApiCountCityService(ApiCountCityService apiCountCityService) { - this.apiCountCityService = apiCountCityService; - } + public void setServerAreaService(ServerAreaService serverAreaService) { + this.serverAreaService = serverAreaService; + } - public Map string2map(String str) - { - Map map = new HashMap(); - String [] a = str.split(","); + public void setApiVisitCountService(ApiVisitCountService apiVisitCountService) { + this.apiVisitCountService = apiVisitCountService; + } - for (String i : a) - { - String [] b = i.split(":"); - if (b.length > 1) - { - map.put(b[0],Integer.parseInt(b[1])); - } - } - return map; - } + public void setOpenResourceCountService( + OpenResourceCountService openResourceCountService) { + this.openResourceCountService = openResourceCountService; + } - public Object priceRatingAction(ApiUserModel model) throws IllegalAccessException { - ApiUserAuthority apiUserAuthority = apiUserAuthorityService.findByUserId(model.getUserId()); - if (apiUserAuthority != null && apiUserAuthority.getPriceRatingMap() != null){ - model.setPriceRatingMap(apiUserAuthority.getPriceRatingMap()); - }else{ - Map map = new HashMap(); - map.put("one",0.61); - map.put("newOne",0.61); - map.put("two",0.61); - map.put("three",0.61); - map.put("four",0.61); - map.put("five",0.61); - model.setPriceRatingMap(map); - } - if ( apiUserAuthority != null && apiUserAuthority.getCreditLevelStatus() != null) { - model.setCreditLevelStatus(apiUserAuthority.getCreditLevelStatus()); - } - ApiUser apiUser = apiUserService.findApiUserById(model.getUserId()); - if (apiUser != null) { - if (apiUser.getCompany() != null) { - model.setCompany(apiUser.getCompany()); - } - } - model.setUserId(model.getUserId()); - return model; - } + public void setOpenUriAnalyService(OpenUriAnalyService openUriAnalyService) { + this.openUriAnalyService = openUriAnalyService; + } - public Object savePriceRateingAction(ApiUserModel model) throws IllegalAccessException { - ApiUserAuthority apiUserAuthority = apiUserAuthorityService.findByUserId(model.getUserId()); - Map map = new HashMap(); - map.put("one",model.getOne()); - map.put("newOne",model.getNewOne()); - map.put("two",model.getTwo()); - map.put("three",model.getThree()); - map.put("four",model.getFour()); - map.put("five",model.getFive()); - apiUserAuthority.setPriceRatingMap(map); - apiUserAuthority.setCreditLevelStatus(model.getCreditLevelStatus()); - apiUserAuthorityService.update(apiUserAuthority); - model.setViewType("redirect"); - model.setViewParam("location", "/apiUser/list"); - return model; - } + public void setApiUserCfgService(ApiUserCfgService apiUserCfgService) { + this.apiUserCfgService = apiUserCfgService; + } + + public ApiInvokeStatisticalService getApiInvokeStatisticalService() { + return apiInvokeStatisticalService; + } + + public void setApiInvokeStatisticalService( + ApiInvokeStatisticalService apiInvokeStatisticalService) { + this.apiInvokeStatisticalService = apiInvokeStatisticalService; + } + + public void setApiCountCityService(ApiCountCityService apiCountCityService) { + this.apiCountCityService = apiCountCityService; + } + + public Map string2map(String str) { + Map map = new HashMap(); + String[] a = str.split(","); + + for (String i : a) { + String[] b = i.split(":"); + if (b.length > 1) { + map.put(b[0], Integer.parseInt(b[1])); + } + } + return map; + } + + public Object priceRatingAction(ApiUserModel model) throws IllegalAccessException { + ApiUserAuthority apiUserAuthority = apiUserAuthorityService.findByUserId(model.getUserId()); + if (apiUserAuthority != null && apiUserAuthority.getPriceRatingMap() != null) { + model.setPriceRatingMap(apiUserAuthority.getPriceRatingMap()); + } else { + Map map = new HashMap(); + map.put("one", 0.61); + map.put("newOne", 0.61); + map.put("two", 0.61); + map.put("three", 0.61); + map.put("four", 0.61); + map.put("five", 0.61); + model.setPriceRatingMap(map); + } + if (apiUserAuthority != null && apiUserAuthority.getCreditLevelStatus() != null) { + model.setCreditLevelStatus(apiUserAuthority.getCreditLevelStatus()); + } + ApiUser apiUser = apiUserService.findApiUserById(model.getUserId()); + if (apiUser != null) { + if (apiUser.getCompany() != null) { + model.setCompany(apiUser.getCompany()); + } + } + model.setUserId(model.getUserId()); + + return model; + } + + public Object savePriceRateingAction(ApiUserModel model) throws IllegalAccessException { + ApiUserAuthority apiUserAuthority = apiUserAuthorityService.findByUserId(model.getUserId()); + Map map = new HashMap(); + map.put("one", model.getOne()); + map.put("newOne", model.getNewOne()); + map.put("two", model.getTwo()); + map.put("three", model.getThree()); + map.put("four", model.getFour()); + map.put("five", model.getFive()); + apiUserAuthority.setPriceRatingMap(map); + apiUserAuthority.setCreditLevelStatus(model.getCreditLevelStatus()); + apiUserAuthorityService.update(apiUserAuthority); + model.setViewType("redirect"); + model.setViewParam("location", "/apiUser/list"); + return model; + } } diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/AvgPriceUpdateController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/AvgPriceUpdateController.java index 022176f79..9e99dd400 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/AvgPriceUpdateController.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/AvgPriceUpdateController.java @@ -602,6 +602,18 @@ public class AvgPriceUpdateController { calcCommandService.save(cmds); json.put("msg", "任务保存成功,共保存" + cmds.size() + "条任务"); + + //均价修改,让小区也修改,为了福州可以识别被修改小区 + if(commands.size()>0){ + for (int i = 0, len = commands.size(); i < len; i++) { + JSONObject command = (JSONObject) commands.get(i); + if(command.containsKey("id")){ + Map udata = new HashMap(); + udata.put("modificationDate", new Date()); + districtService.updateById(udata, command.getString("id")); + } + } + } return model; } diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/BuildingRatioController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/BuildingRatioController.java new file mode 100644 index 000000000..159155d1c --- /dev/null +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/BuildingRatioController.java @@ -0,0 +1,175 @@ +package com.fangjia.bkoff.controllers; + +import com.fangjia.bkoff.model.ApiUserModel; +import com.fangjia.bkoff.model.BuildingRatioModel; +import com.fangjia.dal.mongo.model.bkoff.BuildingRatio; +import com.fangjia.dal.sql.model.User; +import com.fangjia.service.bo.BuildingRatioBo; +import com.fangjia.service.mongo.bkoff.BuildingRatioService; +import org.apache.commons.lang.StringUtils; + +import java.net.URLEncoder; +import java.util.*; + +/** + * @author zhaojixiang + * @since 2023/7/5 + */ +public class BuildingRatioController { + + private BuildingRatioService buildingRatioService; + + /** + * 新建楼栋系数信息 + * + * @param model + * @return + */ + public Object doAddAction(BuildingRatioModel model) throws Exception { + try { + if(checkBuildingNameAction(model)){ + model.redirect("/buildingRatio/add?msg=" + URLEncoder.encode(model.getMsg(), "UTF-8")); + return model; + } + Date date = new Date(); + BuildingRatio buildingRatio = new BuildingRatio(); + buildingRatio.setCity(model.getCity_name()); + buildingRatio.setRegion(model.getRegion()); + buildingRatio.setDistrict(model.getDistrict()); + buildingRatio.setBuilding_name(model.getBuilding_name()); + buildingRatio.setRatio(model.getRatio()); + buildingRatio.setC_date(date); + buildingRatio.setM_date(date); + buildingRatio.setCreate_user(model.getCreate_user()); + buildingRatio.setNote(model.getNote()); + buildingRatio.setBuilding_avg_price(model.getBuilding_avg_price()); + buildingRatio.setAvg_price(model.getAvg_price()); + this.buildingRatioService.save(buildingRatio); + + model.setMsg("新建成功!"); + } catch (Exception e) { + e.printStackTrace(); + model.setMsg("新建失败!"); + } + model.redirect("/buildingRatio/add?msg=" + URLEncoder.encode(model.getMsg(), "UTF-8")); + return model; + } + + public Object doDeleteAction(BuildingRatioModel model){ + if(StringUtils.isNotBlank(model.getId())){ + this.buildingRatioService.deleteById(model.getId()); + } + model.setViewType("redirect"); + model.setViewParam("location","/buildingRatio/list"); + return model; + } + + /** + * 修改楼栋系数信息 + * + * @param model + * @return + */ + public Object updateAction(BuildingRatioModel model) throws Exception { + Map data_buildingRatio = new HashMap(); + + data_buildingRatio.put("id", model.getId()); + data_buildingRatio.put("city", model.getCity_name()); + data_buildingRatio.put("region", model.getRegion()); + data_buildingRatio.put("district", model.getDistrict()); + data_buildingRatio.put("building_name", model.getBuilding_name()); + data_buildingRatio.put("building_avg_price", model.getBuilding_avg_price()); + data_buildingRatio.put("avg_price", model.getAvg_price()); + data_buildingRatio.put("ratio", model.getRatio()); + data_buildingRatio.put("m_date", new Date()); + data_buildingRatio.put("create_user", model.getCreate_user()); + data_buildingRatio.put("note", model.getNote()); + + this.buildingRatioService.saveOrUpdateByBuildingName(model.getCity_name(),model.getRegion(),model.getDistrict(),model.getBuilding_name(), data_buildingRatio); + + model.setViewType("redirect"); + model.setViewParam("location", "/buildingRatio/list"); + + return model; + } + + public Object listAction(BuildingRatioModel model) { + + List buildingRatioList = this.buildingRatioService.findAllByBuildingName(model.getCity_name(),model.getRegion(),model.getDistrict(),model.getBuilding_name()); + + List buildingRatioBoList = new ArrayList(); + + for (BuildingRatio buildingRatio : buildingRatioList) { + BuildingRatioBo bo = new BuildingRatioBo(); + + bo.setId(buildingRatio.getId()); + bo.setCity_name(buildingRatio.getCity()); + bo.setRegion(buildingRatio.getRegion()); + bo.setDistrict(buildingRatio.getDistrict()); + bo.setBuilding_name(buildingRatio.getBuilding_name()); + bo.setBuilding_avg_price(buildingRatio.getBuilding_avg_price()); + bo.setAvg_price(buildingRatio.getAvg_price()); + bo.setRatio(buildingRatio.getRatio()); + bo.setC_date(buildingRatio.getC_date()); + bo.setM_date(buildingRatio.getM_date()); + bo.setCreate_user(buildingRatio.getCreate_user()); + bo.setNote(buildingRatio.getNote()); + + buildingRatioBoList.add(bo); + } + + model.setBuildingRatioBoList(buildingRatioBoList); + return model; + } + + public Object addAction(BuildingRatioModel model) { + return model; + } + + /** + * 编辑api用户信息 + * + * @param model + * @return + */ + public Object editAction(BuildingRatioModel model) { + BuildingRatio buildingRatio = this.buildingRatioService.findBuildingRatioById(model.getId()); + + BuildingRatioBo bo = new BuildingRatioBo(); + bo.setId(buildingRatio.getId()); + bo.setCity_name(buildingRatio.getCity()); + bo.setRegion(buildingRatio.getRegion()); + bo.setDistrict(buildingRatio.getDistrict()); + bo.setBuilding_name(buildingRatio.getBuilding_name()); + bo.setBuilding_avg_price(buildingRatio.getBuilding_avg_price()); + bo.setAvg_price(buildingRatio.getAvg_price()); + bo.setRatio(buildingRatio.getRatio()); + bo.setCreate_user(buildingRatio.getCreate_user()); + bo.setNote(buildingRatio.getNote()); + + model.setBuildingRatioBo(bo); + if (StringUtils.isNotBlank(model.getMsg()) && model.getMsg().equals("success")) { + model.setMsg("更新成功!"); + } + return model; + } + + public boolean checkBuildingNameAction(BuildingRatioModel model) { + model.setViewType("json"); + model.setViewParam("config", null); + List buildingRatioList = buildingRatioService.findAllByBuildingName(model.getCity_name(),model.getRegion(),model.getDistrict(),model.getBuilding_name()); + if (buildingRatioList.size()>0) { + model.setMsg("此楼栋名称已经存在!"); + return true; + } + return false; + } + + public BuildingRatioService getBuildingRatioService() { + return buildingRatioService; + } + + public void setBuildingRatioService(BuildingRatioService buildingRatioService) { + this.buildingRatioService = buildingRatioService; + } +} diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DataController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DataController.java index 3d55ac818..7628d085f 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DataController.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DataController.java @@ -618,8 +618,9 @@ public class DataController { System.out.println ( "IOException." + e ); } finally { try { - if (os != null) + if(os != null) { os.close(); + } if(fos != null){ fos.close(); } @@ -840,21 +841,40 @@ public class DataController { HSSFRow onerow = s.createRow(0); int oneRowIndex = 0; - Map displayMap = getFliedDisplay(); - for(String key : outfields){ - if(cat.equals("商铺")){ - if(key.equals("bedKind")){ - continue; - } - } - String display = (String) displayMap.get(key); - if(StringUtils.isNotBlank(display)){ - onerow.createCell((short)oneRowIndex).setCellValue(display); - }else{ - onerow.createCell((short)oneRowIndex).setCellValue(key); - } - oneRowIndex ++; - } + Map displayMap = getFliedDisplay(cat); + + /* + 以displayMap为准 移除outfields中多余字段 + */ + Iterator it = outfields.iterator(); + while(it.hasNext()) { + + String key = it.next(); + + String display = (String) displayMap.get(key); + + if (StringUtils.isNotBlank(display)) { + onerow.createCell((short)oneRowIndex).setCellValue(display); + oneRowIndex ++; + }else{ + it.remove(); + } + } +//因 写字楼导出仅展示写字楼后台的字段需求 改动 +// for(String key : outfields){ +// if(cat.equals("商铺")){ +// if(key.equals("bedKind")){ +// continue; +// } +// } +// String display = (String) displayMap.get(key); +// if(StringUtils.isNotBlank(display)){ +// onerow.createCell((short)oneRowIndex).setCellValue(display); +// }else{ +// onerow.createCell((short)oneRowIndex).setCellValue(key); +// } +// oneRowIndex ++; +// } for(Map map : list){ HSSFRow row = s.createRow(s.getPhysicalNumberOfRows()); @@ -891,151 +911,236 @@ public class DataController { return wb; } - public Map getFliedDisplay(){ + public Map getFliedDisplay(String cat){ Map map = new HashMap(){ { put( "province" , "省份" ); put( "city" , "城市" ); put( "cityLevel" , "城市等级" ); put( "rankingLevel" , "行政区划" ); - put( "existingDistrictCount" , "小区数量" ); - put( "districtsHasLoudong" , "有楼栋的小区数量" ); - put( "districtsHasFanghao" , "有房号的小区数量" ); - put( "existingOfficeCount" , "写字楼数量" ); - put( "existingShopCount" , "商铺数量" ); - put( "priceCoverage" , "价格覆盖率" ); - put( "priceCreditGte80Coverage", "0.8≤价格可信度"); - put( "priceCreditGte66Coverage", "0.66≤价格可信度<0.8"); - put( "priceCreditGte60Coverage", "0.6≤价格可信度<0.66"); - put( "priceCreditGte00Coverage", "价格可信度<0.6"); - put( "name" , "名称" ); - put( "region" , "区域" ); - put( "block" , "板块" ); - put( "address" , "地址" ); - put( "estateType" , "物业类型" ); - put( "householdCount" , "户数" ); - put( "openDate" , "开盘时间" ); - put( "latLng" , "mapabc经纬度" ); - put( "latLng2" , "百度经纬度" ); - put( "allArea" , "占地面积" ); - put( "buildArea" , "建筑面积" ); - put( "buildType" , "建筑类型" ); - put( "developer" , "开发商" ); - put( "estateCompany" , "物业公司" ); - put( "cubagePercent" , "容积率" ); - put( "virescencePercent" , "绿化率" ); - put( "carSite" , "停车位" ); - put( "carSiteCount" , "停车位描述" ); - put( "estateCharge" , "物业费" ); - put( "floorplanPics" , "楼层平面图" ); - put( "outPics" , "外景图" ); - put( "rentPrice" , "租金" ); - put( "bedKind" , "写字楼等级" ); - put( "houseFloor" , "楼层" ); - put( "houseHeight" , "楼高" ); - put( "houseArea" , "面积" ); - put( "room" , "室" ); - put( "hall" , "厅" ); - put( "direction" , "朝向" ); - put( "toilet" , "卫" ); - put( "noise" , "噪音" ); - put( "fitmentRank" , "装修" ); - put( "fitmentAge" , "装修年限" ); - put( "leaseTerm","租赁年限"); - put( "paymentPattern","付款方式"); - put( "rentPrice","出租价格"); - put( "sellPrice","出售价格"); - put( "mobile","电话"); - put( "floor","建筑楼层"); - put( "floorInfo","楼层状况"); - put( "bayArea","开间面积"); - put( "finishBuildingDate","竣工时间"); - put( "liveDate","开业时间"); - put( "divisible","是否可分割"); - put( "unifiedManage","是否统一管理"); - put( "metroInfo","地铁沿线"); - put( "metroNames","地铁站名"); - put( "facilities","配套设施"); - put( "propertyInfo","物业概况"); - put( "traffic","交通情况"); - put( "surrounding","周边情况"); - put( "businessStatus","经营业态"); - put( "rentType","租售类型"); - put( "price","价格"); - put( "businessQuarter","商圈"); - put( "startBuildingDate","开工时间"); - put( "liveDate","交房时间"); - put( "loopLineInfo","环线"); - put( "propertyLife","产权年限"); - put( "houseProperty","产权性质"); - put( "licence","预售许可证"); - put( "buildStructure","建筑结构"); - put( "house_count","房号总量"); - put( "exists_house_dis_count","有房号的小区数量"); - put( "house_num_rate","楼号覆盖率"); - put( "unit_num_rate","单元覆盖率"); - put( "room_num_rate","室号覆盖率"); - put( "area_rate","面积覆盖率"); - put( "room_info_rate","户型覆盖率"); - put( "hourse_structure_rate","户型结构覆盖率"); - put( "actualFloor","实际层覆盖率"); - put( "nominalFloor","名义层覆盖率"); - put( "build_type","建筑类型覆盖率"); - put( "loudong_count","楼栋总量"); - put( "exists_loudong_dis_count","有楼栋的小区数量"); - put( "loudong_num_rate","楼栋号覆盖率"); - put( "loudong_height_rate","总楼层覆盖率"); - put( "elevatornumber_rate","电梯数覆盖率"); - put( "households_rate","户数覆盖率"); - put( "address_rate","地址覆盖率"); - put( "structure_rate","建筑结构覆盖率"); - put( "build_year_rate","建筑年代覆盖率"); - put( "usage_rate","楼栋用途覆盖率"); - put( "loudong_type_rate","楼栋类型覆盖率"); - put( "floor_type_reate","建筑类型(按楼层)覆盖率"); - put( "archiNature_rate","建筑性质覆盖率"); - put( "totalAreas_rate","建筑总面积覆盖率"); - put("streetCommunity","街道社区"); - put("committee","居委会"); - put("schools","对口学校"); - put("houseStructure","房屋结构"); - put("estateType2","物业类型"); - put("buildDate","建筑年代"); - put("alias","别名"); - put("addrAlias","地址别名"); - put("mainTypeArea","主力面积"); - put("loudongCount","楼栋数"); - put("township","乡镇街道"); - put("schools","对口小学"); - put("kindergartens","对口幼儿园"); - put("elevator","电梯"); - put("landProperty","权属类别"); - put("usageCard","土地使用权证号"); - put("landUsageStart","土地使用年限"); - put("occupancyRate","入住率"); - put("mainType","主力户型"); - put("mappingAlias","映射别名"); - put("districtAliasTotalCount", "别名总量"); + put( "latLng" , "mapabc经纬度" ); + put( "latLng2" , "百度经纬度" ); - put("undergroundCarSite", "地下车位数"); - put("landCarSite", "地上车位数"); - put("parkingFee", "车位月租金"); - put("sight", "开间面积"); - put("lobbyHeight", "大堂层高"); - put("standardHeight", "标准层高"); - put("clearHeight", "净高"); - put("standardArea", "标准层面积"); - put("foreign", "是否涉外"); - put("register", "是否可注册"); - put("divisible", "是否可分割"); - put("elevatorsCount","电梯数量"); - put("personElevatorsCount","客梯数"); - put("goodsElevatorCount","货梯数"); - put("realUsePercent","得房率"); - put("landFloor","地上层数"); - put("undergroundFloor","地下层数"); +// put( "floorplanPics" , "楼层平面图" ); +// put( "outPics" , "外景图" ); +// put( "rentPrice" , "租金" ); +// put( "houseFloor" , "楼层" ); +// put( "houseHeight" , "楼高" ); +// put( "houseArea" , "面积" ); +// put( "room" , "室" ); +// put( "hall" , "厅" ); +// put( "direction" , "朝向" ); +// put( "toilet" , "卫" ); +// put( "noise" , "噪音" ); +// put( "fitmentRank" , "装修" ); +// put( "fitmentAge" , "装修年限" ); +// put( "leaseTerm","租赁年限"); +// put( "paymentPattern","付款方式"); +// put( "sellPrice","出售价格"); +// put( "mobile","电话"); +// put( "liveDate","开业时间"); +// put( "divisible","是否可分割"); +// put( "unifiedManage","是否统一管理"); +// put( "metroInfo","地铁沿线"); +// put( "metroNames","地铁站名"); +// put( "facilities","配套设施"); +// put( "propertyInfo","物业概况"); +// put( "traffic","交通情况"); +// put( "surrounding","周边情况"); +// put( "rentType","租售类型"); +// put( "price","价格"); +// put("schools","对口学校"); +// put("estateType" , "物业类型" ); +// put("estateType2","物业类型"); +// put("buildDate","建筑年代"); } };// + + if(cat.equals("小区")){ + map = setDistrictFields(map); + }else if(cat.equals("写字楼")){ + map = setOfficeFields(map); + }else if(cat.equals("房号")){ + map = setRoomNumberFields(map); + }else if(cat.equals("商铺")){ + map = setShopsFields(map); + }else if(cat.equals("楼栋")){ + map = setBuildingFields(map); + } + return map; } + private Map setDistrictFields (Map map){ + map.put( "existingDistrictCount" , "小区数量" ); + map.put( "districtsHasLoudong" , "有楼栋的小区数量" ); + map.put( "districtsHasFanghao" , "有房号的小区数量" ); + map.put( "priceCoverage" , "价格覆盖率" ); + map.put("districtAliasTotalCount", "别名总量"); + map.put( "priceCreditGte80Coverage", "0.8≤价格可信度"); + map.put( "priceCreditGte66Coverage", "0.66≤价格可信度<0.8"); + map.put( "priceCreditGte60Coverage", "0.6≤价格可信度<0.66"); + map.put( "priceCreditGte00Coverage", "价格可信度<0.6"); + map.put( "businessQuarter","商圈"); + map.put( "startBuildingDate","开工时间"); + map.put( "liveDate","交房时间"); + map.put( "loopLineInfo","环线"); + map.put( "propertyLife","产权年限"); + map.put( "houseProperty","产权性质"); + map.put( "licence","预售许可证"); + map.put( "buildStructure","建筑结构"); + map.put( "name" , "名称" ); + map.put( "region" , "区域" ); + map.put( "block" , "板块" ); + map.put( "address" , "地址" ); + map.put( "estateType2" , "物业类型" ); + map.put( "householdCount" , "户数" ); + map.put( "openDate" , "开盘时间" ); + map.put("buildDate","建筑年代"); + map.put( "allArea" , "占地面积" ); + map.put( "buildArea" , "建筑面积" ); + map.put( "buildType" , "建筑类型" ); + map.put( "developer" , "开发商" ); + map.put( "estateCompany" , "物业公司" ); + map.put( "cubagePercent" , "容积率" ); + map.put( "virescencePercent" , "绿化率" ); + map.put( "carSite" , "停车位" ); + map.put( "estateCharge" , "物业费" ); + map.put( "finishBuildingDate","竣工时间"); + map.put("streetCommunity","街道社区"); + map.put("committee","居委会"); + map.put("schools","对口小学"); + map.put("houseStructure","房屋结构"); + map.put("alias","别名"); + map.put("addrAlias","地址别名"); + map.put("mainTypeArea","主力面积"); + map.put("loudongCount","楼栋数"); + map.put( "carSiteCount" , "停车位描述" ); + map.put("mappingAlias","映射别名"); + map.put("elevator","电梯"); + map.put("township","乡镇街道"); + map.put("kindergartens","对口幼儿园"); + map.put("mainType","主力户型"); + map.put("landProperty","权属类别"); + map.put("usageCard","土地使用权证号"); + map.put("occupancyRate","入住率"); + map.put("landUsageStart","土地使用年限"); + map.put( "rentPrice","出租价格"); + map.put("realUsePercent","得房率"); + return map; + } + private Map setOfficeFields (Map map){ + map.put( "existingOfficeCount" , "写字楼数量" ); + map.put( "name" , "名称" ); + map.put( "region" , "区域" ); + map.put( "block" , "板块" ); + map.put( "address" , "地址" ); +// map.put( "estateType2" , "物业类型" ); +// map.put( "openDate" , "开盘时间" ); +// map.put( "liveDate","交房时间"); + map.put( "allArea" , "占地面积" ); + map.put( "buildArea" , "建筑面积" ); +// map.put( "buildType" , "建筑类型" ); + map.put( "developer" , "开发商" ); + map.put( "estateCompany" , "物业公司" ); + map.put( "cubagePercent" , "容积率" ); + map.put( "virescencePercent" , "绿化率" ); + map.put( "carSite" , "停车位" ); + map.put( "estateCharge" , "物业费" ); + map.put( "finishBuildingDate","竣工时间"); +// map.put( "startBuildingDate","开工时间"); +// map.put( "carSiteCount" , "停车位描述" ); + map.put( "bedKind" , "写字楼等级" ); + map.put("alias","别名"); + map.put("addrAlias","地址别名"); +// map.put( "businessQuarter","商圈"); + map.put( "loopLineInfo","环线"); +// map.put( "floorInfo","楼层状况"); + map.put("undergroundCarSite", "地下车位数"); + map.put("landCarSite", "地上车位数"); + map.put("parkingFee", "车位月租金"); + map.put( "bayArea","开间面积"); + map.put( "propertyLife","产权年限"); + map.put("elevatorsCount","电梯数量"); + map.put("personElevatorsCount","客梯数"); + map.put("goodsElevatorCount","货梯数"); + map.put("standardHeight", "标准层高"); + map.put("clearHeight", "净高"); + map.put("standardArea", "标准层面积"); + map.put("foreign", "是否涉外"); + map.put("register", "是否可注册"); + map.put("lobbyHeight", "大堂层高"); +// map.put("township","乡镇街道"); + map.put("divisible", "是否可分割"); + map.put("landFloor","地上层数"); + map.put("undergroundFloor","地下层数"); + + return map; + } + + private Map setRoomNumberFields (Map map){ + map.put( "house_count","房号总量"); + map.put( "exists_house_dis_count","有房号的小区数量"); + map.put( "house_num_rate","楼号覆盖率"); + map.put( "unit_num_rate","单元覆盖率"); + map.put( "room_num_rate","室号覆盖率"); + map.put( "area_rate","面积覆盖率"); + map.put( "room_info_rate","户型覆盖率"); + map.put( "hourse_structure_rate","户型结构覆盖率"); + map.put( "actualFloor","实际层覆盖率"); + map.put( "nominalFloor","名义层覆盖率"); + map.put( "build_type","建筑类型覆盖率"); + return map; + } + + private Map setShopsFields (Map map){ + map.put( "existingShopCount" , "商铺数量" ); + map.put( "name" , "名称" ); + map.put( "region" , "区域" ); + map.put( "block" , "板块" ); + map.put( "address" , "地址" ); + map.put("alias","别名"); + map.put("addrAlias","地址别名"); + map.put( "estateType2" , "物业类型" ); + map.put( "openDate" , "开盘时间" ); + map.put( "liveDate","交房时间"); + map.put( "allArea" , "占地面积" ); + map.put( "buildArea" , "建筑面积" ); + map.put( "buildType" , "建筑类型" ); + map.put( "developer" , "开发商" ); + map.put( "estateCompany" , "物业公司" ); + map.put( "carSite" , "停车位" ); + map.put( "estateCharge" , "物业费" ); + map.put( "floor","建筑楼层"); + map.put( "finishBuildingDate","竣工时间"); + map.put( "businessQuarter","商圈"); + map.put( "startBuildingDate","开工时间"); + map.put("sight", "开间面积"); + map.put( "propertyLife","产权年限"); + map.put( "businessStatus","经营业态"); + map.put("parkingFee", "车位月租金"); + map.put("township","乡镇街道"); + map.put( "loopLineInfo","环线"); + map.put("landFloor","地上层数"); + map.put("undergroundFloor","地下层数"); + return map; + } + private Map setBuildingFields (Map map){ + map.put( "loudong_count","楼栋总量"); + map.put( "exists_loudong_dis_count","有楼栋的小区数量"); + map.put( "unit_num_rate","单元覆盖率"); + map.put( "loudong_num_rate","楼栋号覆盖率"); + map.put( "loudong_height_rate","总楼层覆盖率"); + map.put( "elevatornumber_rate","电梯数覆盖率"); + map.put( "households_rate","户数覆盖率"); + map.put( "address_rate","地址覆盖率"); + map.put( "structure_rate","建筑结构覆盖率"); + map.put( "build_year_rate","建筑年代覆盖率"); + map.put( "usage_rate","楼栋用途覆盖率"); + map.put( "loudong_type_rate","楼栋类型覆盖率"); + map.put( "floor_type_reate","建筑类型(按楼层)覆盖率"); + map.put( "archiNature_rate","建筑性质覆盖率"); + map.put( "totalAreas_rate","建筑总面积覆盖率"); + return map; + } + public Object houseAction(DataModel model) { if (StringUtils.isBlank(model.getCityDisplay())) { diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DevelopmentZoneController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DevelopmentZoneController.java new file mode 100644 index 000000000..8306117fe --- /dev/null +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DevelopmentZoneController.java @@ -0,0 +1,263 @@ +package com.fangjia.bkoff.controllers; + +import com.fangjia.bkoff.model.DevelopmentZoneModel; +import com.fangjia.bkoff.model.JsonModel; +import com.fangjia.bkoff.model.LatlngPolygonModel; +import com.fangjia.core.util.GeoUtils; +import com.fangjia.core.util.ThreadLocalData; +import com.fangjia.core.util.ThreadLocalKey; +import com.fangjia.dal.mongo.model.DevelopmentZone; +import com.fangjia.dal.mongo.model.LatlngPolygon; +import com.fangjia.dal.mongo.model.StatsIndex; +import com.fangjia.dal.mongo.model.bkoff.BkoffUsers; +import com.fangjia.service.mongo.bkoff.BkoffUsersService; +import com.fangjia.service.mongo.fangjia.DevelopmentZoneService; +import com.fangjia.service.mongo.fangjia.LatlngPolygonService; +import org.apache.commons.lang.StringUtils; +import org.sothis.core.util.Pager; + +import java.util.*; + +import static com.fangjia.core.util.GeoUtils.LAT; +import static com.fangjia.core.util.GeoUtils.LNG; + +/** + * Created by dxy on 2015/6/8. + */ +public class DevelopmentZoneController { + private DevelopmentZoneService developmentZoneService; + private BkoffUsersService bkoffUsersService; + + public Object listAction(DevelopmentZoneModel model) { + Pager pager = model.getPager(30); + if (pager.getCurrentPage() > 100) { + pager.setCurrentPage(1); + } + long countDev = developmentZoneService.countDev(model.getProvince(), model.getName(), model.getLevel()); + pager.setTotalRows((int) countDev); + List developmentZones = developmentZoneService.findDevelopmentZone(model.getProvince(), model.getName(), model.getLevel(), pager); + model.setDevelopmentZoneList(developmentZones); + model.setPager(pager); + return model; + } + + public Object showAction(DevelopmentZoneModel model) { + if (model.getId() == null) { + return model; + } + + model.setDevelopmentZone(developmentZoneService.findDevelopmentZone(model.getId())); + return model; + } + + public Object editAction(DevelopmentZoneModel model) { + if (model.getId() == null) { + return model; + } + + model.setDevelopmentZone(developmentZoneService.findDevelopmentZone(model.getId())); + return model; + } + + public Object deleteAction(LatlngPolygonModel model) { + JsonModel ret = new JsonModel(); + if (model.getId() == null) { + return ret; + } + developmentZoneService.deleteDevelopmentZone(model.getId()); + return ret; + } + + public Object saveOrUpdateAction(DevelopmentZoneModel model) { + String userId = (String) ThreadLocalData.getInstance().get(ThreadLocalKey.UserId); + BkoffUsers user = bkoffUsersService.findBkoffUsersById(userId); + JsonModel ret = new JsonModel(); + Map data = new HashMap(); + ret.setJsonModel(data); + if (model.getId() == null) { + // name province bdLocation level 不能为空 + if (StringUtils.isBlank(model.getProvince()) || StringUtils.isBlank(model.getName()) || StringUtils.isBlank(model.getLevel())) { + data.put("msg", "保存失败(开发区名称,所在省份,级别不能为空)"); + return ret; + } + DevelopmentZone entity = new DevelopmentZone(); + // name province bdLocation level 不能为空/ + entity.setName(model.getName()); + entity.setProvince(model.getProvince()); + // 新加开发区,围栏不是必须有的 + if (model.getBdShape() != null && !model.getBdShape().toString().equals("[]")) { + String locationStr = model.getBdShape().toString().replaceAll("\\[", "").replaceAll("\\]", "").replaceAll(" ", ""); + List> bdLocationList = new ArrayList>(); + String[] splitStr = locationStr.split(";"); + for (int i = 0; i < splitStr.length; i++) { + String[] splitStr2 = splitStr[i].split(","); + List location = new ArrayList(); + location.add(Double.parseDouble(splitStr2[0])); + location.add(Double.parseDouble(splitStr2[1])); + bdLocationList.add(location); + } + //加上第一个,形成首尾闭合 + bdLocationList.add(bdLocationList.get(0)); + model.setBdShape(bdLocationList); + // 百度经纬度 + Map bdShape = new HashMap(); + bdShape.put("type", "polygon"); + bdShape.put("coordinates", model.getBdShape()); + entity.setBdShape(bdShape); + // 高德经纬度 + Map shape = new HashMap(); + shape.put("type", "polygon"); + Object coordinates = convertGeoList(model.getBdShape()); + shape.put("coordinates", coordinates); + entity.setShape(shape); + } + + entity.setLevel(model.getLevel()); + String aliasString = model.getAlias().replaceAll(",", ","); + List alias = Arrays.asList(aliasString.split("\\s*,\\s*")); + entity.setAlias(alias); + entity.setAddress(StringUtils.isBlank(model.getAddress()) ? "" : model.getAddress()); + entity.setArea(StringUtils.isBlank(model.getArea()) ? "" : model.getArea()); + entity.setBlock(StringUtils.isBlank(model.getBlock()) ? "" : model.getBlock()); + entity.setBuildDate(StringUtils.isBlank(model.getBuildDate()) ? "" : model.getBuildDate()); + entity.setCreateTime(new Date()); + entity.setIndustry(StringUtils.isBlank(model.getIndustry()) ? "" : model.getIndustry()); + entity.setNameEn(StringUtils.isBlank(model.getNameEn()) ? "" : model.getNameEn()); + entity.setType(StringUtils.isBlank(model.getType()) ? "" : model.getType()); + entity.setUrl(StringUtils.isBlank(model.getUrl()) ? "" : model.getUrl()); + entity.setCityName1(StringUtils.isBlank(model.getCityName1()) ? "" : model.getCityName1()); + entity.setDistrict(StringUtils.isBlank(model.getDistrict()) ? "" : model.getDistrict()); + //记录操作人员 + entity.setOperator(user.getRealName()); + developmentZoneService.saveDevelopmentZone(entity); + data.put("msg", "保存成功"); + } else { +// DevelopmentZone entity = developmentZoneService.findDevelopmentZone(model.getId()); + Map udata = new HashMap(); + if (StringUtils.isNotBlank(model.getProvince())) { + udata.put("province", model.getProvince()); + } + if (StringUtils.isNotBlank(model.getName())) { + udata.put("name", model.getName()); + } + if (StringUtils.isNotBlank(model.getLevel())) { + udata.put("level", model.getLevel()); + } + if (model.getBdShape() != null && !model.getBdShape().toString().equals("[]")) { + String locationStr = model.getBdShape().toString().replaceAll("\\[", "").replaceAll("\\]", "").replaceAll(" ", ""); + List> bdLocationList = new ArrayList>(); + String[] splitStr = locationStr.split(";"); + for (int i = 0; i < splitStr.length; i++) { + String[] splitStr2 = splitStr[i].split(","); + List location = new ArrayList(); + location.add(Double.parseDouble(splitStr2[0])); + location.add(Double.parseDouble(splitStr2[1])); + bdLocationList.add(location); + } + //加上第一个,形成首尾闭合 + bdLocationList.add(bdLocationList.get(0)); + model.setBdShape(bdLocationList); + // 百度经纬度 + Map bdShape = new HashMap(); + bdShape.put("type", "polygon"); + bdShape.put("coordinates", model.getBdShape()); + udata.put("bdShape", bdShape); + // 高德经纬度 + Map shape = new HashMap(); + shape.put("type", "polygon"); + Object coordinates = convertGeoList(model.getBdShape()); + shape.put("coordinates", coordinates); + udata.put("shape", shape); + } + if (StringUtils.isNotBlank(model.getAlias())) { + String aliasString = model.getAlias().replaceAll(",", ","); + List alias = Arrays.asList(aliasString.split("\\s*,\\s*")); + udata.put("alias", alias); + } + if (StringUtils.isNotBlank(model.getAddress())) { + udata.put("address", model.getAddress()); + } + if (StringUtils.isNotBlank(model.getArea())) { + udata.put("area", model.getArea()); + } + if (StringUtils.isNotBlank(model.getBlock())) { + udata.put("block", model.getBlock()); + } + if (StringUtils.isNotBlank(model.getBuildDate())) { + udata.put("buildDate", model.getBuildDate()); + } + if (StringUtils.isNotBlank(model.getIndustry())) { + udata.put("industry", model.getIndustry()); + } + if (StringUtils.isNotBlank(model.getNameEn())) { + udata.put("nameEn", model.getNameEn()); + } + if (StringUtils.isNotBlank(model.getType())) { + udata.put("type", model.getType()); + } + if (StringUtils.isNotBlank(model.getUrl())) { + udata.put("url", model.getUrl()); + } + if (StringUtils.isNotBlank(model.getCityName1())) { + udata.put("cityName1", model.getCityName1()); + } + if (StringUtils.isNotBlank(model.getDistrict())){ + udata.put("district", model.getDistrict()); + } + udata.put("createTime", new Date()); + //记录操作人员 + udata.put("operator", user.getRealName()); + developmentZoneService.updateDevelopmentZone(udata, model.getId()); + data.put("msg", "修改成功"); + } + + return ret; + } + + public JsonModel provincesAction() { + JsonModel model = new JsonModel(); + List provinces = developmentZoneService.findProvinces(); + model.setJsonModel(provinces); + return model; + } + + public JsonModel citiesAction(DevelopmentZoneModel model) { + JsonModel jsonModel = new JsonModel(); + List cities = developmentZoneService.findCities(model.getProvince()); + jsonModel.setJsonModel(cities); + return jsonModel; + } + + public JsonModel districtsAction(DevelopmentZoneModel model) { + JsonModel jsonModel = new JsonModel(); + List districts = developmentZoneService.findDistricts(model.getCityName1()); + jsonModel.setJsonModel(districts); + return jsonModel; + } + + public void setDevelopmentZoneService(DevelopmentZoneService developmentZoneService) { + this.developmentZoneService = developmentZoneService; + } + + public void setBkoffUsersService(BkoffUsersService bkoffUsersService) { + this.bkoffUsersService = bkoffUsersService; + } + //将百度坐标转为高德坐标 + + public List> convertGeoList(List> bdLocationList) { + List> gdLocationList = new ArrayList>(); + + // 使用增强的 for 循环遍历列表 + for (List bdLocation : bdLocationList) { + List gdLocation = new ArrayList(); + // 将百度坐标转为高德坐标 + Map map = GeoUtils.bd09ToGcj02(bdLocation.get(0), bdLocation.get(1)); + gdLocation.add(map.get(LAT)); + gdLocation.add(map.get(LNG)); + gdLocationList.add(gdLocation); + } + return gdLocationList; + } + + +} diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DistrictController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DistrictController.java index 657388333..080f08f51 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DistrictController.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/DistrictController.java @@ -243,12 +243,12 @@ public class DistrictController { } } else { BooleanQuery query = new BooleanQuery(); - Query q1 = new TermQuery(new Term("keyword", model.getKeyword())); - q1.setBoost(0.99f); - query.add(q1, Occur.SHOULD); - // Query q2 = new TermQuery(new Term("keyword_cjk", model.getKeyword())); - // q2.setBoost(0.01f); - // query.add(q2, Occur.SHOULD); +// Query q1 = new TermQuery(new Term("keyword", model.getKeyword())); +// q1.setBoost(0.99f); +// query.add(q1, Occur.SHOULD); + Query q2 = new TermQuery(new Term("keyword_cjk", model.getKeyword())); + q2.setBoost(0.1f); + query.add(q2, Occur.SHOULD); params.add(new QueryParam("$sr", new SrQuery(query))); } } @@ -331,7 +331,7 @@ public class DistrictController { for (QueryParam pa : params) { fenQiParams.add(pa); } - fenQiParams.add(new QueryParam("masterDistrictNname", "master")); + fenQiParams.add(new QueryParam("masterDistrictName", "master")); fenQiParams.add(new QueryParam("visible", 0)); int fenQiCount = (int) districtService.findDistrictCount(0, fenQiParams); // int surplusDistrictCount = @@ -373,7 +373,7 @@ public class DistrictController { } else if (model.getValid() != null && model.getValid() == 3) { // 分期数据处理 params.add(new QueryParam("visible", 0)); - params.add(new QueryParam("masterDistrictNname", "master")); + params.add(new QueryParam("masterDistrictName", "master")); districts = districtService.findDistrictList(pager, params, sortParams); List vos = new ArrayList(); for (District district : districts) { @@ -482,19 +482,34 @@ public class DistrictController { || StringUtils.isBlank(model.getName())) { return ret; } - HttpRequest request = new HttpRequest(); - HashMap params = new HashMap(); - params.put("category", "sell"); - params.put("city", model.getCityDisplay()); - params.put("region", model.getRegion()); - params.put("name", model.getName()); - params.put("count", "4"); - params.put("retainHistory", "true"); - try { - request.getJsonContent(Constants.MSVC_FANG_JIA_DATA_SERVICE_BASE_PATH + "/districtPriceCalculate", params, "UTF-8"); - } catch (HttpRequestException e) { - e.printStackTrace(); - } + + Runnable myRunnable = new Runnable(){ + public void run(){ + try { + District district = districtService.findDistrict(new DistrictKey(model.getCityDisplay(), model.getRegion(), model.getName()),"district"); + if(null != district){ + HttpRequest request = new HttpRequest(); + HashMap params = new HashMap(); + params.put("category", "sell"); + params.put("city", model.getCityDisplay()); + params.put("region", model.getRegion()); + params.put("name", model.getName()); + params.put("count", "4"); + params.put("retainHistory", "true"); + try { + request.getJsonContent(Constants.MSVC_FANG_JIA_DATA_SERVICE_BASE_PATH + "/districtPriceCalculate", params, "UTF-8"); + } catch (HttpRequestException e) { + e.printStackTrace(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }; + Thread thread = new Thread(myRunnable); + thread.start(); + return ret; } @@ -1185,6 +1200,37 @@ public class DistrictController { model.setJsonModel(data); return model; } + /** + * 校验小区名是否为其他小区的别名 + */ + public Object checkDistrictNameAction(@Param(name = "city") String city, @Param(name = "region") String region, + @Param(name = "name") String name, @Param(name = "cat") String cat, @Param(name = "id") String id) { + JsonModel model = new JsonModel(); + boolean exist = false; + + List list = new ArrayList(); + list.add(name); + List params = new ArrayList(); + params.add(new QueryParam("category", cat)); + params.add(new QueryParam("city", city)); + params.add(new QueryParam("region", region)); + params.add(new QueryParam("alias", name)); + params.add(new QueryParam("visible", 0)); + + List ds = districtService.findAllByParams(params); + if (CollectionUtils.isNotEmpty(ds)) { + for (District d : ds) { + if (!d.getId().equals(id)) { + exist = true; + break; + } + } + } + Map data = new HashMap(); + data.put("exist", exist); + model.setJsonModel(data); + return model; + } /** * 保存新增小区 @@ -1306,7 +1352,7 @@ public class DistrictController { && StringUtils.isNotBlank(district.getRegion())) { // signFiledEditFlag(district, null); districtService.save(district); - districtUpdateTaskService.createTask(district, 5); + districtUpdateTaskService.createTask(district, 5, null); } if (model.isGoPic()) { @@ -1874,6 +1920,7 @@ public class DistrictController { district.setMappingAlias(null); } } + district.setModificationDate(new Date()); districtService.save(district); } @@ -1935,6 +1982,7 @@ public class DistrictController { district.setLandProperty(model.getLandProperty()); } + district.setModificationDate(new Date()); districtService.save(district); } return model; @@ -2014,28 +2062,28 @@ public class DistrictController { districtUpdateTaskService.createTask(orgDis, 2, newName, newRegion); districtUpdateTaskService.createTask(orgDis, 6, newName, newRegion); - District distTask = new District(); - distTask.setCity(orgDis.getCity()); - if(StringUtils.isNotBlank(newName)){ - distTask.setRegion(newRegion); - }else{ - distTask.setRegion(orgDis.getRegion()); - } - - distTask.setEstateType2(orgDis.getEstateType2()); - if(StringUtils.isNotBlank(newName)){ - distTask.setName(newName); - }else{ - distTask.setName(orgDis.getName()); - } - - districtUpdateTaskService.createTask(distTask, 5); +// District distTask = new District(); +// distTask.setCity(orgDis.getCity()); +// if(StringUtils.isNotBlank(newName)){ +// distTask.setRegion(newRegion); +// }else{ +// distTask.setRegion(orgDis.getRegion()); +// } +// +// distTask.setEstateType2(orgDis.getEstateType2()); +// if(StringUtils.isNotBlank(newName)){ +// distTask.setName(newName); +// }else{ +// distTask.setName(orgDis.getName()); +// } +// +// districtUpdateTaskService.createTask(distTask, 5); } - if (StringUtils.isNotBlank(district.getEstateType2()) - && district.getEstateType2().equals(orgDis.getEstateType2())) { - districtUpdateTaskService.createTask(district); - } +// if (StringUtils.isNotBlank(district.getEstateType2()) +// && district.getEstateType2().equals(orgDis.getEstateType2())) { +// districtUpdateTaskService.createTask(district); +// } Map data = new HashMap(); data.put("category", district.getCategory()); @@ -2236,6 +2284,9 @@ public class DistrictController { data.put("markMap", markMap); data.put("modificationDate", new Date()); districtService.updateById(data, district.getId()); + + //创建更新任务,用为更新常州农商行数据 + createJnTask(district.getId(), null); msg = "保存成功了!!!"; } @@ -2245,6 +2296,17 @@ public class DistrictController { return model; } + private void createJnTask(String id, Integer type){ + District newDist = districtService.findDistrictById(id); + District distTask = new District(); + distTask.setCity(newDist.getCity()); + distTask.setRegion(newDist.getRegion()); + distTask.setName(newDist.getName()); + distTask.setEstateType2(newDist.getEstateType2()); + distTask.setId(id); + districtUpdateTaskService.createTask(distTask, 5, type); + } + public Object checkNamesAction(DistrictModel model) { List params = new ArrayList(); @@ -2291,6 +2353,7 @@ public class DistrictController { params = new ArrayList(2); params.add(new QueryParam("category", "district,new_district")); params.add(new QueryParam("name", a)); + params.add(new QueryParam("visible", 0)); ds = districtService.findAllByParams(params); @@ -2406,10 +2469,12 @@ public class DistrictController { JsonModel ret = new JsonModel(); if (StringUtils.isNotBlank(model.getId()) && ObjectId.isValid(model.getId())) { districtService.logicDeleteById(model.getId()); + createJnTask(model.getId(), 1); } else if (model.getIds() != null) { String[] ids = model.getIds().toString().split(","); for (String id : ids) { districtService.logicDeleteById(id); + createJnTask(id, 1); } } return ret; @@ -2421,10 +2486,12 @@ public class DistrictController { public Object restoreAction(DistrictModel model) throws UnsupportedEncodingException { if (ObjectId.isValid(model.getId())) { districtService.restoreById(model.getId()); + createJnTask(model.getId(), null); } else if (model.getIds() != null) { String[] ids = model.getIds().split("_"); for (String id : ids) { districtService.restoreById(id); + createJnTask(id, null); } } model.setViewType("redirect"); @@ -3446,8 +3513,8 @@ public class DistrictController { if (type.equals("master")) { masterDistrict = districtService.findById(id); } - if (dis != null && dis.getMasterDistrictNname() != null - && dis.getMasterDistrictNname().equals("master")) { + if (dis != null && dis.getMasterDistrictName() != null + && dis.getMasterDistrictName().equals("master")) { json.setSuccess(false); json.setMsg(dis.getName() + "已经是主小区了"); return json; @@ -3465,13 +3532,13 @@ public class DistrictController { String type = stas[1]; if (type.equals("master")) { Map data = new HashMap(); - data.put("masterDistrictNname", "master"); + data.put("masterDistrictName", "master"); districtService.updateById(data, id); // 设置为人工操作分期标识 districtService.setPersonOperate(id); } else { Map data = new HashMap(); - data.put("masterDistrictNname", masterDistrict.getName()); + data.put("masterDistrictName", masterDistrict.getName()); districtService.updateById(data, id); } } @@ -3499,8 +3566,8 @@ public class DistrictController { json.setMsg("小区不存在,请检查是否输入正确"); return json; } - if (slaveDistrict.getMasterDistrictNname() != null - && slaveDistrict.getMasterDistrictNname().equals("master")) { + if (slaveDistrict.getMasterDistrictName() != null + && slaveDistrict.getMasterDistrictName().equals("master")) { json.setSuccess(false); json.setMsg(slaveDistrict.getName() + "已经是主小区了"); return json; @@ -3509,7 +3576,7 @@ public class DistrictController { if (slaveDistrict.getCity().equals(masterDistrict.getCity()) && slaveDistrict.getRegion().equals(masterDistrict.getRegion())) { Map data = new HashMap(); - data.put("masterDistrictNname", masterDistrict.getName()); + data.put("masterDistrictName", masterDistrict.getName()); districtService.updateById(data, slaveId); // 设置为人工操作分期标识 districtService.setPersonOperate(masterDistrict.getId()); @@ -3534,9 +3601,9 @@ public class DistrictController { if (model.getId() != null && !model.getId().equals("")) { District slaveDistrict = districtService.findById(model.getId()); District masterDistrict = districtService.findDistrict(new DistrictKey(slaveDistrict.getCity(), - slaveDistrict.getRegion(), slaveDistrict.getMasterDistrictNname()), "district"); + slaveDistrict.getRegion(), slaveDistrict.getMasterDistrictName()), "district"); Map data = new HashMap(); - data.put("masterDistrictNname", null); + data.put("masterDistrictName", null); districtService.updateById(data, model.getId()); // 设置为人工操作分期标识 if (masterDistrict != null) { @@ -3560,7 +3627,7 @@ public class DistrictController { List slaves = districtService.findSlaves(masterDistrict.getCity(), masterDistrict.getRegion(), masterDistrict.getName()); Map data = new HashMap(); - data.put("masterDistrictNname", null); + data.put("masterDistrictName", null); for (District district : slaves) { districtService.updateById(data, district.getId()); } @@ -3587,7 +3654,7 @@ public class DistrictController { params.add(new QueryParam("visible", 0)); params.add(new QueryParam("city", slaveDistrict.getCity())); params.add(new QueryParam("region", slaveDistrict.getRegion())); - params.add(new QueryParam("name", slaveDistrict.getMasterDistrictNname())); + params.add(new QueryParam("name", slaveDistrict.getMasterDistrictName())); List list = districtService.findAllByParams(params); if (list == null || list.size() == 0) { json.setSuccess(false); @@ -3602,18 +3669,18 @@ public class DistrictController { for (District district : slaves) { if (district.getId().equals(slaveId)) { Map data = new HashMap(); - data.put("masterDistrictNname", "master"); + data.put("masterDistrictName", "master"); districtService.updateById(data, district.getId()); // 设置为人工操作分期标识 districtService.setPersonOperate(district.getId()); } else { Map data = new HashMap(); - data.put("masterDistrictNname", slaveDistrict.getName()); + data.put("masterDistrictName", slaveDistrict.getName()); districtService.updateById(data, district.getId()); } } Map data = new HashMap(); - data.put("masterDistrictNname", slaveDistrict.getName()); + data.put("masterDistrictName", slaveDistrict.getName()); districtService.updateById(data, masterDistrict.getId()); } return json; diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/LoginController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/LoginController.java index 39d884683..a51c6999c 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/LoginController.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/LoginController.java @@ -84,7 +84,7 @@ public class LoginController { return model.redirect("/users/selfEdit"); } else { String forward = StringUtils.defaultIfEmpty(model.getForward(), "/"); - if(forward.endsWith("/login/login")){ + if(forward.contains("/login/login") || forward.contains("/login/index")){ return model.redirect("/"); }else{ return model.redirect(forward); diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/TownshipController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/TownshipController.java new file mode 100644 index 000000000..af225d92a --- /dev/null +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/TownshipController.java @@ -0,0 +1,84 @@ +package com.fangjia.bkoff.controllers; + +import com.fangjia.bkoff.model.DevelopmentZoneModel; +import com.fangjia.bkoff.model.JsonModel; +import com.fangjia.bkoff.model.TownshipModel; +import com.fangjia.core.util.ThreadLocalData; +import com.fangjia.core.util.ThreadLocalKey; +import com.fangjia.dal.mongo.model.Township; +import com.fangjia.dal.mongo.model.bkoff.BkoffUsers; +import com.fangjia.service.mongo.bkoff.BkoffUsersService; +import com.fangjia.service.mongo.fangjia.TownshipService; +import org.apache.commons.lang.StringUtils; +import org.sothis.core.util.Pager; + +import java.util.*; + +/** + * Created by dxy on 2015/6/8. + */ +public class TownshipController { + private TownshipService townshipService; + private BkoffUsersService bkoffUsersService; + + public Object listAction(TownshipModel model) { + Pager pager = model.getPager(30); + if (pager.getCurrentPage() > 100) { + pager.setCurrentPage(1); + } + long countDev = townshipService.countTownship(model.getProvince(), model.getCity1(), model.getDistrict(),model.getStreet()); + pager.setTotalRows((int) countDev); + List townships = townshipService.findTownship(model.getProvince(), model.getCity1(), model.getDistrict(),model.getStreet(), pager); + model.setTownshipList(townships); + model.setPager(pager); + return model; + } + + public Object editAction(TownshipModel model) { + if (model.getId() == null) { + return model; + } + + model.setTownship(townshipService.findTownship(model.getId())); + return model; + } + + public Object updateAction(TownshipModel model) { + String userId = (String) ThreadLocalData.getInstance().get(ThreadLocalKey.UserId); + BkoffUsers user = bkoffUsersService.findBkoffUsersById(userId); + JsonModel ret = new JsonModel(); + Map data = new HashMap(); + if (model.getId() != null) { + Map udata = new HashMap(); + if (StringUtils.isNotBlank(model.getAlias())) { + String aliasString = model.getAlias().replaceAll(",", ","); + List alias = Arrays.asList(aliasString.split("\\s*,\\s*")); + udata.put("alias", alias); + } + udata.put("updateTime", new Date()); + //记录操作人员 + udata.put("operator", user.getRealName()); + townshipService.updateTownship(udata, model.getId()); + data.put("msg", "修改成功"); + } + ret.setJsonModel(data); + return ret; + } + + + public void setBkoffUsersService(BkoffUsersService bkoffUsersService) { + this.bkoffUsersService = bkoffUsersService; + } + + public TownshipService getTownshipService() { + return townshipService; + } + + public void setTownshipService(TownshipService townshipService) { + this.townshipService = townshipService; + } + + public BkoffUsersService getBkoffUsersService() { + return bkoffUsersService; + } +} diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/VillageIdentifyController.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/VillageIdentifyController.java new file mode 100644 index 000000000..771eaa2e4 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/controllers/VillageIdentifyController.java @@ -0,0 +1,139 @@ +package com.fangjia.bkoff.controllers; + +import com.fangjia.bkoff.model.AverageStatisticsModel; +import com.fangjia.bkoff.model.JsonModel; +import com.fangjia.bkoff.model.VillageIdentifyModel; +import com.fangjia.bkoff.util.ExcelUtils; +import com.fangjia.dal.QueryParam; +import com.fangjia.dal.mongo.model.VillageIdentify; +import com.fangjia.service.mongo.fangjia.VillageIdentifyService; +import org.apache.commons.lang.StringUtils; +import org.sothis.core.util.Pager; +import org.sothis.web.mvc.ActionContext; +import org.sothis.web.mvc.interceptors.MultipartHttpServletRequest; +import org.springframework.core.io.ClassPathResource; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.net.URLEncoder; + +public class VillageIdentifyController { + private VillageIdentifyService villageIdentifyService; + + public Object importResultAction(VillageIdentifyModel model) { + Pager pager = model.getPager(25); + pager.setTotalRows(villageIdentifyService.count(model.getVillageType(), model.getCity1(), model.getAddress())); + model.setVillageIdentifyList(villageIdentifyService.findAll(model.getVillageType(), model.getCity1(), model.getAddress(), pager)); + return model; + } + + public void expectAction(HttpServletRequest request, HttpServletResponse response) throws IOException { + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + + // 编码文件名,避免乱码 + String fileName = "涉农结果导入后台模板.xlsx"; + String encodedFileName = encodeFileName(fileName, request); + + // 设置 Content-Disposition 响应头 + response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\""); + + // 使用 ClassPathResource 来获取资源文件 + ClassPathResource resource = new ClassPathResource(fileName); + InputStream in = resource.getInputStream(); + OutputStream out = response.getOutputStream(); + + byte[] buffer = new byte[1024]; + int bytesRead; + + while ((bytesRead = in.read(buffer)) != -1) { + out.write(buffer, 0, bytesRead); + } + + out.flush(); + + } + + private String encodeFileName(String fileName, HttpServletRequest request) throws IOException { + String userAgent = request.getHeader("User-Agent"); + String encodedFileName; + + if (userAgent.contains("MSIE") || userAgent.contains("Trident")) { + // 针对IE浏览器 + encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20"); + } else { + // 针对其他浏览器 + encodedFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); + } + + return encodedFileName; + } + + public Object uploadAction(HttpServletRequest request) throws IOException { + Object fileInputStream = ActionContext.getContext().getParameters().get("fileInputStream")[0]; + JsonModel ret = new JsonModel(); + Map data = new HashMap(); + Map dataMap = ExcelUtils.read((InputStream) fileInputStream, 0, 0); + List> addressList = dataMap.get("data"); + List> headers = dataMap.get("header"); + + if (!("涉农类型".equals(headers.get(0)) && "地址".equals(headers.get(2)))) { + data.put("msg", "模板错误"); + } else if (addressList.size() > 100000) { + data.put("msg", "该批次数据量超过100000条"); + } else { + //模板正确,数据不超过100000,开始处理数据 + for (List row : addressList) { + + Map updata = new HashMap(); + // 创建一个包含所有key的list + List keys = Arrays.asList( + "villageType", "cityParam", "address", "province", "provinceCode", + "city1", "cityCode", "district", "districtCode", "town", "townCode", + "committee", "committeeCode", "typeCode", "typeName", "verifyFlag", "addrVerify", + "countyLevelCity", "administrativeTowns", "devDistrict", + "devDistrictName", "devLevel", "countyGov", "addrArea" + ); + + // 遍历keys list并从row中获取相应的值放入updata中 + for (int i = 0; i < keys.size(); i++) { + if (i < row.size() && StringUtils.isNotBlank(row.get(i))) { + updata.put(keys.get(i), row.get(i)); + } + } + + // 处理特定情况: cityParam + String cityParam = ""; + if (StringUtils.isNotBlank(row.get(1))) { + cityParam = row.get(1); + updata.put("cityParam", cityParam); + } + + // 添加createTime + updata.put("createTime", new Date()); + List queryParams = new ArrayList(); + queryParams.add(new QueryParam("address", updata.get("address"))); + if ("" != cityParam) { + queryParams.add(new QueryParam("cityParam", cityParam)); + } + queryParams.add(new QueryParam("villageType", updata.get("villageType"))); + // 保存/更新 + villageIdentifyService.updateByparams(updata, queryParams); + } + data.put("msg", "保存成功"); + } + + + ret.setJsonModel(data); + return ret; + } + + public void setVillageIdentifyService(VillageIdentifyService villageIdentifyService) { + this.villageIdentifyService = villageIdentifyService; + } +} diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/interceptor/FileUploadInterceptor.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/interceptor/FileUploadInterceptor.java new file mode 100644 index 000000000..6d1da882e --- /dev/null +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/interceptor/FileUploadInterceptor.java @@ -0,0 +1,35 @@ +package com.fangjia.bkoff.interceptor; + +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.sothis.core.beans.Bean; +import org.sothis.core.beans.Scope; +import org.sothis.web.mvc.ActionContext; +import org.sothis.web.mvc.ActionInvocation; +import org.sothis.web.mvc.ActionInvocationException; +import org.sothis.web.mvc.Interceptor; +import org.sothis.web.mvc.interceptors.HttpMultipartException; +import org.sothis.web.mvc.interceptors.MultipartHttpServletRequest; + +import javax.servlet.http.HttpServletRequest; + +/** + * 文件上传拦截器 + * @author wenyan + */ +@Bean(scope = Scope.SINGLETON) +public class FileUploadInterceptor implements Interceptor { + + public Object intercept(ActionInvocation invocation) throws ActionInvocationException { + ActionContext context = invocation.getActionContext(); + HttpServletRequest request = context.getRequest(); + if (ServletFileUpload.isMultipartContent(request)) { + try { + context.setRequest(new MultipartHttpServletRequest(request)); + } catch (HttpMultipartException e) { + throw new ActionInvocationException("error process multipart reqeust: ", e); + } + } + return invocation.invoke(); + } + +} diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/ApiUserModel.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/ApiUserModel.java index b252774f1..ad264fe9a 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/ApiUserModel.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/ApiUserModel.java @@ -38,6 +38,7 @@ public class ApiUserModel extends BaseModel { private Integer creditLevelStatus; private String priceType; private Map priceRatingMap; + private Integer isMonitor; public String getPriceType() { return priceType; @@ -606,4 +607,12 @@ public class ApiUserModel extends BaseModel { public void setManager(String manager) { this.manager = manager; } + + public Integer getIsMonitor() { + return isMonitor; + } + + public void setIsMonitor(Integer isMonitor) { + this.isMonitor = isMonitor; + } } diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/BuildingRatioModel.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/BuildingRatioModel.java new file mode 100644 index 000000000..3c916b169 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/BuildingRatioModel.java @@ -0,0 +1,152 @@ +package com.fangjia.bkoff.model; + +import com.fangjia.service.bo.BuildingRatioBo; +import org.springframework.format.annotation.DateTimeFormat; + +import java.util.Date; +import java.util.List; + +/** + * @author zhaojixiang + * @since 2023/7/5 + */ +public class BuildingRatioModel extends BaseModel{ + + private String id; + private String city_name; + private String region; + private String district; + private String building_name; + private String avg_price; + private String building_avg_price; + private String create_user; + private String note; + private Double ratio; + private String msg; + private List buildingRatioBoList; + private BuildingRatioBo buildingRatioBo; + @DateTimeFormat(pattern = "yyyy-MM-dd") + private Date c_date; + @DateTimeFormat(pattern = "yyyy-MM-dd") + private Date m_date; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getCity_name() { + return city_name; + } + + public void setCity_name(String city_name) { + this.city_name = city_name; + } + + public String getRegion() { + return region; + } + + public void setRegion(String region) { + this.region = region; + } + + public String getDistrict() { + return district; + } + + public void setDistrict(String district_name) { + this.district = district_name; + } + + public String getBuilding_name() { + return building_name; + } + + public void setBuilding_name(String building_name) { + this.building_name = building_name; + } + + public Double getRatio() { + return ratio; + } + + public void setRatio(Double ratio) { + this.ratio = ratio; + } + + public Date getC_date() { + return c_date; + } + + public void setC_date(Date c_date) { + this.c_date = c_date; + } + + public Date getM_date() { + return m_date; + } + + public void setM_date(Date m_date) { + this.m_date = m_date; + } + + public List getBuildingRatioBoList() { + return buildingRatioBoList; + } + + public void setBuildingRatioBoList(List buildingRatioBoList) { + this.buildingRatioBoList = buildingRatioBoList; + } + + public BuildingRatioBo getBuildingRatioBo() { + return buildingRatioBo; + } + + public void setBuildingRatioBo(BuildingRatioBo buildingRatioBo) { + this.buildingRatioBo = buildingRatioBo; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public String getCreate_user() { + return create_user; + } + + public void setCreate_user(String create_user) { + this.create_user = create_user; + } + + public String getNote() { + return note; + } + + public void setNote(String note) { + this.note = note; + } + + public String getAvg_price() { + return avg_price; + } + + public void setAvg_price(String avg_price) { + this.avg_price = avg_price; + } + + public String getBuilding_avg_price() { + return building_avg_price; + } + + public void setBuilding_avg_price(String building_avg_price) { + this.building_avg_price = building_avg_price; + } +} diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/DevelopmentZoneModel.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/DevelopmentZoneModel.java new file mode 100644 index 000000000..54f85ab42 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/DevelopmentZoneModel.java @@ -0,0 +1,197 @@ +package com.fangjia.bkoff.model; + +import com.fangjia.dal.mongo.model.DevelopmentZone; +import com.fangjia.dal.mongo.model.LatlngPolygon; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +public class DevelopmentZoneModel extends BaseModel { + private String id; + private String address; + private String buildDate; + private Date createTime; + private String industry; + private String area; + + private String level; + private String name; + private String alias; +// private List addr_alias; + private String nameEn; + private String province; + private String type; + private String url; + private String district; + + List> shape; + List> bdShape; + + private String block; + + private DevelopmentZone developmentZone; + private List developmentZoneList; + + private String cityName1; + + public String getAlias() { + return alias; + } + + public void setAlias(String alias) { + this.alias = alias; + } + + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getBuildDate() { + return buildDate; + } + + public void setBuildDate(String buildDate) { + this.buildDate = buildDate; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public String getIndustry() { + return industry; + } + + public void setIndustry(String industry) { + this.industry = industry; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNameEn() { + return nameEn; + } + + public void setNameEn(String nameEn) { + this.nameEn = nameEn; + } + + public String getProvince() { + return province; + } + + public void setProvince(String province) { + this.province = province; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public List> getShape() { + return shape; + } + + public void setShape(List> shape) { + this.shape = shape; + } + + public List> getBdShape() { + return bdShape; + } + + public void setBdShape(List> bdShape) { + this.bdShape = bdShape; + } + + public String getBlock() { + return block; + } + + public void setBlock(String block) { + this.block = block; + } + + public DevelopmentZone getDevelopmentZone() { + return developmentZone; + } + + public void setDevelopmentZone(DevelopmentZone developmentZone) { + this.developmentZone = developmentZone; + } + + public List getDevelopmentZoneList() { + return developmentZoneList; + } + + public String getArea() { + return area; + } + + public void setArea(String area) { + this.area = area; + } + + public void setDevelopmentZoneList(List developmentZoneList) { + this.developmentZoneList = developmentZoneList; + } + + public String getCityName1() { + return cityName1; + } + + public void setCityName1(String cityName1) { + this.cityName1 = cityName1; + } +} diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/TownshipModel.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/TownshipModel.java new file mode 100644 index 000000000..7de4c3b55 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/TownshipModel.java @@ -0,0 +1,286 @@ +package com.fangjia.bkoff.model; + +import com.alibaba.fastjson.annotation.JSONField; +import com.fangjia.dal.mongo.model.Township; + +import java.util.List; + +public class TownshipModel extends BaseModel { + private String province; + private String city1; + private String district; + private String street; + private String pid; + private String id; + + @JSONField(name = "tjj_province_code") + private String tjjProvinceCode; + + @JSONField(name = "tjj_city_code") + private String tjjCityCode; + + @JSONField(name = "tjj_district_code") + private String tjjDistrictCode; + + @JSONField(name = "tjj_street_code") + private String tjjStreetCode; + + @JSONField(name = "tjj_source_year") + private Integer tjjSourceYear; + + @JSONField(name = "mzb_province_code") + private String mzbProvinceCode; + + @JSONField(name = "mzb_city_code") + private String mzbCityCode; + + @JSONField(name = "mzb_district_code") + private String mzbDistrictCode; + + @JSONField(name = "mzb_district_name") + private String mzbDistrictName; + + @JSONField(name = "mzb_street_code") + private String mzbStreetCode; + + private String type; + + + private String alias; + + + @JSONField(name = "street_pinyin") + private String streetPinyin; + + //民政部区域和统计局区域是否相同,1为相同,0为不同,为了解决2条的问题 + @JSONField(name = "district_diff") + private Integer districtDiff; + + + //乡镇街道是否输出 0:不输出 1:输出 + @JSONField(name = "street_output") + private Integer streetOutput; + + + @JSONField(name = "province_short") + private String provinceShort; + + @JSONField(name = "city_short") + private String cityShort; + + @JSONField(name = "district_short") + private String districtShort; + + private Township township; + private List townshipList; + + public String getProvince() { + return province; + } + + public void setProvince(String province) { + this.province = province; + } + + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getPid() { + return pid; + } + + public void setPid(String pid) { + this.pid = pid; + } + + public String getTjjProvinceCode() { + return tjjProvinceCode; + } + + public void setTjjProvinceCode(String tjjProvinceCode) { + this.tjjProvinceCode = tjjProvinceCode; + } + + public String getTjjCityCode() { + return tjjCityCode; + } + + public void setTjjCityCode(String tjjCityCode) { + this.tjjCityCode = tjjCityCode; + } + + public String getTjjDistrictCode() { + return tjjDistrictCode; + } + + public void setTjjDistrictCode(String tjjDistrictCode) { + this.tjjDistrictCode = tjjDistrictCode; + } + + public String getTjjStreetCode() { + return tjjStreetCode; + } + + public void setTjjStreetCode(String tjjStreetCode) { + this.tjjStreetCode = tjjStreetCode; + } + + public Integer getTjjSourceYear() { + return tjjSourceYear; + } + + public void setTjjSourceYear(Integer tjjSourceYear) { + this.tjjSourceYear = tjjSourceYear; + } + + public String getMzbProvinceCode() { + return mzbProvinceCode; + } + + public void setMzbProvinceCode(String mzbProvinceCode) { + this.mzbProvinceCode = mzbProvinceCode; + } + + public String getMzbCityCode() { + return mzbCityCode; + } + + public void setMzbCityCode(String mzbCityCode) { + this.mzbCityCode = mzbCityCode; + } + + public String getMzbDistrictCode() { + return mzbDistrictCode; + } + + public void setMzbDistrictCode(String mzbDistrictCode) { + this.mzbDistrictCode = mzbDistrictCode; + } + + public String getMzbDistrictName() { + return mzbDistrictName; + } + + public void setMzbDistrictName(String mzbDistrictName) { + this.mzbDistrictName = mzbDistrictName; + } + + public String getMzbStreetCode() { + return mzbStreetCode; + } + + public void setMzbStreetCode(String mzbStreetCode) { + this.mzbStreetCode = mzbStreetCode; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + + public String getStreetPinyin() { + return streetPinyin; + } + + public void setStreetPinyin(String streetPinyin) { + this.streetPinyin = streetPinyin; + } + + public Integer getDistrictDiff() { + return districtDiff; + } + + public void setDistrictDiff(Integer districtDiff) { + this.districtDiff = districtDiff; + } + + public Integer getStreetOutput() { + return streetOutput; + } + + public void setStreetOutput(Integer streetOutput) { + this.streetOutput = streetOutput; + } + + public String getProvinceShort() { + return provinceShort; + } + + public void setProvinceShort(String provinceShort) { + this.provinceShort = provinceShort; + } + + public String getCityShort() { + return cityShort; + } + + public void setCityShort(String cityShort) { + this.cityShort = cityShort; + } + + public String getDistrictShort() { + return districtShort; + } + + public void setDistrictShort(String districtShort) { + this.districtShort = districtShort; + } + + public String getCity1() { + return city1; + } + + public void setCity1(String city1) { + this.city1 = city1; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getAlias() { + return alias; + } + + public void setAlias(String alias) { + this.alias = alias; + } + + public Township getTownship() { + return township; + } + + public void setTownship(Township township) { + this.township = township; + } + + public List getTownshipList() { + return townshipList; + } + + public void setTownshipList(List townshipList) { + this.townshipList = townshipList; + } +} + diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/VillageIdentifyModel.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/VillageIdentifyModel.java new file mode 100644 index 000000000..40c172b33 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/model/VillageIdentifyModel.java @@ -0,0 +1,365 @@ +package com.fangjia.bkoff.model; + +import com.alibaba.fastjson.annotation.JSONField; +import com.fangjia.dal.mongo.model.Township; +import com.fangjia.dal.mongo.model.VillageIdentify; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.springframework.web.multipart.MultipartFile; + +import javax.xml.crypto.Data; +import java.util.List; +import java.util.Date; + +public class VillageIdentifyModel extends BaseModel { + private String province; + private String city1; + private String district; + private String town; + private String committee; + private String type; + private String provinceCode; + private String cityCode; + private String districtCode; + private String townCode; + private String committeeCode; + private String typeCode; + private String typeName; + private String verifyFlag;//涉农标识 + private String addrVerify;//地址是否有效信息 + + private String countyLevelCity;//是否为县级市 + private String administrativeTowns;//是否市辖建制镇 + private String countyGov;//是否为县政府 + private String devDistrict;//是否为开发区 + private String devDistrictName;//开发区 + private String devLevel;//开发区等级 + + private Double lat; + private Double lng; + + private String addrArea; + + + //测试时使用 + private String splitCommittee; + private String splitStreet; + private String poiName; + private String splitStreetNum; + private String dev; + private String communitySource;//居委来源 + private String matchPoiName;//匹配poi的名称 + private String regionInfo;//围栏区域信息 + + private String tjjDistrictName; + + private Date createTime; + private String villageType; + private MultipartFile file; + private List villageIdentifyList; + private String address; + + public String getProvince() { + return province; + } + + public void setProvince(String province) { + this.province = province; + } + + public String getCity1() { + return city1; + } + + public void setCity1(String city1) { + this.city1 = city1; + } + + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } + + public String getTown() { + return town; + } + + public void setTown(String town) { + this.town = town; + } + + public String getCommittee() { + return committee; + } + + public void setCommittee(String committee) { + this.committee = committee; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getProvinceCode() { + return provinceCode; + } + + public void setProvinceCode(String provinceCode) { + this.provinceCode = provinceCode; + } + + public String getCityCode() { + return cityCode; + } + + public void setCityCode(String cityCode) { + this.cityCode = cityCode; + } + + public String getDistrictCode() { + return districtCode; + } + + public void setDistrictCode(String districtCode) { + this.districtCode = districtCode; + } + + public String getTownCode() { + return townCode; + } + + public void setTownCode(String townCode) { + this.townCode = townCode; + } + + public String getCommitteeCode() { + return committeeCode; + } + + public void setCommitteeCode(String committeeCode) { + this.committeeCode = committeeCode; + } + + public String getTypeCode() { + return typeCode; + } + + public void setTypeCode(String typeCode) { + this.typeCode = typeCode; + } + + public String getTypeName() { + return typeName; + } + + public void setTypeName(String typeName) { + this.typeName = typeName; + } + + public String getVerifyFlag() { + return verifyFlag; + } + + public void setVerifyFlag(String verifyFlag) { + this.verifyFlag = verifyFlag; + } + + public String getAddrVerify() { + return addrVerify; + } + + public void setAddrVerify(String addrVerify) { + this.addrVerify = addrVerify; + } + + public String getCountyLevelCity() { + return countyLevelCity; + } + + public void setCountyLevelCity(String countyLevelCity) { + this.countyLevelCity = countyLevelCity; + } + + public String getAdministrativeTowns() { + return administrativeTowns; + } + + public void setAdministrativeTowns(String administrativeTowns) { + this.administrativeTowns = administrativeTowns; + } + + public String getCountyGov() { + return countyGov; + } + + public void setCountyGov(String countyGov) { + this.countyGov = countyGov; + } + + public String getDevDistrict() { + return devDistrict; + } + + public void setDevDistrict(String devDistrict) { + this.devDistrict = devDistrict; + } + + public String getDevDistrictName() { + return devDistrictName; + } + + public void setDevDistrictName(String devDistrictName) { + this.devDistrictName = devDistrictName; + } + + public String getDevLevel() { + return devLevel; + } + + public void setDevLevel(String devLevel) { + this.devLevel = devLevel; + } + + public Double getLat() { + return lat; + } + + public void setLat(Double lat) { + this.lat = lat; + } + + public Double getLng() { + return lng; + } + + public void setLng(Double lng) { + this.lng = lng; + } + + public String getAddrArea() { + return addrArea; + } + + public void setAddrArea(String addrArea) { + this.addrArea = addrArea; + } + + public String getSplitCommittee() { + return splitCommittee; + } + + public void setSplitCommittee(String splitCommittee) { + this.splitCommittee = splitCommittee; + } + + public String getSplitStreet() { + return splitStreet; + } + + public void setSplitStreet(String splitStreet) { + this.splitStreet = splitStreet; + } + + public String getPoiName() { + return poiName; + } + + public void setPoiName(String poiName) { + this.poiName = poiName; + } + + public String getSplitStreetNum() { + return splitStreetNum; + } + + public void setSplitStreetNum(String splitStreetNum) { + this.splitStreetNum = splitStreetNum; + } + + public String getDev() { + return dev; + } + + public void setDev(String dev) { + this.dev = dev; + } + + public String getCommunitySource() { + return communitySource; + } + + public void setCommunitySource(String communitySource) { + this.communitySource = communitySource; + } + + public String getMatchPoiName() { + return matchPoiName; + } + + public void setMatchPoiName(String matchPoiName) { + this.matchPoiName = matchPoiName; + } + + public String getRegionInfo() { + return regionInfo; + } + + public void setRegionInfo(String regionInfo) { + this.regionInfo = regionInfo; + } + + public String getTjjDistrictName() { + return tjjDistrictName; + } + + public void setTjjDistrictName(String tjjDistrictName) { + this.tjjDistrictName = tjjDistrictName; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public String getVillageType() { + return villageType; + } + + public void setVillageType(String villageType) { + this.villageType = villageType; + } + + public MultipartFile getFile() { + return file; + } + + public void setFile(MultipartFile file) { + this.file = file; + } + + public List getVillageIdentifyList() { + return villageIdentifyList; + } + + public void setVillageIdentifyList(List villageIdentifyList) { + this.villageIdentifyList = villageIdentifyList; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} + diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/util/BaseAvgImportServlet.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/util/BaseAvgImportServlet.java index f640377a3..22c68e4cb 100644 --- a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/util/BaseAvgImportServlet.java +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/util/BaseAvgImportServlet.java @@ -459,6 +459,11 @@ public class BaseAvgImportServlet extends HttpServlet { price.setCat("district"); price.setModifyDate(new Date()); guidingPriceService.save(price); + + Map udata = new HashMap(); + udata.put("modificationDate", new Date()); + districtService.updateById(udata, dis.getId()); + HttpRequest request = new HttpRequest(); HashMap params = new HashMap(); params.put("category", "sell"); diff --git a/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/util/ExcelUtils.java b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/util/ExcelUtils.java new file mode 100644 index 000000000..bc9974c76 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/java/com/fangjia/bkoff/util/ExcelUtils.java @@ -0,0 +1,148 @@ +package com.fangjia.bkoff.util; + +import com.alibaba.excel.EasyExcelFactory; +import com.alibaba.excel.ExcelReader; +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.event.AnalysisEventListener; +import org.apache.commons.lang.StringUtils; +import org.apache.poi.ss.formula.eval.ErrorEval; +import org.apache.poi.ss.usermodel.*; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * excel读写工具类 + * + * @author shenjian + * @since 2021/07/12 + */ +public class ExcelUtils { + public static Map read(InputStream inputStream, int sheetIndex, int skipRow) { + // sheetIndex sheet下标 + // skipRow 跳过的表头行数 + Map map = new HashMap(); + List> ret = new ArrayList>(); + InputStream inp = null; + try { + inp = inputStream; + BufferedInputStream bufferedInputStream = new BufferedInputStream(inp, 1024 * 200); + Workbook workbook = WorkbookFactory.create(bufferedInputStream); + workbook.setForceFormulaRecalculation(true); + Sheet sheet = workbook.getSheetAt(sheetIndex); + //行号 + int rowIndex = 0; + for (Row row : sheet) { + rowIndex++; + if (rowIndex <= skipRow) { + continue; + } + short minColIx = 0; + short maxColIx = row.getLastCellNum(); + List rowData = new ArrayList(); + for (short colIx = minColIx; colIx < maxColIx; colIx++) { + Cell cell = row.getCell(colIx); + if (cell == null) { + rowData.add(colIx, null); + } else { + if (StringUtils.isNotBlank(cell.toString())) { + rowData.add(getCellValue(cell).toString()); + }else { + rowData.add(""); + } + } + } + ret.add(rowData); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (inp != null) { + try { + inp.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + map.put("header", ret.subList(0, 1).get(0)); + map.put("data", ret.subList(1, ret.size())); + return map; + } + + public static Object getCellValue(Cell cell) { + switch (cell.getCellType()) { + case Cell.CELL_TYPE_BLANK: + return null; + case Cell.CELL_TYPE_BOOLEAN: + return cell.getBooleanCellValue(); + case Cell.CELL_TYPE_ERROR: + + return ErrorEval.getText(cell.getErrorCellValue()); + case Cell.CELL_TYPE_FORMULA: + try { + return cell.getNumericCellValue(); + } catch (Exception e) { + try { + return cell.getStringCellValue(); + } catch (Exception ex) { + return cell.getRichStringCellValue().getString(); + } + } + case Cell.CELL_TYPE_NUMERIC: + if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) { + return cell.getDateCellValue(); + } + return cell.getNumericCellValue(); + case Cell.CELL_TYPE_STRING: + return cell.getStringCellValue(); + default: + return null; + } + } + + public static class SimpleExcelListener extends AnalysisEventListener { + private List> dataList = new ArrayList>(); + private List headers = new ArrayList(); + + @Override + public void invoke(Object o, AnalysisContext analysisContext) { + Map map = (Map) o; + dataList.add(new ArrayList(map.values())); + } + + @Override + public void invokeHeadMap(Map headMap, AnalysisContext context) { + for (Object val : headMap.values()) { + headers.add((String) val); + } + } + + @Override + public void doAfterAllAnalysed(AnalysisContext analysisContext) { + + } + + List> getDataList() { + return dataList; + } + + void setDataList(List> dataList) { + this.dataList = dataList; + } + + public List getHeaders() { + return headers; + } + + public void setHeaders(List headers) { + this.headers = headers; + } + } +} diff --git a/projects/fangjia-bkoff/src/main/resources/ftl/city.ftl b/projects/fangjia-bkoff/src/main/resources/ftl/city.ftl index b72f6b106..0a6ac6c87 100644 --- a/projects/fangjia-bkoff/src/main/resources/ftl/city.ftl +++ b/projects/fangjia-bkoff/src/main/resources/ftl/city.ftl @@ -9,7 +9,7 @@
diff --git a/projects/fangjia-bkoff/src/main/resources/sothis.properties b/projects/fangjia-bkoff/src/main/resources/sothis.properties index 46c1ca032..5e138d238 100644 --- a/projects/fangjia-bkoff/src/main/resources/sothis.properties +++ b/projects/fangjia-bkoff/src/main/resources/sothis.properties @@ -4,7 +4,7 @@ sothis.viewResolver.class=org.sothis.web.mvc.DefaultModelAndViewResolver sothis.actionMapper.class=org.sothis.web.mvc.DefaultActionMapper sothis.interceptors.params.class=org.sothis.web.mvc.interceptors.ParametersInterceptor -sothis.interceptors.upload.class=org.sothis.web.mvc.interceptors.FileUploadInterceptor +sothis.interceptors.upload.class=com.fangjia.bkoff.interceptor.FileUploadInterceptor sothis.interceptors.auth.class=com.fangjia.bkoff.interceptor.AuthInterceptor sothis.interceptors.stack.default=upload,params,auth diff --git a/projects/fangjia-bkoff/src/main/resources/娑夊啘缁撴灉瀵煎叆鍚庡彴妯℃澘.xlsx b/projects/fangjia-bkoff/src/main/resources/娑夊啘缁撴灉瀵煎叆鍚庡彴妯℃澘.xlsx new file mode 100644 index 000000000..f43174e2b Binary files /dev/null and b/projects/fangjia-bkoff/src/main/resources/娑夊啘缁撴灉瀵煎叆鍚庡彴妯℃澘.xlsx differ diff --git a/projects/fangjia-bkoff/src/main/webapp/apiUser/add.ftl b/projects/fangjia-bkoff/src/main/webapp/apiUser/add.ftl index 410b73fae..907506c9f 100644 --- a/projects/fangjia-bkoff/src/main/webapp/apiUser/add.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/apiUser/add.ftl @@ -1,162 +1,206 @@ <#ftl attributes={"content_type":"text/html; charset=UTF-8"}> <#compress> - - - - - api鐢ㄦ埛鏂板 - - <#include "/common_js.ftl" /> - - - - <#include "/layout/header.ftl" /> -
-${msg!''} - -
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- 鏍忎綅 - - 鍊� -
鏄电О
鐢ㄦ埛鍚�
瀵嗙爜
璐︽埛绫诲瀷 - -
璐︽埛鐢ㄩ�� - -
Email
閿�鍞礋璐d汉
鍏徃
浼颁环璋冩暣姣旂巼(娉ㄦ剰:璁剧疆璇ュ弬鏁板悗浼颁环鎺ュ彛鐨勮繑鍥炰环鏍煎皢涔樹互璇ョ郴鏁�)
siteName
鍒版湡鏃堕棿
ip鍦板潃(姣忚涓�涓狪P鍦板潃)
-
-
- + + + <#include "/layout/header.ftl" /> +
+ ${msg!''} + +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ 鏍忎綅 + + 鍊� +
鏄电О
鐢ㄦ埛鍚�
瀵嗙爜
璐︽埛绫诲瀷 + +
璐︽埛鐢ㄩ�� + +
鏄惁鐩戞帶 + 涓嶇洃鎺� + 鐩戞帶 +
Email
閿�鍞礋璐d汉
鍏徃
浼颁环璋冩暣姣旂巼(娉ㄦ剰:璁剧疆璇ュ弬鏁板悗浼颁环鎺ュ彛鐨勮繑鍥炰环鏍煎皢涔樹互璇ョ郴鏁�) +
siteName
鍒版湡鏃堕棿
ip鍦板潃(姣忚涓�涓狪P鍦板潃) +
+
+
+ - - + function getRandomElement(arr) { + return arr[parseInt(Math.random() * arr.length)]; + } + + function createPassword() { + var password = ""; + + // 纭繚鑷冲皯鍖呭惈涓�涓壒娈婂瓧绗� + password += getRandomElement(special); + + // 闅忔満閫夋嫨鍏朵綑7涓瓧绗� + for (var i = 0; i < 7; i++) { + password += getRandomElement(numAndengAndENGAndSpecial); + } + + // 灏嗙敓鎴愮殑瀵嗙爜鎵撲贡椤哄簭 + password = password.split('').sort(() => 0.5 - Math.random()).join(''); + + return password; + } + + + + \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/apiUser/auth.ftl b/projects/fangjia-bkoff/src/main/webapp/apiUser/auth.ftl index 387007283..9e0ea31e6 100644 --- a/projects/fangjia-bkoff/src/main/webapp/apiUser/auth.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/apiUser/auth.ftl @@ -10,7 +10,27 @@ <#include "/common_js.ftl" /> - + +<#-- 灏嗚〃澶村浐瀹�--> + @@ -31,12 +51,13 @@
- Ap + + API鏁伴噺锛� ${authorityBoList?size}涓� +<#-- --> +<#-- --> +<#-- --> +<#-- --> +<#-- --> +<#-- --> +<#-- --> +<#-- --> - - + + + + + + @@ -144,15 +161,15 @@ return re.test(strIP) } - $("#resetPwd").click(function () { - if (confirm('纭閲嶇疆瀵嗙爜涓恒��123456銆戯紵')) { - $.get('resetPwd', - "userId=" + $("#userId").val(), - function (data) { - alert(status); - }) - } - }) + // $("#resetPwd").click(function () { + // if (confirm('纭閲嶇疆瀵嗙爜涓恒��123456銆戯紵')) { + // $.get('resetPwd', + // "userId=" + $("#userId").val(), + // function (data) { + // alert(status); + // }) + // } + // }) diff --git a/projects/fangjia-bkoff/src/main/webapp/apiUser/editPwd.ftl b/projects/fangjia-bkoff/src/main/webapp/apiUser/editPwd.ftl new file mode 100644 index 000000000..fe85acf7b --- /dev/null +++ b/projects/fangjia-bkoff/src/main/webapp/apiUser/editPwd.ftl @@ -0,0 +1,85 @@ +<#ftl attributes={"content_type":"text/html; charset=UTF-8"}> +<#compress> + + + + + api鐢ㄦ埛瀵嗙爜淇敼 + + + <#include "/common_js.ftl" /> + + + + + + <#include "/layout/header.ftl" /> +
+
+
uri - 鎻忚堪 + API鍚嶇О 鏄惁鏈夋潈闄�鍏ㄩ�� @@ -63,7 +84,7 @@ ${bo.uri!} - ${bo.description!} + ${bo.name!} checked id="auth_${bo_index + 1}" > diff --git a/projects/fangjia-bkoff/src/main/webapp/apiUser/edit.ftl b/projects/fangjia-bkoff/src/main/webapp/apiUser/edit.ftl index caf99a2c7..3f8d5a463 100644 --- a/projects/fangjia-bkoff/src/main/webapp/apiUser/edit.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/apiUser/edit.ftl @@ -43,10 +43,20 @@ ${apiUserBo.userName!}<#if (apiUserBo.displayName??)>(${apiUserBo.displayName!})
瀵嗙爜
瀵嗙爜
瀵嗙爜 +     淇敼瀵嗙爜 +
璐︽埛绫诲瀷 @@ -72,6 +82,13 @@
鏄惁鐩戞帶 + checked="checked" name="isMonitor" value="0" />涓嶇洃鎺� + checked="checked" name="isMonitor" value="1" style="margin-left: 15px;"/>鐩戞帶 +
Email
+ + + + + + + + + + + + + + + +
鐢ㄦ埛鍚�${apiUserBo.userName!}<#if (apiUserBo.displayName??)>(${apiUserBo.displayName!})
鏂板瘑鐮�
+
+
+ + + + \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/apiUser/list.ftl b/projects/fangjia-bkoff/src/main/webapp/apiUser/list.ftl index 0924ceb7e..e16556d06 100644 --- a/projects/fangjia-bkoff/src/main/webapp/apiUser/list.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/apiUser/list.ftl @@ -1,140 +1,179 @@ <#ftl attributes={"content_type":"text/html; charset=UTF-8"}> <#compress> - - - - - api鐢ㄦ埛鍒楄〃 - - <#include "/common_js.ftl" /> - - - <#include "/layout/header.ftl" /> -
- ${msg!''} - -
-
-
- 鍏辨湁鐢ㄦ埛${apiUserBoList?size}涓� -
- - - - - + + + + + api鐢ㄦ埛鍒楄〃 + + <#include "/common_js.ftl" /> + + <#-- 灏嗚〃澶村浐瀹�--> + + + + <#include "/layout/header.ftl" /> +
+ ${msg!''} + +
+
+
+ 鍏辨湁鐢ㄦ埛${apiUserBoList?size}涓� +
+
- ID - - 鏄电О -
+ + + + - - + + - + + - - - - <#if (apiUserBoList??&&apiUserBoList?size>0)> - <#list apiUserBoList as bo> - style="background-color:#C3C3C3"> - - - - - - - - - - - - - - - -
+ ID + + 鏄电О + 璐︽埛鐢ㄩ�� - username - - password - + username + + password + 閿�鍞礋璐d汉 鍏徃 - appKey - + appKey + 璐︽埛绫诲瀷 璐︽埛鐢ㄩ�� + 鏄惁鐩戞帶 + 鍒版湡鏃堕棿 - 鎿嶄綔 -
- ${bo.userId!} - - ${bo.displayName!} - - <#if bo.purpose?? && bo.purpose == 1> - API - <#elseif bo.purpose?? && bo.purpose == 2> - PDS - <#elseif bo.purpose?? && bo.purpose == 4> - 鎴跨敓娲� - - - ${bo.userName!} - - <#if bo.password?? && bo.password == t_util.md5Hex('123456')> - 鍒濆瀵嗙爜 - <#else> - ****** - - - ${bo.manager!} - - ${bo.company!} - - ${bo.appKey!} - - <#if bo.isTest==0> - 姝e紡璐︽埛 - <#else> - 娴嬭瘯璐︽埛 - - - <#if bo.purpose?? && bo.purpose == 1> - API - <#elseif bo.purpose?? && bo.purpose == 2> - PDS - <#elseif bo.purpose?? && bo.purpose == 4> - 鎴跨敓娲� - - - <#if bo.deadTime??> - ${bo.deadTime?string("yyyy骞碝M鏈坉d鏃�")} - - - 鏉冮檺鎺у埗 - 鍩庡競绠$悊 - 浠锋牸璇勭骇 - <#if bo.status==0> - 绂佺敤 - <#else> - 鍐嶅惎鐢� - -
-
-
- - + + 鎿嶄綔 + + + + <#if (apiUserBoList??&&apiUserBoList?size>0)> + <#list apiUserBoList as bo> + style="background-color:#C3C3C3"> + + ${bo.userId!} + + + ${bo.displayName!} + + + <#if bo.purpose?? && bo.purpose == 1> + API + <#elseif bo.purpose?? && bo.purpose == 2> + PDS + <#elseif bo.purpose?? && bo.purpose == 4> + 鎴跨敓娲� + + + + ${bo.userName!} + + + <#if bo.password?? && bo.password == t_util.md5Hex('123456')> + 鍒濆瀵嗙爜 + <#else> + ****** + + + + ${bo.manager!} + + + ${bo.company!} + + + ${bo.appKey!} + + + <#if bo.isTest==0> + 姝e紡璐︽埛 + <#else> + 娴嬭瘯璐︽埛 + + + + <#if bo.purpose?? && bo.purpose == 1> + API + <#elseif bo.purpose?? && bo.purpose == 2> + PDS + <#elseif bo.purpose?? && bo.purpose == 4> + 鎴跨敓娲� + + + + <#if bo.isMonitor==1> + 鏄� + <#else> + 鍚� + + + + <#if bo.deadTime??> + ${bo.deadTime?string("yyyy骞碝M鏈坉d鏃�")} + + + + API鏉冮檺鎺у埗 + 鏂板API + 鍩庡競绠$悊 + 浠锋牸璇勭骇 + <#if bo.status==0> + 绂佺敤 + <#else> + 鍐嶅惎鐢� + + + + + + + + + + \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/avgPriceUpdate/districtDetail.ftl b/projects/fangjia-bkoff/src/main/webapp/avgPriceUpdate/districtDetail.ftl index b173ee86a..2e55ef1c2 100644 --- a/projects/fangjia-bkoff/src/main/webapp/avgPriceUpdate/districtDetail.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/avgPriceUpdate/districtDetail.ftl @@ -1016,7 +1016,7 @@ var type = $(this).attr('type'); var data ={}; var commands = Array(); - commands.push({city:'${district.city!}',region:'${district.region!}',name:'${district.name!}',estateType:'${district.estateType2!}'}) + commands.push({id:'${district.id!}',city:'${district.city!}',region:'${district.region!}',name:'${district.name!}',estateType:'${district.estateType2!}'}) data.commands = commands ; data.calcRange = type; $.ajax({ diff --git a/projects/fangjia-bkoff/src/main/webapp/avgPriceUpdate/guidingPrice.ftl b/projects/fangjia-bkoff/src/main/webapp/avgPriceUpdate/guidingPrice.ftl index 05d865419..aa6278a15 100644 --- a/projects/fangjia-bkoff/src/main/webapp/avgPriceUpdate/guidingPrice.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/avgPriceUpdate/guidingPrice.ftl @@ -68,7 +68,7 @@ - + + + + <#include "/layout/header.ftl" /> +
+${msg!''} + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ 鏍忎綅 + + 鍊� +
鍩庡競
鍖哄煙
灏忓尯鍚嶇О
妤兼爧鍚嶇О
妤兼爧鍧囦环
灏忓尯鍧囦环
妤兼爧绯绘暟
鍒涘缓浜�
澶囨敞
+
+
+ + + + \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/buildingRatio/edit.ftl b/projects/fangjia-bkoff/src/main/webapp/buildingRatio/edit.ftl new file mode 100644 index 000000000..b0b46502e --- /dev/null +++ b/projects/fangjia-bkoff/src/main/webapp/buildingRatio/edit.ftl @@ -0,0 +1,136 @@ +<#ftl attributes={"content_type":"text/html; charset=UTF-8"}> +<#compress> + + + + + 妤兼爧绯绘暟淇℃伅淇敼 + + + <#include "/common_js.ftl" /> + + + + + + <#include "/layout/header.ftl" /> +
+ ${msg!''} + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ 鏍忎綅 + + 鍊� +
鍩庡競
鍖哄煙
灏忓尯鍚嶇О
妤兼爧鍚嶇О
妤兼爧鍧囦环
灏忓尯鍧囦环
妤兼爧绯绘暟
鍒涘缓浜�
澶囨敞
+
+
+ + + + \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/buildingRatio/list.ftl b/projects/fangjia-bkoff/src/main/webapp/buildingRatio/list.ftl new file mode 100644 index 000000000..047159443 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/webapp/buildingRatio/list.ftl @@ -0,0 +1,132 @@ +<#ftl attributes={"content_type":"text/html; charset=UTF-8"}> +<#compress> + + + + + 鍧囦环绠$悊-妤兼爧绯绘暟绠$悊 + + <#include "/common_js.ftl" /> + + + <#include "/layout/header.ftl" /> + +
+
+ 鍩庡競锛� + 鍖哄煙锛� + 灏忓尯锛� + +
+
+ +
+ ${msg!''} + +
+
+
+ 鍏辨湁妤兼爧绯绘暟${buildingRatioBoList?size}涓� +
+ + + + + + + + + + + + + + + + + + + <#if (buildingRatioBoList??&&buildingRatioBoList?size>0)> + <#list buildingRatioBoList as bo> + + + + + + + + + + + + + + + + + +
+ ID + + 鍩庡競 + + 鍖哄煙 + + 灏忓尯鍚嶇О + + 妤兼爧鍚嶇О + + 妤兼爧鍧囦环 + + 灏忓尯鍧囦环 + + 妤兼爧绯绘暟 + + 鍒涘缓浜� + + 鍒涘缓鏃ユ湡 + + 淇敼鏃ユ湡 + + 澶囨敞 + + 鎿嶄綔 +
+ ${bo.id!} + + ${bo.city_name!} + + ${bo.region!} + + ${bo.district!} + + ${bo.building_name!} + + ${bo.building_avg_price!} + + ${bo.avg_price!} + + ${bo.ratio!} + + ${bo.create_user!} + + <#if bo.c_date??> + ${bo.c_date?string("yyyy骞碝M鏈坉d鏃� HH:mm:ss")} + + + <#if bo.m_date??> + ${bo.m_date?string("yyyy骞碝M鏈坉d鏃� HH:mm:ss")} + + + ${bo.note!} + + 缂栬緫 + 鍒犻櫎 +
+
+
+ + + \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/city/edit.ftl b/projects/fangjia-bkoff/src/main/webapp/city/edit.ftl index 6c04cd992..38b8e8317 100644 --- a/projects/fangjia-bkoff/src/main/webapp/city/edit.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/city/edit.ftl @@ -153,7 +153,7 @@ table{text-align: left;} - + + + + +<#include "/common_js.ftl" /> +<#include "/layout/header.ftl" /> +
+ + +
+
+ <#if developmentZone??> + + + + + + + + + + + + +
+ <#if developmentZone??> + <@d_city defaultValue="${developmentZone.cityName1!}" callback="changeCity" callbackField="display" name="cityDisplay" /> + <#else> + <@d_city defaultValue="涓婃捣" callback="changeCity" callbackField="display" name="cityDisplay" /> + + + + + + + + + + + + + +
+ +
+ + + +
+ +
+ +
+ +
+
+
+
+
+ + + + + + + + + + + + + + + + + diff --git a/projects/fangjia-bkoff/src/main/webapp/developmentZone/list.ftl b/projects/fangjia-bkoff/src/main/webapp/developmentZone/list.ftl new file mode 100644 index 000000000..84c9bed96 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/webapp/developmentZone/list.ftl @@ -0,0 +1,112 @@ +<#ftl attributes={"content_type":"text/html; charset=UTF-8"}> +<#compress> + + + + + 寮�鍙戝尯鍥存爮鍒楄〃 + + + + + <#include "/common_js.ftl" /> + <#include "/layout/header.ftl" /> +
+ +
+
+ + + + + + + + + +
+
+
+ 鏌ヨ鍒�${pager.totalRows!}鏉¤褰� + + + + + + + + + + + + + + + <#list developmentZoneList as it> + + + + + + + + + + + + + + + + + +
鍚嶇О鍒悕寮�鍙戝尯绾у埆鐪佷唤鍩庡競鍖哄煙鍖哄潡鏄惁鏈夊洿鏍�鎿嶄綔浜哄憳淇敼鏃ユ湡鎿嶄綔
${it.name!} + <#if it.alias??> + <#list it.alias as item> + ${item?string}<#if item_has_next>, + + + ${it.level!}${it.province!}${it.cityName1!}${it.district!}${it.block!} + <#if it.bdShape?has_content> + 宸叉湁鍥存爮 + + ${it.operator!}${it.createTime!?string("yyyy-MM-dd HH:mm:ss")} + 鏌ョ湅 + 鏂板缓鍥存爮 +<#-- 鍒犻櫎--> +
+ <#if pager??> + <@d_pager controller="developmentZone" action="list" currentPage=pager.currentPage totalPages=pager.totalPages theme="full"/> + +
+
+ + + + \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/developmentZone/show.ftl b/projects/fangjia-bkoff/src/main/webapp/developmentZone/show.ftl new file mode 100644 index 000000000..33dfbda28 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/webapp/developmentZone/show.ftl @@ -0,0 +1,148 @@ +<#ftl attributes={"content_type":"text/html; charset=UTF-8"}> +<#compress> + + + + + 寮�鍙戝尯鍥存爮鍒楄〃 + + + + + <#include "/common_js.ftl" /> + <#include "/layout/header.ftl" /> +
+ + +
+
+ <#if developmentZone??> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
鐪佷唤${developmentZone.province!}
鍩庡競${developmentZone.cityName1!}
鍖哄煙${developmentZone.district!}
绾у埆${developmentZone.level!}
鍚嶇О${developmentZone.name!}
鍒悕 + <#if developmentZone.alias??> + <#list developmentZone.alias as item> + ${item?string}<#if item_has_next>, + + +
鍖哄潡${developmentZone.block!}
+
+
+
+
+
+ + + + + + + + + + + + + + \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/dikuai/edit.ftl b/projects/fangjia-bkoff/src/main/webapp/dikuai/edit.ftl index d25bcbdf0..798c67acc 100644 --- a/projects/fangjia-bkoff/src/main/webapp/dikuai/edit.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/dikuai/edit.ftl @@ -331,7 +331,7 @@ - + - - + + <#----> - - + + <#----> - + diff --git a/projects/fangjia-bkoff/src/main/webapp/district/gaoDeMap.ftl b/projects/fangjia-bkoff/src/main/webapp/district/gaoDeMap.ftl index e65316b8c..6876e9927 100644 --- a/projects/fangjia-bkoff/src/main/webapp/district/gaoDeMap.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/district/gaoDeMap.ftl @@ -44,7 +44,7 @@ - + +
diff --git a/projects/fangjia-bkoff/src/main/webapp/district/latlng2.ftl b/projects/fangjia-bkoff/src/main/webapp/district/latlng2.ftl index cba6a35ea..9a7dc475d 100644 --- a/projects/fangjia-bkoff/src/main/webapp/district/latlng2.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/district/latlng2.ftl @@ -7,7 +7,7 @@ 鐧惧害MAP <#include "/common_js.ftl" /> - + diff --git a/projects/fangjia-bkoff/src/main/webapp/district/map.ftl b/projects/fangjia-bkoff/src/main/webapp/district/map.ftl index 3d5d80901..63189a58e 100644 --- a/projects/fangjia-bkoff/src/main/webapp/district/map.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/district/map.ftl @@ -25,7 +25,7 @@ <#include "/common_js.ftl" /> - + <#----> - + + + + + <#----> - + <#----> - + <#----> - + + diff --git a/projects/fangjia-bkoff/src/main/webapp/district2/officelist.ftl b/projects/fangjia-bkoff/src/main/webapp/district2/officelist.ftl index 961807a3d..5ca872b27 100644 --- a/projects/fangjia-bkoff/src/main/webapp/district2/officelist.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/district2/officelist.ftl @@ -42,20 +42,23 @@ <#include "officeHeader.ftl"/>
+ 鍩庡競: <@d_city defaultValue="${cityDisplay!}" callback="changeCity" callbackField="display" name="cityDisplay" showCountry = "1" /> + 鍖哄煙: - - 绫诲瀷锛� + 绫诲瀷: @@ -345,6 +348,8 @@ + + diff --git a/projects/fangjia-bkoff/src/main/webapp/images/photo/6577f8a8610dfc00011288fd.jpg b/projects/fangjia-bkoff/src/main/webapp/images/photo/6577f8a8610dfc00011288fd.jpg new file mode 100644 index 000000000..c5cef45d7 Binary files /dev/null and b/projects/fangjia-bkoff/src/main/webapp/images/photo/6577f8a8610dfc00011288fd.jpg differ diff --git a/projects/fangjia-bkoff/src/main/webapp/latlngPolygon/edit.ftl b/projects/fangjia-bkoff/src/main/webapp/latlngPolygon/edit.ftl index 4459b3754..e653b4063 100644 --- a/projects/fangjia-bkoff/src/main/webapp/latlngPolygon/edit.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/latlngPolygon/edit.ftl @@ -54,7 +54,7 @@
- + diff --git a/projects/fangjia-bkoff/src/main/webapp/latlngPolygon/show.ftl b/projects/fangjia-bkoff/src/main/webapp/latlngPolygon/show.ftl index 58942ea8d..a1810a04e 100644 --- a/projects/fangjia-bkoff/src/main/webapp/latlngPolygon/show.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/latlngPolygon/show.ftl @@ -48,7 +48,7 @@ - + diff --git a/projects/fangjia-bkoff/src/main/webapp/layout/menu.ftl b/projects/fangjia-bkoff/src/main/webapp/layout/menu.ftl index 719e92e83..339840223 100644 --- a/projects/fangjia-bkoff/src/main/webapp/layout/menu.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/layout/menu.ftl @@ -48,6 +48,8 @@ <@menuitem uri='/developer/list' text="寮�鍙戝晢" /> <@menuitem uri='/agentMaster/listMaster' text="涓粙鍏徃" /> <@menuitem uri='/mortgageInfo/list' text="鎶垫娂鍝�" /> + <@menuitem uri='/developmentZone/list' text="寮�鍙戝尯" /> + <@menuitem uri='/township/list' text="涔¢晣琛楅亾" /> diff --git a/projects/fangjia-bkoff/src/main/webapp/loudong/edit.ftl b/projects/fangjia-bkoff/src/main/webapp/loudong/edit.ftl index 65738179a..83885d5d0 100644 --- a/projects/fangjia-bkoff/src/main/webapp/loudong/edit.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/loudong/edit.ftl @@ -274,7 +274,7 @@ - + --> - + --> - + + - + + + + <#include "/common_js.ftl" /> + <#include "/layout/header.ftl" /> +
+ + +
+ + <#if township??> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
鐪佷唤:
鍩庡競:
鍖哄煙:
姘戞斂閮ㄥ尯鍩�:
涔¢晣琛楅亾:
鍒悕:(鍒悕鐢紝闅斿紑) +
+ +
+ +
+
+ + + + + + + diff --git a/projects/fangjia-bkoff/src/main/webapp/township/list.ftl b/projects/fangjia-bkoff/src/main/webapp/township/list.ftl new file mode 100644 index 000000000..0a3653ae4 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/webapp/township/list.ftl @@ -0,0 +1,71 @@ +<#ftl attributes={"content_type":"text/html; charset=UTF-8"}> +<#compress> + + + + + 涔¢晣琛楅亾鍒楄〃 + + + + + <#include "/common_js.ftl" /> + <#include "/layout/header.ftl" /> +
+
+
+ + + + + + + + + +
+
+
+ 鏌ヨ鍒�${pager.totalRows!}鏉¤褰� + + + + + + + + + + + <#list townshipList as it> + + + + + + + + + + +
鐪佷唤鍩庡競鍖哄煙涔¢晣涔¢晣鍒悕淇敼鏃ユ湡鎿嶄綔浜�
${it.province!}${it.city1!}${it.district!} ${it.street!} <#if it.alias??> + <#list it.alias as item> + ${item?string}<#if item_has_next>, + + + ${it.updateTime!?string("yyyy-MM-dd HH:mm:ss")}${it.operator!}
+ <#if pager??> + <@d_pager controller="township" action="list" currentPage=pager.currentPage totalPages=pager.totalPages theme="full"/> + +
+
+ + + + \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/villageIdentify/importResult.ftl b/projects/fangjia-bkoff/src/main/webapp/villageIdentify/importResult.ftl new file mode 100644 index 000000000..8886e4879 --- /dev/null +++ b/projects/fangjia-bkoff/src/main/webapp/villageIdentify/importResult.ftl @@ -0,0 +1,221 @@ +<#ftl attributes={"content_type":"text/html; charset=UTF-8"}> +<#compress> + + + + + 娑夊啘缁撴灉瀵煎叆 + + + <#include "/common_js.ftl"/> + + + + + <#include "/layout/header.ftl"/> +
+
+
+
+ + + 涓嬭浇妯℃澘 +
+
+
+ 娑夊啘绫诲瀷锛� + + 鍩庡競锛� + + + 鍦板潃锛� + + +
+
+ <#if villageIdentifyList??> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <#if (villageIdentifyList??&&villageIdentifyList?size>0)> + <#list villageIdentifyList as it> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
娑夊啘绫诲瀷鍩庡競(鍙傛暟)鍦板潃鐪佷唤鐪佷唤缂栫爜鍩庡競鍩庡競缂栫爜鍖哄幙鍖哄幙缂栫爜涔¢晣琛楅亾涔¢晣琛楅亾缂栫爜灞呭灞呭缂栫爜鍩庝埂缂栫爜鍩庝埂鍒嗙被娑夊啘鏍囪瘑鍦板潃楠岃瘉鏄惁鍘跨骇甯�鏄惁甯傝緰寤哄埗闀�鏄惁寮�鍙戝尯寮�鍙戝尯鍚嶇О寮�鍙戝尯绾у埆鏄惁鍘挎斂搴�鎵�灞炲尯鍩�鏃堕棿
${it.villageType!}${it.cityParam!}${it.address!}${it.province!}${it.provinceCode!}${it.city1!}${it.cityCode!}${it.district!}${it.districtCode!}${it.town!}${it.townCode!}${it.committee!}${it.committeeCode!}${it.typeCode!}${it.typeName!}${it.verifyFlag!}${it.addrVerify!}${it.countyLevelCity!}${it.administrativeTowns!}${it.devDistrict!}${it.devDistrictName!}${it.devLevel!}${it.countyGov!}${it.addrArea!}${it.createTime?string("yyyy-MM-dd")}
+ + <#if pager??> + <@d_pager action = "base" currentPage = pager.currentPage controller = "villageIdentify" totalPages = pager.totalPages/> + +
+
+ + + + + + \ No newline at end of file diff --git a/projects/fangjia-bkoff/src/main/webapp/yugudan/add.ftl b/projects/fangjia-bkoff/src/main/webapp/yugudan/add.ftl index 1a2c42cf1..10353a22b 100644 --- a/projects/fangjia-bkoff/src/main/webapp/yugudan/add.ftl +++ b/projects/fangjia-bkoff/src/main/webapp/yugudan/add.ftl @@ -1085,7 +1085,7 @@ html { - + + + + + @@ -50,7 +47,14 @@ <#-- --> <#----> +<<<<<<< HEAD <#--fixedNav01--> +======= +<#----> +>>>>>>> c7c2bae298951f01848f2b654c4c5e7fdba454c0
@@ -991,8 +995,6 @@ - - - +
diff --git a/projects/fangjia-dataanalysis/src/main/webapp/seaweed/map.ftl b/projects/fangjia-dataanalysis/src/main/webapp/seaweed/map.ftl index 3b2e7a413..ce2c8036f 100644 --- a/projects/fangjia-dataanalysis/src/main/webapp/seaweed/map.ftl +++ b/projects/fangjia-dataanalysis/src/main/webapp/seaweed/map.ftl @@ -7,7 +7,7 @@ - +
diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddrSvcController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddrSvcController.java index e2774f08b..b35541339 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddrSvcController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddrSvcController.java @@ -1,6 +1,9 @@ package com.fangjia.open.controllers; import com.fangjia.core.util.HttpRequest; +import com.fangjia.dal.common.DistrictKey; +import com.fangjia.dal.mongo.model.VillageIdentify; +import com.fangjia.dal.seaweed.model.District; import com.fangjia.open.dto.addressGovernance.*; import com.fangjia.open.interceptors.Authority; import com.fangjia.open.interceptors.Role; @@ -9,9 +12,33 @@ import com.fangjia.open.model.AddressModel; import com.fangjia.open.model.BasicModel; import com.fangjia.open.model.RestfulModelAndView; import com.fangjia.open.util.CommonDtoUtils; +import com.fangjia.service.bo.DistrictStatBo; +import com.fangjia.service.datastore.DistrictService; +import com.fangjia.service.district.DistrictStatService; +import com.fangjia.service.mongo.fangjia.VillageIdentifyService; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.sothis.core.util.Pager; +import sun.misc.BASE64Encoder; +import java.io.IOException; +import java.net.Authenticator; +import java.net.InetSocketAddress; +import java.net.PasswordAuthentication; +import java.net.Proxy; +import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; @@ -24,6 +51,10 @@ import java.util.Map; @Authority(role = Role.USER) public class AddrSvcController { + private DistrictStatService districtStatService; + private DistrictService districtService; + private VillageIdentifyService villageIdentifyService; + /** * 地址结构化 * @@ -179,7 +210,7 @@ public class AddrSvcController { /** * 地址匹配 */ - public Object matchAction(AddesssMatchModel model) { + public Object matchAction(AddesssMatchModel model) throws Exception { RestfulModelAndView mav = new RestfulModelAndView(); if (StringUtils.isBlank(model.getAddress())) { @@ -195,18 +226,13 @@ public class AddrSvcController { params.put("category", model.getCategory()); params.put("district", model.getSuggestDistrict()); try { - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/match", params, "UTF-8"); - if (json != null) { - int code = json.getInt("status"); - String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); - if (json.containsKey("result")) { - basicModel.setResult(CommonDtoUtils.transformV(MatchedBuildingDto.class, json.get("result"))); - } - mav.setModel(basicModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + //新匹配接口 + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", params, "UTF-8"); + BasicModel basicModel = new BasicModel(200, "ok"); + if (json != null && json.size() > 0) { + basicModel.setResult(CommonDtoUtils.transformV(MatchedBuildingDto.class, json)); } + mav.setModel(basicModel); } catch (Exception e) { e.printStackTrace(); mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); @@ -226,7 +252,7 @@ public class AddrSvcController { mav.setModel(BasicModel.buildBadRequestModel("城市不能为空")); return mav; } - if (StringUtils.isBlank(model.getKeyword())) { + if (StringUtils.isBlank(model.getKeywords())) { mav.setModel(BasicModel.buildBadRequestModel("关键字不能为空")); return mav; } @@ -236,7 +262,7 @@ public class AddrSvcController { Map params = new HashMap(); params.put("city", model.getCity()); params.put("region", model.getRegion()); - params.put("keywords", model.getKeyword()); + params.put("keywords", model.getKeywords()); params.put("page", "0"); params.put("size", String.valueOf(model.getMax() == 0 ? 20 : (model.getMax() > 100 ? 100 : model.getMax()))); try { @@ -262,9 +288,555 @@ public class AddrSvcController { return mav; } +<<<<<<< HEAD public static void main(String[] args) { String address = "江西省南康市蓉江街道办事处麻田村石桥19号"; String townShip = "蓉江街道"; System.out.println(address.substring(address.indexOf(townShip)+townShip.length())); +======= + public Object avgPriceAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", model.getCity()); + params.put("address", model.getAddress()); + params.put("category", model.getCategory()); + params.put("useMap", String.valueOf(model.isUseMap())); +// params.put("district", model.getSuggestDistrict());//接口没有此参数 + try { + //新匹配接口 + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", params, "UTF-8"); + BasicModel basicModel = new BasicModel(200, "ok"); + if (json != null && json.size() > 0) { + MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); + + District district = districtService.findByNameAndAlias(dto.getCity(), dto.getDistrict(), dto.getName(), "district"); + if (null != district) { + DistrictStatBo statBo = districtStatService.findCurrentDistrictStat(new DistrictKey(dto.getCity(), dto.getDistrict(), dto.getName())); + if (null != statBo) { + if (statBo.getDistrictStat() != null) { + dto.setAvgPrice(statBo.getDistrictStat().getAvgPrice()); + } else if (statBo.getVillaDistrictStat() != null) { + dto.setAvgPrice(statBo.getVillaDistrictStat().getAvgPrice()); + } + + } + } + basicModel.setResult(dto); + } + mav.setModel(basicModel); + } catch (Exception e) { + e.printStackTrace(); + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + + return mav; + } + + /** + * 五级地址标准化 + * + * @param model + * @return + */ + public Object fiveLevelStructureAction(AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); + params.put("refCity", StringUtils.isNotBlank(model.getRefCity()) ? model.getRefCity() : null); + params.put("address", model.getAddress()); + // 默认不输出省市区的代码 + params.put("showCode", StringUtils.isNotBlank(model.getShowCode()) ? model.getShowCode() : "0"); + params.put("complete", "true"); + params.put("addressAssessment", "true"); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/v3/structure", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/v3/structure", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + private static final Map areaMap = new HashMap() { + { + // 添加键值对到 Map 中 + put("111", "主城区"); + put("112", "城乡结合区"); + put("121", "镇中心区"); + put("122", "镇乡结合区"); + put("123", "特殊区域"); + put("210", "乡中心区"); + put("220", "村庄"); + } + }; + + /** + * 涉农识别-新规则-南京银行 + * + * @param model + * @return + */ + public Object njcbVillageIdentifyAction(AddressModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); + String address = model.getAddress(); + params.put("address", address); + String type = StringUtils.isNotBlank(model.getType()) ? model.getType() : null; + params.put("type", type); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/v6/villageIdentify", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/v6/villageIdentify", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + //我们的结果 + JSONObject result = json.getJSONObject("result"); + //我们省级及以上有开发区,直接用我们的结果 + if (result.containsKey("devDistrictName")) { + basicModel.setResult(result); + + } else { + try { + //如果是江苏省或者浙江省 调用齐梁的结果 + if ("江苏省".equals(result.getString("province")) || "浙江省".equals(result.getString("province"))) { + //结果比较,如果涉农结果不一致 + //调用齐梁 type :1 对公 0 对私 + //我们 type :1 对私 2 对共 + String qltype = "2".equals(type) ? "1" : "0"; + Map map = senRequest(address, qltype); + // 涉农结果不一样 + if (!map.get("verifyFlag").equals(result.get("verifyFlag"))) { + //城市不一样 用我们 + if (result.containsKey("city")) { + if ((!result.get("city").equals(map.get("city")) && StringUtils.isNotBlank(result.getString("city")))) { + basicModel.setResult(result); + } else { + map.put("addrVerify", "地址有效"); + map.put("typeName", areaMap.get(map.get("typeCode"))); + basicModel.setResult(map); + } + } else { + map.put("addrVerify", "地址有效"); + map.put("typeName", areaMap.get(map.get("typeCode"))); + basicModel.setResult(map); + } + + } else { + basicModel.setResult(result); + } + + } else { + basicModel.setResult(result); + + } + + } catch (Exception e) { + e.printStackTrace(); + basicModel.setResult(result); + } + + } + + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + + /** + * 涉农识别-新规则-基础版本 + * + * @param model + * @return + */ + public Object villageIdentifyAction(AddressModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); + String address = model.getAddress(); + params.put("address", address); + String type = StringUtils.isNotBlank(model.getType()) ? model.getType() : null; + String villageType = "2".equals(model.getType()) ? "对公" : "对私"; + params.put("type", type); + params.put("showFullValue", "2"); + Pager pager = new Pager(1, 1); + VillageIdentify villageResult = villageIdentifyService.findAll(villageType, model.getCity(), model.getAddress(), pager).get(0); + if (villageResult != null && StringUtils.isNotBlank(villageResult.getVerifyFlag())) { + Map resultMap = new HashMap(); + resultMap.put("province",villageResult.getProvince()); + resultMap.put("city",villageResult.getCity1()); + resultMap.put("district",villageResult.getDistrict()); + resultMap.put("town",villageResult.getTown()); + resultMap.put("committee",villageResult.getCommittee()); + resultMap.put("provinceCode",villageResult.getCityCode()); + resultMap.put("cityCode",villageResult.getCityCode()); + resultMap.put("districtCode",villageResult.getDistrictCode()); + resultMap.put("townCode",villageResult.getTownCode()); + resultMap.put("committeeCode",villageResult.getCommitteeCode()); + resultMap.put("typeCode",villageResult.getTypeCode()); + resultMap.put("typeName",villageResult.getTypeName()); + resultMap.put("verifyFlag",villageResult.getVerifyFlag()); + resultMap.put("addrVerify", villageResult.getAddrVerify()); + resultMap.put("countyLevelCity",villageResult.getCountyLevelCity()); + resultMap.put("administrativeTowns",villageResult.getAdministrativeTowns()); + resultMap.put("countyGov",villageResult.getCountyGov()); + resultMap.put("devDistrict",villageResult.getDevDistrict()); + resultMap.put("devDistrictName",villageResult.getDevDistrictName()); + resultMap.put("devLevel",villageResult.getDevLevel()); + resultMap.put("addrArea",villageResult.getAddrArea()); + BasicModel basicModel = new BasicModel(200, "OK"); + basicModel.setResult(resultMap); + mav.setModel(basicModel); + } else { +// params.put("showTestValue", "2"); + Integer radius = model.getRadius(); + params.put("radius", (radius != null && radius != 0) ? radius.toString() : null); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/villageIdentify", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/villageIdentify", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + //我们的结果 + JSONObject result = json.getJSONObject("result"); + //我们省级及以上有开发区,直接用我们的结果 + if (result.containsKey("devDistrictName")) { + basicModel.setResult(result); + + } else { + try { + //如果是江苏省或者浙江省 调用齐梁的结果 + if ("江苏省".equals(result.getString("province")) || "浙江省".equals(result.getString("province"))) { + + //结果比较,如果涉农结果不一致 + //调用齐梁 type :1 对公 0 对私 + //我们 type :1 对私 2 对共 + String qltype = "2".equals(type) ? "1" : "0"; + Map map = senRequest(address, qltype); + // 涉农结果不一样 + if (!map.get("verifyFlag").equals(result.get("verifyFlag"))) { + //有市辖建制镇, 或者城市不一样 用我们 + if (result.containsKey("city")) { + if ("是".equals(result.get("administrativeTowns")) || (!result.get("city").equals(map.get("city")) && StringUtils.isNotBlank(result.getString("city")))) { + basicModel.setResult(result); + } else { + map.put("addrVerify", "地址有效"); + map.put("typeName", areaMap.get(map.get("typeCode"))); + basicModel.setResult(map); + } + } else { + map.put("addrVerify", "地址有效"); + map.put("typeName", areaMap.get(map.get("typeCode"))); + basicModel.setResult(map); + } + + } else { + basicModel.setResult(result); + } + + } else { + basicModel.setResult(result); + + } + + } catch (Exception e) { + e.printStackTrace(); + basicModel.setResult(result); + } + + } + + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + } + return mav; + } + + private static Map senRequest(String address, String type) throws IOException { + String targetURL = "http://146.56.217.44:9010/uams/farmer/all/v3/sign"; + String proxyHost = "tunnel2.qg.net"; + int proxyPort = 14186; + final String proxyUsername = "113BBC06"; + final String proxyPassword = "3B2FBD05B0AF"; + String jsonData = "{\"address\":\"" + address + "\",\"type\":\"" + type + "\"}"; + String authKey = proxyUsername; + String password = proxyPassword; + String auth = authKey + ":" + password; + String authHeader = "Basic " + new BASE64Encoder().encode(auth.getBytes(Charset.forName("UTF-8"))); + + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(targetURL); + Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); + Authenticator.setDefault(new Authenticator() { + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray()); + } + }); + httpPost.setHeader("Content-Type", "application/json"); + httpPost.setHeader("Accept", "*/*"); + httpPost.setHeader("Host", "146.56.217.44:9010"); + httpPost.setHeader("Proxy-Authorization", authHeader); + StringEntity stringEntity = new StringEntity(jsonData, ContentType.APPLICATION_JSON); + httpPost.setEntity(stringEntity); + + CloseableHttpResponse httpResponse = null; + int retryCount = 2; // 设置重试次数 + int retryDelay = 10; // 设置重试延迟时间(毫秒) + boolean success = false; + for (int i = 0; i < retryCount; i++) { + try { + httpResponse = httpClient.execute(httpPost); + success = true; + break; + } catch (IOException e) { + System.err.println("代理请求失败,进行重试..."); + try { + Thread.sleep(retryDelay); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + } + + if (success) { + HttpEntity responseEntity = httpResponse.getEntity(); + String responseString = EntityUtils.toString(responseEntity); + + // 使用 Gson 解析 JSON 字符串 + Gson gson = new Gson(); + JsonObject jsonObject = gson.fromJson(responseString, JsonObject.class); + + + // 创建 Map 存储各个值 + Map dataMap = new HashMap(); + + // 获取各个值并放入 Map +// dataMap.put("code", jsonObject.get("code").getAsString()); +// dataMap.put("msg", jsonObject.get("msg").getAsString()); + JsonElement dataElement = jsonObject.get("data"); + if (dataElement != null && !dataElement.isJsonNull() && dataElement.isJsonObject()) { + JsonObject data = dataElement.getAsJsonObject(); + // 在这里继续处理 data 对象 + + if (data != null && !data.isJsonNull()) { + +// dataMap.put("version", data.get("version").getAsString()); + dataMap.put("province", data.get("province").getAsString()); + dataMap.put("city", data.get("city").getAsString()); + dataMap.put("district", data.get("district").getAsString()); + dataMap.put("town", data.get("town").getAsString()); + dataMap.put("committee", data.get("village").getAsString()); + dataMap.put("provinceCode", data.get("provinceCode").getAsString()); + dataMap.put("cityCode", data.get("cityCode").getAsString()); + dataMap.put("districtCode", data.get("districtCode").getAsString()); + dataMap.put("townCode", data.get("townCode").getAsString()); + dataMap.put("committeeCode", data.get("villageCode").getAsString()); + dataMap.put("typeCode", data.get("areaCode").getAsString()); + dataMap.put("verifyFlag", "0".equals(data.get("farmer").getAsString()) ? "非农" : "农"); + dataMap.put("countyGov", "0".equals(data.get("isGovt").getAsString()) ? "否" : "是"); +// dataMap.put("govtAddr", data.get("govtAddr").isJsonNull() ? null : data.get("govtAddr").getAsString()); // 对于可能为 null 的值,需要判断是否为空 + JsonArray indusParkList = data.get("indusParkList").isJsonNull() ? null : data.get("indusParkList").getAsJsonArray(); + + if (indusParkList != null) { + JsonObject jsonObject1 = gson.fromJson(indusParkList.get(0), JsonObject.class); + dataMap.put("devDistrictName", jsonObject1.get("indusParkName").getAsString()); + dataMap.put("devLevel", jsonObject1.get("indusParkLevel").getAsString()); + dataMap.put("devDistrict", "是"); + } + } + } + + httpResponse.close(); + return dataMap; + } else { + System.err.println("重试次数已用完,请求失败。"); + } + + httpClient.close(); + return null; + } + + /** + * 涉农识别-新规则-标准版 + * + * @param model + * @return + */ + public Object villageIdentifyStandardAction(AddressModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); + params.put("address", model.getAddress()); + params.put("type", StringUtils.isNotBlank(model.getType()) ? model.getType() : null); + params.put("showFullValue", StringUtils.isNotBlank(model.getShowFullValue()) ? model.getShowFullValue() : null); + params.put("showTestValue", StringUtils.isNotBlank(model.getShowTestValue()) ? model.getShowTestValue() : null); + Integer radius = model.getRadius(); + params.put("radius", (radius != null && radius != 0) ? radius.toString() : null); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/villageIdentify", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/villageIdentify", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + + /** + * 地址联想-PRO + * + * @param model + * @return + */ + public Object addressAssociationAction(AddressModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getKeywords()) && (StringUtils.isBlank(model.getLat()) && StringUtils.isBlank(model.getLng()))) { + mav.setModel(BasicModel.buildBadRequestModel("关键字或经纬度必填一个")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); + params.put("district", StringUtils.isNotBlank(model.getDistrict()) ? model.getDistrict() : null); + params.put("keywords", StringUtils.isNotBlank(model.getKeywords()) ? model.getKeywords() : null); + if (StringUtils.isNotBlank(model.getLng()) && StringUtils.isNotBlank(model.getLat())) { + params.put("lat", model.getLat()); + params.put("lng", model.getLng()); + } + Integer radius = model.getRadius(); + params.put("radius", (radius != null && radius != 0) ? radius.toString() : null); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/v2/addressAssociation", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/v2/addressAssociation", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + public void setDistrictStatService(DistrictStatService districtStatService) { + this.districtStatService = districtStatService; + } + + public void setDistrictService(DistrictService districtService) { + this.districtService = districtService; + } + + public void setVillageIdentifyService(VillageIdentifyService villageIdentifyService) { + this.villageIdentifyService = villageIdentifyService; +>>>>>>> c7c2bae298951f01848f2b654c4c5e7fdba454c0 } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddressController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddressController.java index cf00f9e9c..c50eb7af6 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddressController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/AddressController.java @@ -83,3246 +83,3251 @@ import java.util.regex.Pattern; @Authority(role = Role.USER) public class AddressController { - private AddressService addressService; - private DistrictService districtService; - private EvaluationService evaluationService; - private CommDataService commDataService; - private RegionBlockService regionBlockService; - private BaiduApiService baiduApiService; - private AddressParser addressParser; - private ServerAreaService serverAreaService; - private AddressParserService addressParserService; - private WaitCrawlKeywordsService waitCrawlKeywordsService; - private HouseLoudongService houseLoudongService; - private FjtEvaluationService fjtEvaluationService; - private AddressMatchProxyService addressMatchProxyService; - - private final static String AK = OpenConfig.getConfig().getBaiduAk(); - private final static Logger LOGGER = LoggerFactory.getLogger(AddressController.class); - - private static Map> districts_cache = new HashMap>(); - - private static final String FJW_LEVEL = "5CAE1FAC646CB2D8"; - private static final String GRADE_AREA = "区域评分"; - private static final String GRADE_CITY = "城市评分"; - private static final String GRADE_NATION = "全国评分"; - private static final String GRADE_CONSUME = "消费评分"; - - public final static OpenConfig CONFIG = OpenConfig.getConfig(); - private static final String ES_USER = "developer"; - private static final String ES_PASSWORD = "5e8edd851d2fdfbd7415232c67367cc3"; - - /** - * @deprecated see parse2Action - * @param model - * @return - */ - @Authority(role = Role.USER) - public Object parseAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setModel(addressParser.parse(model.getCity(), model.getAddress(), model.getTarget(), model.isNearby())); - return mav; - } - - @Authority(role = Role.USER) - public Object parse2Action(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - if (ServerAreaData.getServerAreaByCity(model.getCity()) == null) { - HashMap resMap = new HashMap(); - resMap.put("status", 0); - resMap.put("precise", -1); - resMap.put("searchKey", model.getAddress()); - mav.setModel(resMap); - return mav; - } - mav.setModel(addressParser.parse2(model.getCity(), model.getAddress(), model.getTarget(), model.isNearby())); - return mav; - } - - /** - * 解析地址,能够返回多个结果 参数有:city 城市 address 地址 includeMaps - * 匹配的结果是否包含来自地图的数据,true表示结果包含来自地图的数据 max 返回的结果集中最多条数 - * - * @param model - * @return - */ - @Authority(role = Role.USER) - public Object parseAsListAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setModel( - addressParser.parseAsList(model.getCity(), model.getAddress(), model.isIncludeMaps(), model.getMax())); - return mav; - } - - @Authority(role = Role.USER) - public Object cacheFlushAction(AddesssMatchModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - String result = addressMatchProxyService.cacheFlush(convertModelToMap(model)); - mav.setModel(result); - return mav; - } - - @Authority(role = Role.USER) - public Object analyzeAction(AddressModel model){ - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getCity())) { - mav.setModel(BasicModel.buildBadRequestModel("城市不能为空")); - return mav; - } - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - HttpRequest request = new HttpRequest(); - Map params = new HashMap(); - params.put("address", model.getAddress()); - params.put("city", model.getCity()); - try { - JSONObject result = request.getJsonContent("http://192.168.0.19:38080/FangJiaHelper/address/analyze/api", params, "UTF-8"); - mav.setModel(BasicModel.buildOKModel().setResult(result)); - } catch (HttpRequestException e) { - e.printStackTrace(); - } - return mav; - } - - public Object rateAction(@Valid RateModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - JSONArray dataList; - try { - dataList = JSONArray.fromObject(model.getData()); - } catch (Exception e) { - mav.setModel(BasicModel.buildBadRequestModel("数据格式错误")); - return mav; - } - List metaDatas = new ArrayList(dataList.size()); - JSONObject item; - AddressMatchMetaData metaData; - Map idMap = new HashMap(dataList.size()); - for (int i = 0; i < dataList.size(); i++) { - item = dataList.getJSONObject(i); - metaData = new AddressMatchMetaData(); - if (item.containsKey("city")) { - metaData.setCity(item.getString("city")); - } else { - metaData.setCity(model.getCity()); - } - if (item.containsKey("district")) { - metaData.setDistrict(item.getString("district")); - } - metaData.setMainName(item.getString("name")); - metaData.addName(item.getString("name"), MatchText.MAIN_NAME_PRIORITY); - if (item.containsKey("address")) { - Map addrWeightMap = analyseAddress(model.getCity(), item.getString("address")); - for (String addr : addrWeightMap.keySet()) { - metaData.addAddress(addr, addrWeightMap.get(addr)); - } - } - if (item.containsKey("uid")) { - metaData.setId(item.getString("uid")); - idMap.put(metaData.getId(), item); - } - if (item.containsKey("lng")) { - metaData.setLng(item.getDouble("lng")); - } - if (item.containsKey("lat")) { - metaData.setLat(item.getDouble("lat")); - } - metaData.setBuildingType(BuildingType.DISTRICT); - metaDatas.add(metaData); - } - AddressRate addressRate = addressParserService.rate(model.getCity(), model.getAddress(), metaDatas); - List results = new ArrayList(metaDatas.size()); - for (AddressMatchMetaData meta : addressRate.getMetaData()) { - JSONObject result = idMap.get(meta.getId()); - results.add(result); - } - mav.setModel(BasicModel.buildOKModel().setResult(results)); - return mav; - } - - private Map analyseAddress(String city, String address) { - - if (StringUtils.isBlank(address)) { - return Collections.EMPTY_MAP; - } - try { - Address addr = addressParserService.standardize(city, address); - if (!addr.isAvailable()) { - return Collections.EMPTY_MAP; - } - Map addrWeightMap = new HashMap(); - - if (StringUtils.isNotBlank(addr.getStreet())) { - String street = addr.getStreet(); - List streets = new ArrayList(); - streets.add(street); - if (street.endsWith("弄")) { - addrWeightMap.put(street, MatchText.MAIN_ADDR_PRIORITY); - addrWeightMap.put(street.replaceAll("弄$", "号"), MatchText.GEN_ADDR_PRIORITY); - streets.add(street.replaceAll("弄$", "号")); - } - if (StringUtils.isNotBlank(addr.getStreetNumber())) { - for (String s : streets) { - if (addr.getStreetNumber().endsWith("号")) { - addrWeightMap.put(s + addr.getStreetNumber().replaceAll("号$", "弄"), - MatchText.GEN_ADDR_PRIORITY); - } else if (street.endsWith("弄")) { - addrWeightMap.put(s + addr.getStreetNumber().replaceAll("弄$", "号"), - MatchText.GEN_ADDR_PRIORITY); - } - } - } - - if (CollectionUtils.isNotEmpty(addr.getStreetNumbers())) { - addrWeightMap.put(street + addr.getStreetNumber(), MatchText.MAIN_ADDR_PRIORITY); - for (String s : streets) { - for (String streetNumber : addr.getStreetNumbers()) { - if (streetNumber.endsWith("号")) { - addrWeightMap.put(s + streetNumber.replaceAll("号$", "弄"), MatchText.GEN_ADDR_PRIORITY); - } else if (street.endsWith("弄")) { - addrWeightMap.put(s + streetNumber.replaceAll("弄$", "号"), MatchText.GEN_ADDR_PRIORITY); - } - } - } - } - - } else { - addrWeightMap.put(addr.getMiniAddress(), MatchText.MAIN_ADDR_PRIORITY); - } - return addrWeightMap; - } catch (Exception e) { - - } - return Collections.EMPTY_MAP; - - } - - public Object standardizeAction(AddressModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - Address address = addressParserService.standardize(model.getCity(), model.getAddress()); - mav.setModel(BasicModel.buildOKModel().setResult(address)); - return mav; - } - - public Object realCertificateAction(AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (!OpenConfig.getConfig().addressMatchEnabled()) { - mav.setModel(BasicModel.buildBadRequestModel("不支持该服务")); - return mav; - } - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - MatchParams matchParams = new MatchParams(); - matchParams.setCity(model.getCity()); - matchParams.setAddress(model.getAddress()); - matchParams.setAddressParserGoal(AddressParserGoal.Certificate); - matchParams.setPreciseLevel(PreciseLevel.STRICT); - Building building = addressParserService.certificate(matchParams); - Address address = building.getSearchAddress(); - UniversalDto dto = UniversalDto.newDto(); - dto.append("province", address.getProvince()); - dto.append("city", address.getCity()); - if (address.getDistrict() != null) { - dto.append("district", address.getDistrict()); - } else { - dto.append("district", building.getDistrict()); - } - dto.append("developmentZone", address.getDevelopmentZone()); - dto.append("township", address.getTownship()); - dto.append("street", address.getStreet()); - dto.append("streetNumber", address.getStreetNumber()); - dto.append("name", building.getSuggestName()); - dto.append("buildingNumber", address.getBuildingNumber()); - dto.append("unitNumber", address.getUnitNumber()); - dto.append("roomNumber", address.getRoomNumber()); - dto.append("formattedAddress", address.getFormattedAddress()); - dto.append("certified", address.getCertified()); - dto.append("floor", address.getFloor()); - mav.setModel(BasicModel.buildOKModel().setResult(dto)); - return mav; - } - - public Object certificateAction(AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - String result = addressMatchProxyService.certificate(convertModelToMap(model)); - if (result != null) { - mav.setModel(result); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - public Object authAction(AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - String result = addressMatchProxyService.auth(convertModelToMap(model)); - if (result != null) { - mav.setModel(result); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - public Object realAuthAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - if (!OpenConfig.getConfig().addressMatchEnabled()) { - mav.setModel(BasicModel.buildBadRequestModel("不支持该服务")); - return mav; - } - MatchParams matchParams = new MatchParams(); - matchParams.setCity(model.getCity()); - matchParams.setAddress(model.getAddress()); - matchParams.setAddressParserGoal(AddressParserGoal.Certificate); - matchParams.setUseMap(true); - Building building = addressParserService.certificate(matchParams); - Address address = building.getSearchAddress(); - UniversalDto dto = UniversalDto.newDto(); - dto.append("province", address.getProvince()); - dto.append("city", address.getCity()); - dto.append("district", address.getDistrict()); - dto.append("developmentZone", address.getDevelopmentZone()); - dto.append("township", address.getTownship()); - dto.append("street", address.getStreet()); - dto.append("streetNumber", address.getStreetNumber()); - dto.append("buildingNumber", address.getBuildingNumber()); - dto.append("unitNumber", address.getUnitNumber()); - dto.append("roomNumber", address.getRoomNumber()); - dto.append("formattedAddress", address.getFormattedAddress()); - List certified = address.getCertified(); - if (certified.contains("roomNumber")) { - dto.append("authLevel", "A"); - } else if (certified.contains("buildingNumber")) { - dto.append("authLevel", "B"); - } else { - dto.append("authLevel", "C"); - } - mav.setModel(BasicModel.buildOKModel().setResult(dto)); - return mav; - } - - public Map analyseAddress(String address) { - Map ret = new HashMap(); - ret.put("address", address); - if (districts_cache.isEmpty()) { - List serverAreas = serverAreaService.findAll(); - for (ServerArea serverArea : serverAreas) { - if (StringUtils.isBlank(serverArea.getProvince())) { - continue; - } - String city = serverArea.getDisplay(); - String province = serverArea.getProvince(); - List cities = districts_cache.get(province); - if (cities == null) { - cities = new ArrayList(); - districts_cache.put(province, cities); - } - if (!cities.contains(city)) { - cities.add(city); - } - } - } - - for (Entry> p : districts_cache.entrySet()) { - if (address.startsWith(p.getKey())) { - ret.put("province", p.getKey()); - List cities = p.getValue(); - if (cities.size() == 1 && cities.contains(p.getKey())) {// 直辖市 - ret.put("city", p.getKey()); - } else { - String temp = address.substring(p.getKey().length());// 移除省份 - if (temp.startsWith("省") || temp.startsWith("市") || temp.startsWith("县") || temp.startsWith("区")) { - temp = temp.substring(1); - } - for (String c : cities) { - if (temp.startsWith(c)) { - ret.put("city", c); - break; - } - } - } - break; - } - } - return ret; - } - - @Authority(role = Role.USER) - public Object matchAction(AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - String result = addressMatchProxyService.parser(convertModelToMap(model)); - if (result != null) { - JSONObject json = JSONObject.fromObject(result); - BasicModel resultModel = new BasicModel(json.getInt("code"), json.getString("msg")); - resultModel.setResult(json.get("result")); - mav.setModel(resultModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - /** - * 地址匹配第二个版本,基于第一个版本的逻辑,对匹配出的结果进行正确性的判断 - * @author yinjihuan - * @param model - * @return - */ - @Authority(role = Role.USER) - public Object matchV2Action(AddesssMatchModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - String result = addressMatchProxyService.parser(convertModelToMap(model)); - JSONObject json = JSONObject.fromObject(result); - BasicModel resultModel = new BasicModel(json.getInt("code"), json.getString("msg")); - if (result != null) { - JSONObject jsonResult = (JSONObject) json.get("result"); - if (jsonResult != null && jsonResult.getDouble("credit") > 0) { - CheckMatchDistrictCorrectParam param = new CheckMatchDistrictCorrectParam(); - String city = jsonResult.getString("city"); - String region = jsonResult.getString("district"); - String name = jsonResult.getString("name"); - param.setCity(city); - param.setRegion(region); - param.setName(name); - param.setInputAddress(model.getAddress()); - if (jsonResult.containsKey("lng")) { - param.setBlng(jsonResult.getDouble("lng")); - } - if (jsonResult.containsKey("lat")) { - param.setBlat(jsonResult.getDouble("lat")); - } - param.setDebug(model.isDebug()); - District district = districtService.findDistrict(new DistrictKey(city, region, name), "district"); - if (district != null && district.getLng() != null && district.getLng() > 0) { - param.setGlng(district.getLng() / 10000000000.0); - param.setGlat(district.getLat() / 10000000000.0); - } - MatchDistrictResult matchResult = addressMatchProxyService.checkMatchDistrictCorrect(param); - jsonResult.put("matchResult", matchResult); - if (jsonResult.containsKey("category")) { - if ("office".equals(jsonResult.getString("category"))) { - jsonResult.put("propertyType", "写字楼"); - } else if ("shop".equals(jsonResult.getString("category"))) { - jsonResult.put("propertyType", "商铺"); - } - } - } else if (jsonResult != null) { - // 判断是否为自然村 - boolean matchedVillage = false; - try { - if (jsonResult.get("searchAddress") != null) { - JSONObject searchAddress = (JSONObject) jsonResult.get("searchAddress"); - String city = searchAddress.containsKey("city") ? searchAddress.getString("city") : null; - String region = searchAddress.containsKey("district") ? searchAddress.getString("district") : null; - String name = searchAddress.containsKey("keywords") ? searchAddress.getString("keywords") : null; - String township = searchAddress.containsKey("township") ? searchAddress.getString("township") : null; - if (StringUtils.isNotBlank(city) && StringUtils.isNotBlank(region) && StringUtils.isNotBlank(name)) { - List villages = findVillage(city, region, name); - if (CollectionUtils.isNotEmpty(villages)) { - if (villages.size() == 1 || StringUtils.isBlank(township)) { - JSONObject village = villages.get(0).getJSONObject("_source"); - jsonResult.put("id", villages.get(0).getString("_id")); - jsonResult.put("province", village.getString("province")); - jsonResult.put("city", village.getString("city")); - jsonResult.put("district", village.getString("region")); - jsonResult.put("township", village.getString("township")); - jsonResult.put("name", village.getString("name")); - jsonResult.put("lng", village.getJSONObject("location").getDouble("lon")); - jsonResult.put("lat", village.getJSONObject("location").getDouble("lat")); - jsonResult.put("propertyType", "自然村"); - matchedVillage = true; - } else { - for (JSONObject source : villages) { - JSONObject village = source.getJSONObject("_source"); - if (village.getString("township").contains(township) || township.contains(village.getString("township"))) { - jsonResult.put("id", source.getString("_id")); - jsonResult.put("province", village.getString("province")); - jsonResult.put("city", village.getString("city")); - jsonResult.put("district", village.getString("region")); - jsonResult.put("township", village.getString("township")); - jsonResult.put("name", village.getString("name")); - jsonResult.put("lng", village.getJSONObject("location").getDouble("lon")); - jsonResult.put("lat", village.getJSONObject("location").getDouble("lat")); - jsonResult.put("propertyType", "自然村"); - matchedVillage = true; - break; - } - } - } - } - } - } - } catch(Exception ex) { - ex.printStackTrace(); - } - if (matchedVillage == false) { - jsonResult.put("matchResult", new MatchDistrictResult()); - } - } - resultModel.setResult(json.get("result")); - mav.setModel(resultModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - public Object realMatchAction(@Valid AddesssMatchModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (!OpenConfig.getConfig().addressMatchEnabled()) { - mav.setModel(BasicModel.buildBadRequestModel("不支持该服务")); - return mav; - } - String address = model.getAddress(); - address = address.replaceAll("@@", "#");// 框架无法处理参数带有#的Buge 用@@代替 - BuildingType buildingType = null; - if (StringUtils.isNotBlank(model.getCategory())) { - if ("property".equals(model.getCategory())) { - model.setCategory("district"); - } - try { - buildingType = BuildingType.valueOf(model.getCategory().toUpperCase()); - } catch (Exception e) { - - } - } - PreciseLevel preciseLevel = PreciseLevel.FUZZY; - if ("strict".equals(model.getPreciseLevel())) { - preciseLevel = PreciseLevel.STRICT; - } - MatchParams params = new MatchParams(); - params.setCity(model.getCity()); - params.setSuggestDistrict(model.getSuggestDistrict()); - params.setSuggestName(model.getSuggestName()); - params.setAddress(address); - params.setBuildingType(buildingType); - params.setPreciseLevel(preciseLevel); - params.setProvince(model.getProvince()); - params.setUseMap(model.isUseMap()); - params.setDebugName(model.getDebugName()); - long start = System.currentTimeMillis(); - Building building = addressParserService.parser(params); - long end = System.currentTimeMillis(); - if (end - start > 200) { - LOGGER.warn("匹配parser耗时:\t" + (end - start) + "ms"); - } - if ("true".equalsIgnoreCase(model.getVerify())) { - verify(building); - } - BasicModel baseModel = BasicModel.buildOKModel(); - Map result = convertBuildingToMap(building); - if (!APIConstant.SUPER_USER_TOKEN.equals(model.getToken())) { - submitFetchTask(building); - result.remove("precise"); - result.remove("searchAddress"); - result.remove("map"); - } - baseModel.setResult(result); - mav.setModel(baseModel); - return mav; - } - - Map convertBuildingToMap(Building building) { - Map result = new LinkedHashMap(); - if (building != null) { - result.put("id", building.getId()); - result.put("credit", building.getCredit()); - result.put("precise", building.getPrecise()); - result.put("province", building.getProvince()); - result.put("city", building.getCity()); - result.put("district", building.getDistrict()); - result.put("name", building.getName()); - result.put("suggestName", building.getSuggestName()); - result.put("map", building.getMap()); - result.put("propertyType", building.getPropertyType()); - result.put("township", building.getTownship()); - result.put("suggestAddress", building.getSuggestAddress()); - if ("district".equals(building.getCategory())) { - result.put("category", "property"); - } else { - result.put("category", building.getCategory()); - } - result.put("address", building.getAddress()); - result.put("block", building.getBlock()); - result.put("lng", building.getLng()); - result.put("lat", building.getLat()); - result.put("alias", building.getAlias()); - result.put("searchAddress", building.getSearchAddress()); - } - return result; - } - - public Object cleanCacheAction(final AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (!OpenConfig.getConfig().addressMatchEnabled()) { - mav.setModel(BasicModel.buildBadRequestModel("不支持该服务")); - return mav; - } - new Thread() { - @Override - public void run() { - addressParserService.clearCache(model.getCity()); - } - }.start(); - mav.setModel(BasicModel.buildOKModel().setMsg("开始刷新缓存")); - return mav; - } - - @Authority(role = Role.NONE) - public Object realMatchAllAction(@Valid AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (!OpenConfig.getConfig().addressMatchEnabled()) { - mav.setModel(BasicModel.buildBadRequestModel("不支持该服务")); - return mav; - } - String address = model.getAddress(); - address = address.replaceAll("@@", "#");// 框架无法处理参数带有#的Buge 用@@代替 - BuildingType buildingType = null; - if (StringUtils.isNotBlank(model.getCategory())) { - if ("property".equals(model.getCategory())) { - model.setCategory("district"); - } - buildingType = BuildingType.valueOf(model.getCategory().toUpperCase()); - } - PreciseLevel preciseLevel = PreciseLevel.FUZZY; - if ("strict".equals(model.getPreciseLevel())) { - preciseLevel = PreciseLevel.STRICT; - } - MatchParams params = new MatchParams(); - params.setCity(model.getCity()); - params.setSuggestDistrict(model.getSuggestDistrict()); - params.setAddress(address); - params.setBuildingType(buildingType); - params.setPreciseLevel(preciseLevel); - params.setProvince(model.getProvince()); - params.setSuggestName(model.getSuggestName()); - AddressParseResult addressParseResult = addressParserService.parserAll(params); - List buildings = addressParseResult.getBuildings(); - List> buildingObjs = new ArrayList>(buildings.size()); - for (Building building : buildings) { - buildingObjs.add(convertBuildingToMap(building)); - } - BasicModel baseModel = BasicModel.buildOKModel(); - baseModel.setResult(buildingObjs); - mav.setModel(baseModel); - return mav; - } - - @Authority(role = Role.USER) - public Object matchAllAction(AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - String result = addressMatchProxyService.parserAll(convertModelToMap(model)); - if (result != null) { - mav.setModel(result); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - public Map convertModelToMap(AddesssMatchModel model) { - - Map params = new HashMap(); - Class clzz = model.getClass(); - for (Field field : clzz.getDeclaredFields()) { - field.setAccessible(true); - String paramName = field.getName(); - try { - Object val = field.get(model); - if (val != null) { - params.put(paramName, val.toString()); - } - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - return params; - } - - private void verify(Building building) { - String city = building.getCity(); - String region = building.getDistrict(); - String name = null; - if (building.getPrecise() > -1) { - name = building.getName(); - } else { - name = building.getSearchAddress().getOrgKeywords(); - } - if (StringUtils.isNotBlank(region) && StringUtils.isNotBlank(name)) { - String buildingNumber = AddressParserUtil - .standardizeBuildingNumber(building.getSearchAddress().getOrgBuildingNumber()); - if (buildingNumber != null) { - if (houseLoudongService.findHouseLoudong(city, region, name, buildingNumber, null, null) != null) { - building.getSearchAddress().setBuildingNumberCertified(true); - } else if (fjtEvaluationService.findFjtEvaluationByConditions(city, region, name, buildingNumber, - null) != null) { - building.getSearchAddress().setBuildingNumberCertified(true); - } else if (evaluationService.findEvaluationByNum(city, region, name, buildingNumber, null) != null) { - building.getSearchAddress().setBuildingNumberCertified(true); - } - } - - String roomNumber = AddressParserUtil.standardizeRoomNumber(building.getSearchAddress().getOrgRoomNumber()); - if (roomNumber != null) { - if (houseLoudongService.findHouseLoudong(city, region, name, null, null, roomNumber) != null) { - building.getSearchAddress().setRoomNumberCertified(true); - } else if (fjtEvaluationService.findFjtEvaluationByConditions(city, region, name, null, - roomNumber) != null) { - building.getSearchAddress().setRoomNumberCertified(true); - } else if (evaluationService.findEvaluationByNum(city, region, name, null, roomNumber) != null) { - building.getSearchAddress().setRoomNumberCertified(true); - } - } - } - } - - @Authority(role = Role.NONE) - public Object sendFetchTaskAction(AddressModel model) { - - RestfulModelAndView json = new RestfulModelAndView(); - WaitCrawlKeywords waitCrawlKeywords = new WaitCrawlKeywords(); - waitCrawlKeywords.setCity(model.getCity()); - waitCrawlKeywords.setDateCreated(new Date()); - waitCrawlKeywords.setRead(0); - waitCrawlKeywords.setKeywords(model.getAddress()); - waitCrawlKeywordsService.save(waitCrawlKeywords); - json.setModel(waitCrawlKeywords); - - return json; - } - - private void submitFetchTask(Building building) { - if (building.getPrecise() == -1) { - List keywords = new ArrayList(); - Address address = building.getSearchAddress(); - if (StringUtils.isNotBlank(address.getKeywords()) && address.getKeywords().length() > 2) { - keywords.add(address.getKeywords()); - } else if (address.getOrgAddress().length() > 2 && address.getOrgAddress().length() < 10) {// 一般小区名不会超过10个字 - keywords.add(address.getOrgAddress()); - } - if (address.isStandardAddress()) { - if (address.getStreetNumbers() != null) { - for (String b : address.getStreetNumbers()) { - keywords.add(address.getStreet() + b); - } - } else { - keywords.add(address.getStreet()); - } - } - keywords = DataUtil.uniqueList(keywords); - for (String k : keywords) { - WaitCrawlKeywords waitCrawlKeywords = new WaitCrawlKeywords(); - waitCrawlKeywords.setCity(address.getCity()); - waitCrawlKeywords.setDateCreated(new Date()); - waitCrawlKeywords.setRead(0); - waitCrawlKeywords.setKeywords(k); - waitCrawlKeywordsService.save(waitCrawlKeywords); - } - } - } - - /** - * 从Excel表中加载测试数据 - * - * @return - */ - private List> loadTestDataFromExcel(String excelFileName) { - List> ret = new ArrayList>(); - FileInputStream fileInputStream = null; - try { - fileInputStream = new FileInputStream(excelFileName); - HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream); - HSSFSheet sheet = workbook.getSheetAt(0); - // 行号 - boolean isFirstRow = true; - for (Row row : sheet) { - if (isFirstRow) { - // 第一行,过掉 - isFirstRow = false; - continue; - } - - // 得到列数 - // row.getPhysicalNumberOfCells(); - String in_name = row.getCell(1).toString(); - if (in_name.equals("")) { - // 跳过空内容 - continue; - } - Map data = new HashMap(); - // 第0列:城市 - data.put("city", row.getCell(0).toString()); - // 第一列:输入地址 - data.put("in_name", in_name); - // 第二列:期望名称,用于验证 - Cell cell = row.getCell(2); - if (cell != null) { - data.put("out_name", cell.toString()); - } - ret.add(data); - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (fileInputStream != null) { - try { - fileInputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - return ret; - } - - /** - * 从Excel表中加载测试数据 - * - * @return - */ - private List> loadJingDongTestDataFromExcel(String excelFileName) { - - List> ret = new ArrayList>(); - FileInputStream fileInputStream = null; - try { - fileInputStream = new FileInputStream(excelFileName); - HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream); - HSSFSheet sheet = workbook.getSheetAt(0); - // 行号 - boolean isFirstRow = true; - for (Row row : sheet) { - if (isFirstRow) {// 第一行,过掉 - isFirstRow = false; - continue; - } - String province = row.getCell(0).toString(); - String city = row.getCell(1).toString(); - String in_address = row.getCell(2).toString(); - if (StringUtils.isBlank(in_address) || StringUtils.isBlank(city) || StringUtils.isBlank(province)) { // 跳过空内容 - System.out.println("-->" + row.getRowNum()); - continue; - } - - Map formate = analyseAddress(in_address); - Map data = new HashMap(); - data.put("in_address", in_address); - data.put("city", city); - String formattedAddress = new String(in_address); - List huanxian = Arrays.asList("中环外环之间", "内环以内", "内环中环之间", "中环以内", "外环以外", "(内环高速以里)", "外环外其它地区", - "五环以外", "六环以内", "内环到三环里", "内环到二环里", "二环里", "三环到四环之间", "二环到三环", "四环到五环之间", "二环到三环", "五环至六环之间", - "五环到六环之间", "五环到六环之间", "三环以内", "四环到五环内", "六环以外(其他地区)", "六环以外(张家湾镇、台湖镇、漷县镇)", "六环以外(宋庄镇)", - "一环到二环", "六环以外", "四环至五环之间", "六环外(马驹桥镇)"); - for (String a : huanxian) { - formattedAddress = formattedAddress.replace(a, ""); - } - data.put("formatted_in_address", formattedAddress); - data.put("province", province); - if (formate.get("city") != null) { - data.put("formatedCity", formate.get("city")); - } else { - if (city.endsWith("市") || city.endsWith("县")) { - city = city.substring(0, city.length() - 1); - } else { - if (province.endsWith("市")) { - city = province.substring(0, province.length() - 1); - } else { - city = province; - } - } - data.put("formatedCity", city); - } - ret.add(data); - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (fileInputStream != null) { - try { - fileInputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - return ret; - } - - private JSONObject addTerm(String name, String value){ - JSONObject term = new JSONObject(); - JSONObject match = new JSONObject(); - match.put(name, value); - term.put("term", match); - return term; - } - - private JSONObject addMatchPhrase(String name, String value){ - JSONObject term = new JSONObject(); - JSONObject match = new JSONObject(); - match.put(name, value); - term.put("match_phrase", match); - return term; - } - - /*** - * 获取自然村 - * @param city - * @param region - * @param name - * @return - */ - private List findVillage(String city, String region, String name) { - JSONObject reqBody = new JSONObject(); - reqBody.put("from", 0); - reqBody.put("size", 5); - JSONObject query = new JSONObject(); - JSONObject bool = new JSONObject(); - JSONArray must = new JSONArray(); - must.add(addTerm("city", city)); - must.add(addTerm("region", region)); - must.add(addTerm("name", name)); - bool.put("must", must); - query.put("bool", bool); - reqBody.put("query", query); - Base64 token = new Base64(); - String authenticationEncoding = token.encodeAsString((""+ES_USER+":"+ES_PASSWORD+"").getBytes()); - HttpRequest request = new HttpRequest(); - Map headers = new HashMap(); - headers.put("Content-Type", "application/json"); - headers.put("Authorization", "Basic "+authenticationEncoding+""); - try { - String response = request.postWithBody("http://192.168.0.45:9200/village/_search", reqBody, headers, "UTF-8"); - JSONObject json = JSONObject.fromObject(response); - if(!json.containsKey("hits") || !json.getJSONObject("hits").containsKey("hits")){ - return Collections.emptyList(); - } - JSONArray hits = json.getJSONObject("hits").getJSONArray("hits"); - List results = new ArrayList(); - for(int i=0 ;i < hits.size(); i++){ - JSONObject jsonObject = hits.getJSONObject(i); - results.add(jsonObject); - } - return results; - - } catch (HttpRequestException e) { - e.printStackTrace(); - } - return Collections.emptyList(); - } - - /** - * 加载测试数据 - * - * @return - */ - private List> loadTestData() { - BufferedReader reader = null; - List> ret = new ArrayList>(); - try { - reader = new BufferedReader( - new InputStreamReader(new FileInputStream("D:\\data\\addr\\test20140923.txt"), "utf-8")); - boolean isFirst = true; - while (true) { - String line = reader.readLine(); - if (line == null) { - break; - } - if (isFirst) { - isFirst = false; - int c = line.charAt(0); - if (c == 65279) { - // 去掉UTF-8中头标示 - line = line.substring(1); - } - } - ret.add(parseTestData(line)); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - - } - } - } - return ret; - } - - /** - * 解析测试数据,其中输入字符串为以TAB分隔的字符串,例如: in_name:经济技术开发区贵园北里丁区 out_name:贵园北里 - * - * @param s - * @return - */ - private Map parseTestData(String s) { - Map ret = new HashMap(); - String[] columns = s.split("\t"); - for (String column : columns) { - int index = column.indexOf(":"); - String key; - String value; - if (index > 0) { - key = column.substring(0, index); - value = column.substring(index + 1); - ret.put(key, value); - } - } - return ret; - } - - @Authority(role = Role.USER) - public Object parseAddressAction(AddressModel model) throws Exception { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (model.getCity() == null || model.getAddress() == null) { - return mav; - } - District district = addressService.parseAddress(model.getCity(), model.getAddress()); - if (district != null) { - Map resMap = new HashMap(); - resMap.put("city", district.getCity()); - resMap.put("region", district.getRegion()); - resMap.put("districtName", district.getName()); - resMap.put("address", district.getAddress()); - mav.setModel(resMap); - } - return mav; - } - - @Authority(role = Role.USER) - public Object geocoderAction(AddressModel model) throws Exception { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - - if (model.getCity() == null || model.getAddress() == null) { - return mav; - } - - double[] lngLat = addressService.getLngLat(model.getCity(), model.getAddress(), AK); - Map resMap = new HashMap(); - resMap.put("lng", lngLat[0]); - resMap.put("lat", lngLat[1]); - mav.setModel(resMap); - return mav; - } - - @Authority(role = Role.USER) - public Object geocoderBaiduToGoogleAction(AddressModel model) throws Exception { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - - if (model.getCity() == null || model.getAddress() == null) { - return mav; - } - - double[] lngLat = addressService.getLngLat(model.getCity(), model.getAddress(), AK); - Map resMap = new HashMap(); - resMap.put("lng", lngLat[0]); - resMap.put("lat", lngLat[1]); - mav.setModel(resMap); - return mav; - } - - @Deprecated - @Authority(role = Role.USER) - public Object addressEvaluationAction(AddressModel model) throws Exception { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - - if (model.getCity() == null || model.getAddress() == null || model.getArea() == null) { - return mav; - } - - Map resMap = new HashMap(); - resMap.put("totalPrice", - addressService.evaluationByAddress(model.getCity(), model.getAddress(), model.getArea(), AK)); - mav.setModel(resMap); - return mav; - } - - @Deprecated - @Authority(role = Role.USER) - public Object addressEvaluation2Action(AddressModel model) throws Exception { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - - if (model.getCity() == null || model.getAddress() == null || model.getArea() == null) { - return mav; - } - - Date weekend = DateUtil.getThisSunday(new Date()); - if (model.getWeekend() != null) { - weekend = DateUtil.getThisSunday(model.getWeekend()); - } - - Map resMap = new HashMap(); - resMap.put("totalPrice", 0); - - District district = addressService.parseAddress(model.getCity(), model.getAddress()); - if (district == null) { - double[] lngLatBaidu = addressService.getLngLat(model.getCity(), model.getAddress(), AK); - if (lngLatBaidu == null) { - mav.setModel(resMap); - return mav; - } - double[] lngLatGoogle = addressService.geoconvBaiduToGoogle(lngLatBaidu[0], lngLatBaidu[1]); - double lng = lngLatGoogle[0]; - double lat = lngLatGoogle[1]; - List params = new ArrayList(); - SdQuery sdQuery = new SdQuery(); - if (lat < -90 && lat > 90 && lng < -180 && lng > 180) { - mav.setModel(resMap); - return mav; - } - params.add(new QueryParam("city", model.getCity())); - params.add(new QueryParam("visible", 0)); - sdQuery.setPoint(lat + "," + lng); - sdQuery.setField("lat_lng"); - sdQuery.setDistance("" + (500 / 1000d)); - params.add(new QueryParam(QueryParam.SD_PARAM_NAME, sdQuery)); - List districts = districtService.findAllByParams(params, 0, 3); - - int totalPrice = 0; - int tc = 0; - for (District dis : districts) { - Evaluation evaluation = new Evaluation(); - evaluation.setCity(dis.getCity()); - evaluation.setRegion(dis.getRegion()); - evaluation.setDistrictName(dis.getName()); - evaluation.setArea(model.getArea()); - evaluation.setSource("api_diZhiGuJia"); - evaluation = evaluationService.saveEvaluation(evaluation, weekend); - if (evaluation.getTotalPrice() != null && evaluation.getTotalPrice() > 0) { - totalPrice += evaluation.getTotalPrice(); - tc++; - } - } - if (tc > 0) { - resMap.put("totalPrice", totalPrice / tc); - } - // } - } else { - Evaluation evaluation = new Evaluation(); - evaluation.setCity(district.getCity()); - evaluation.setRegion(district.getRegion()); - evaluation.setDistrictName(district.getName()); - evaluation.setArea(model.getArea()); - evaluation.setSource("api_diZhiGuJia"); - evaluation = evaluationService.saveEvaluation(evaluation, weekend); - resMap.put("totalPrice", evaluation.getTotalPrice()); - - District dist = districtService.findDistrict( - new DistrictKey(district.getCity(), district.getRegion(), district.getName()), "district"); - if (null != dist) { - if (null != dist.getCarSiteCount() && dist.getCarSiteCount() > 0) { - resMap.put("carSiteCount", dist.getCarSiteCount()); - } - } - - CommData commData = commDataService.findCommDataByCity(district.getCity(), district.getRegion(), - district.getName(), "district"); - if (null != commData && commData.getLastCount() > 0) { - resMap.put("householdCount", commData.getLastCount()); - } - } - mav.setModel(resMap); - return mav; - } - - @Authority(role = Role.USER) - public Object addressStandardParserAction(AddressModel model) throws Exception { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - Map resMap = addressService.parseSelectAddressInfo(model.getCity(), model.getAddress()); - mav.setModel(resMap); - return mav; - } - - @Authority(role = Role.USER) - public Object addressStandardAction(AddressModel model) throws Exception { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - - model.setAddress(AddressParserUtils.filteSpecialChar(model.getAddress())); - Map resMap = addressService.parseSelectAddressInfo(model.getCity(), model.getAddress()); - resMap.put("oldAddress", model.getAddress()); - - if (resMap.get("city") == null || model.getAddress() == null) { - return mav; - } - - District district = null; - // 根据地址查找小区 - if (resMap.get("address") != null) { - district = addressService.parseAddress(resMap.get("city").toString(), resMap.get("address").toString()); - } - // 根据地址中提取出的小区名称查小区 - String oldName = resMap.get("oldName") != null ? resMap.get("oldName").toString() : null;// 地址中疑似小区 - if (district == null && null != oldName) { - district = addressService.parseAddress(resMap.get("city").toString(), oldName); - // 百度查小区 - if (district == null && null != oldName) { - Map ret = baiduApiService.mapSearchSimple(resMap.get("city").toString(), oldName, AK); - List rets = (List) ret.get("content"); - if (null != rets) { - boolean flag = false; - for (Map vo : rets) { - List> vs = (List>) vo.get("cla"); - if (vs == null) { - continue; - } - for (List list : vs) { - String s = list.get(1); - if (s.indexOf("小区") != -1 || s.indexOf("楼盘") != -1) { - flag = true; - resMap.put("name", oldName); - String baiduAddress = (String) vo.get("addr"); - if (StringUtils.isNotBlank(baiduAddress)) { - - if (StringUtils.isBlank((String) resMap.get("address"))) { - resMap.put("address", baiduAddress); - } - - } - - break; - } - } - } - - if (!flag && resMap.get("address") == null) { - resMap.put("address", oldName); - } - } - } - } - - if (district != null) { - District dist = districtService.findDistrict( - new DistrictKey(district.getCity(), district.getRegion(), district.getName()), "district"); - if (dist != null) { - district = dist; - } - resMap.put("status", "0"); - } else { - resMap.put("status", "1"); - } - - // 当businessMatch=1,并且进行小区匹配没有成功的情况下,进行商铺写字楼匹配 通过keyword查找 - if (null != model.getBusinessMatch() && model.getBusinessMatch() == 1 && resMap.get("status").equals("1") - && StringUtils.isNotBlank((String) resMap.get("city"))) { - if (StringUtils.isNotBlank(oldName)) { - district = districtService.findFirstByKeyword((String) resMap.get("city"), oldName); - } - - if (null == district && StringUtils.isNotBlank((String) resMap.get("address"))) { - district = districtService.findFirstByKeyword((String) resMap.get("city"), - (String) resMap.get("address")); - } - } - - if (district != null) { - - resMap.put("name", district.getName()); - resMap.put("region", district.getRegion()); - resMap.put("block", district.getBlock()); - resMap.put("cat", district.getCategory()); - resMap.put("alias", district.getAlias()); - - String tempAddress = (String) resMap.get("address"); - if (StringUtils.isBlank(tempAddress)) { - resMap.put("address", district.getAddress()); - } else { - if (tempAddress.indexOf("弄") == -1 && tempAddress.indexOf("号") == -1 || tempAddress.indexOf("街") == -1 - || tempAddress.indexOf("路") == -1) { - resMap.put("address", district.getAddress()); - } - } - } - - String lastAddress = (String) resMap.get("address"); - if (StringUtils.isNotBlank(lastAddress)) { - if (lastAddress.length() < 2) { - resMap.put("address", null); - } else { - resMap.put("address", AddressParserUtils.filteSpecialChar(resMap.get("address").toString())); - } - - } - resMap.remove("louDong"); - mav.setModel(resMap); - return mav; - } - - public Object address2DistrictAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - - String orgCity = model.getCity(); - String orgAddress = AddressParserUtils.filteSpecialChar(model.getAddress()); - if (StringUtils.isBlank(orgCity) || StringUtils.isBlank(orgAddress)) { - return mav; - } - - Map resMap = addressService.parseSelectAddressInfo(orgCity, orgAddress); - resMap.put("oldAddress", orgAddress); - resMap.remove("louDong"); - - if (null == resMap.get("city")) { - return mav; - } - - String city = (String) resMap.get("city"); - District district = null; - // 小区库匹配 - String address = (String) resMap.get("address"); - if (StringUtils.isNotBlank(address)) { - // 地址、小区名、别名匹配 - List params = new ArrayList(4); - params.add(new QueryParam("city", city)); - params.add(new QueryParam("category", "district")); - params.add(new QueryParam("visible", 0)); - - TermQuery q1 = new TermQuery(new Term("name", address)); - TermQuery q2 = new TermQuery(new Term("alias", address)); - TermQuery q3 = new TermQuery(new Term("address", address)); - BooleanQuery bq = new BooleanQuery(); - bq.add(q1, Occur.SHOULD); - bq.add(q2, Occur.SHOULD); - bq.add(q3, Occur.SHOULD); - params.add(new QueryParam(QueryParam.SR_PARAM_NAME, new SrQuery(bq))); - - List ds = districtService.findAllByParams(params, 0, 1); - if (CollectionUtils.isNotEmpty(ds)) { - district = ds.get(0); - } - } - - // 根据地址中提取出的小区名称查小区 - String oldName = StringUtils.trim((String) resMap.get("oldName")); - if (null == district && StringUtils.isNotBlank(oldName)) { - // 小区名、别名匹配 - List params = new ArrayList(4); - params.add(new QueryParam("city", city)); - params.add(new QueryParam("category", "district")); - params.add(new QueryParam("visible", 0)); - - TermQuery q1 = new TermQuery(new Term("name", oldName)); - TermQuery q2 = new TermQuery(new Term("alias", oldName)); - BooleanQuery bq = new BooleanQuery(); - bq.add(q1, Occur.SHOULD); - bq.add(q2, Occur.SHOULD); - params.add(new QueryParam(QueryParam.SR_PARAM_NAME, new SrQuery(bq))); - - List ds = districtService.findAllByParams(params, 0, 1); - if (CollectionUtils.isNotEmpty(ds)) { - district = ds.get(0); - } - } - - // 地址库匹配 - if (null == district) { - // todo - } - - if (null == district) { - resMap.put("status", 1); - } else { - resMap.put("status", 0); - resMap.put("name", district.getName()); - resMap.put("region", district.getRegion()); - resMap.put("block", district.getBlock()); - resMap.put("cat", district.getCategory()); - resMap.put("alias", district.getAlias()); - - String tempAddress = (String) resMap.get("address"); - if (StringUtils.isBlank(tempAddress)) { - resMap.put("address", district.getAddress()); - } else { - if (tempAddress.indexOf("弄") == -1 && tempAddress.indexOf("号") == -1 || tempAddress.indexOf("街") == -1 - || tempAddress.indexOf("路") == -1) { - resMap.put("address", district.getAddress()); - } - } - } - - String lastAddress = (String) resMap.get("address"); - if (StringUtils.isNotBlank(lastAddress)) { - if (lastAddress.length() < 2) { - resMap.put("address", null); - } else { - resMap.put("address", AddressParserUtils.filteSpecialChar(resMap.get("address").toString())); - } - } - - mav.setModel(resMap); - return mav; - } - - private String findStandardRegion(String city, String region) { - - List regionBloks = regionBlockService.getRegionBlockListByCity(city, null); - String s_region = ""; - if (regionBloks.size() > 0) { - for (RegionBlock regionBlock : regionBloks) { - List patterns = regionBlock.getPattern(); - if (null != patterns && patterns.contains(region)) { - s_region = regionBlock.getName(); - break; - } else { - if (regionBlock.getName().indexOf(region) != -1) { - s_region = region; - break; - } - } - } - } else { - s_region = region; - } - return s_region; - } - - /** - * 地址联想提示 (高德官方) /address/su 参数:address city - * 返回:[{"id":"XXXXXXXXX","city":"上海",region:"长宁","name":"xxx","address":"协和路"}] - * - * @return - */ - public Object suAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - try { - List list = addressService.suAmap(model.getCity().trim(), model.getAddress().trim());// su()是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(list); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } - - /** - * 地址真实性检查 (高德官方) /address/check 参数:chooseId address city - * 返回:{type:"存在|不存在|存疑",data:{"id":"XXXXXXXXX","city":"上海",region:"长宁","name":"xxx","address":"协和路"}} - * 存疑的时候才有data返回,返回高德搜索的第一条数据 (超过的时候,找到最大号码返回) - * - * @return - */ - public Object checkAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } - try { - AddressCheckBo bo = addressService.checkAmap(model.getChooseId(), city, model.getAddress().trim());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatAddressCheckBo(bo, city, model)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } - - /** - * 为返回值格式化掉cityCode和AddressId,用于评级和反欺诈 - * - * @param bo - * @return - */ - private AddressCheckBo formatAddressCheckBo2(AddressCheckBo bo, String city, AddressModel model) { - AddressCheck check = bo.getData(); - if (null != check) { - check.setCityCode(null); - if (StringUtils.isEmpty(check.getCity()) || "[]".equals(check.getCity())) { - check.setCity(city); - } - // if (StringUtils.isEmpty(check.getAddress()) || - // "[]".equals(check.getAddress())) { - // check.setAddress(check.getName()); - // } - // 检查相关参数 - if (FJW_LEVEL.equals(model.getDataLevel())) { - bo.setData(check); - } else { - check.setDistrictName(null); - check.setKeyWords(null); - check.setKeyWordsUse(null); - check.setRegion(null); - check.setProvionce(null); - check.setNameUse(null); - check.setAddressUse(null); - check.setAddress2(null); - check.setName2(null); - check.setType(null); - check.setFormatAddress(null); - check.setFormatAddress2(null); - check.setLocation2(null); - check.setLevel(null); - check.setScoreIncity(null); - check.setScoreInnation(null); - check.setPriceScore(null); - check.setAreaScore(null); - check.setEstateScore(null); - bo.setData(check); - } - } - if ("不存在".equals(bo.getType())) { - bo.setType("地址未找到:抱歉,在" + city + "没有找到与'" + model.getAddress() + "'相关的地点"); - } - return bo; - } - - /** - * 查询高德城市及城市编码 - * - * @return - */ - public Object cityAllAction() { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - List list = addressService.findAllCityAmap(); - BasicModel model = new BasicModel(HttpStatusCodeEnum.OK); - model.setResult(list); - mav.setModel(model); - return mav; - } - - /** - * 地址联想提示 (代理) - * - * @return - */ - public Object suAmapAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - try { - List list = addressService.su(model.getCity().trim(), model.getAddress().trim()); - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(list); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } - - /** - * 地址真实性检查 (代理) - * - * @return - */ - public Object checkAmapAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } - try { - AddressCheckBo bo = addressService.check(model.getChooseId(), city, model.getAddress().trim()); - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatAddressCheckBo(bo, city, model)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } - - /** - * 地址评级 - * - * @param model - * (city+address)+addressId - * @return { "code": 200, "msg": "ok", "result": { "data": { "address": "匹配地址", - * "city": "城市", "keyWords": "用户输入", "keyWordsUse": "用户输入格式化", "lat": - * 经纬度, "lng": 经纬度, "name": "匹配POIName", "score": 评分 }, "type": "可能存在" } - * } - */ - public Object gradeAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } - - try { - AddressCheckBo bo = addressService.gradeAmap(model.getChooseId(), city, model.getAddress().trim());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatAddressCheckBo2(bo, city, model)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } - - /** - * 地址反欺诈 (地址验真+周边查询) - * - * @param model - * (city+address)+addressId - * @return { "code": 200, "msg": "ok", "result": { "data": { "address": "匹配地址", - * "city": "城市", "keyWords": "用户输入", "keyWordsUse": "用户输入格式化", "lat": - * 纬度, "lng": 经度, "name": "匹配POIName", "poiList":[ { "name" : - * "文洋大厦停车场(协和路)", "type" : "类型", "address" : "协和路1033号", "lat": 纬度, - * "lng": 经度, "distance":距离 },... ] }, "type": "存在" } } - */ - public Object antiFraudAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } - - try { - AddressCheckBo bo = addressService.antiFraudAmap(model.getChooseId(), city, model.getAddress().trim(), - model.getType(), model.getRadius(), model.getNumber(), model.getPageNo());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatAddressCheckBo2(bo, city, model)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } - - /** - * 地址反欺诈 (地址验真+周边查询) - * - * @param model - * (city+address)+addressId - * @return { "code": 200, "msg": "ok", "result": { "data": { "address": - * "德州路220弄小区", "addressId": "d525e60aab2e84909d2fd998b0af5e8e", "city": - * "上海市", "keyWords": "德州路220弄", "keyWordsUse": "德州路220弄", "lat": - * 31.167814, "lng": 121.495784, "name": "上海后来居上家庭公寓(德州路分店)", "poiMap": - * { "加油站": [ { "address": "杨思路648号", "distance": "642.0m", "lat": - * 31.162078, "lng": 121.496522, "name": "中国石化加油站(杨思路)", "type": "加油站" - * }, { "address": "杨思路2号", "distance": "1.6km", "lat": 31.15627, "lng": - * 121.485031, "name": "中国石油杨思加油站(杨思路)", "type": "加油站" }, ... ] } ... }, - * "type": "存在" } } - */ - public Object antiFraudBAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } - - try { - AddressCheckBo bo = addressService.antiFraudAmapB(model.getChooseId(), city, model.getAddress().trim(), - model.getType(), model.getRadius(), model.getNumber());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatAddressCheckBo2(bo, city, model)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } - - public Object standardAction(AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - String result = addressMatchProxyService.standard(convertModelToMap(model)); - if (result != null) { - JSONObject json = JSONObject.fromObject(result); - int code = json.getInt("code"); - String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); - if(json.containsKey("result")){ - basicModel.setResult(json.get("result")); - } - mav.setModel(basicModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - /** - * 地址标准化接口V2 - * - * @param model - * @return - */ - public Object standard2Action(AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - - HttpRequest request = new HttpRequest(); - JSONObject json = null; - Map params = new HashMap(); - params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); - params.put("address", model.getAddress()); - params.put("showCode", model.getShowCode()); - try{ - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/structure", params, "UTF-8"); - } catch(Exception e){ - try { - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/structure", params, "UTF-8"); - } catch(Exception ex){ - ex.printStackTrace(); - } - } - - if (json != null) { - int code = json.getInt("status"); - String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); - if(json.containsKey("result")){ - basicModel.setResult(json.get("result")); - } - mav.setModel(basicModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - /** - * 招商证券POC测试接口封装 - */ - public Object cmbTestAction(AddesssMatchModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - HttpRequest request = new HttpRequest(); - JSONObject json = null; - Map params = new HashMap(); - params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); - params.put("address", model.getAddress()); - try{ - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/cmbTest", params, "UTF-8"); - } catch(Exception e){ - try { - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/cmbTest", params, "UTF-8"); - } catch(Exception ex){ - ex.printStackTrace(); - } - } - - if (json != null) { - int code = json.getInt("status"); - String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); - if(json.containsKey("result")){ - basicModel.setResult(json.get("result")); - } - mav.setModel(basicModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - /** - * 五级地址标准化接口 - * - * @param model - * @return - */ - public Object fiveDivisionStructureAction(AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - - HttpRequest request = new HttpRequest(); - JSONObject json = null; - Map params = new HashMap(); - params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); - params.put("address", model.getAddress()); - // 地址验证无效也输出标准化结果 - params.put("flag", "true"); - try{ - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/fiveDivisionStructure", params, "UTF-8"); - } catch(Exception e){ - try { - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/fiveDivisionStructure", params, "UTF-8"); - } catch(Exception ex){ - ex.printStackTrace(); - } - } - - if (json != null) { - int code = json.getInt("status"); - String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); - if(json.containsKey("result")){ - basicModel.setResult(json.get("result")); - } - mav.setModel(basicModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - /** - * 五级行政区划V2地址标准化接口 - * - * @param model - * @return - */ - public Object fiveDivisionStructure2Action(AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - - HttpRequest request = new HttpRequest(); - JSONObject json = null; - Map params = new HashMap(); - params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); - params.put("address", model.getAddress()); - // 地址验证无效也输出标准化结果 - params.put("flag", "true"); - try{ - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/fiveDivisionStructure/v2", params, "UTF-8"); - } catch(Exception e){ - try { - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/fiveDivisionStructure/v2", params, "UTF-8"); - } catch(Exception ex){ - ex.printStackTrace(); - } - } - - if (json != null) { - int code = json.getInt("status"); - String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); - if(json.containsKey("result")){ - basicModel.setResult(json.get("result")); - } - mav.setModel(basicModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - /** - * 详细地址标准化接口 - * - * @param model - * @return - */ - public Object divisionStructureAction(AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - - HttpRequest request = new HttpRequest(); - JSONObject json = null; - Map params = new HashMap(); - params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); - params.put("address", model.getAddress()); - // 地址验证无效也输出标准化结果 - params.put("flag", "true"); - try{ - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/divisionStructure", params, "UTF-8"); - } catch(Exception e){ - try { - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/divisionStructure", params, "UTF-8"); - } catch(Exception ex){ - ex.printStackTrace(); - } - } - - if (json != null) { - int code = json.getInt("status"); - String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); - if(json.containsKey("result")){ - basicModel.setResult(json.get("result")); - } - mav.setModel(basicModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - /** - * 地址标准化专用测试接口 - * @param model - * @return - */ - public Object structureAndCompleteAction(AddesssMatchModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - - HttpRequest request = new HttpRequest(); - JSONObject json = null; - Map params = new HashMap(); - params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); - params.put("address", model.getAddress()); - // 地址验证无效也输出标准化结果 - params.put("flag", "true"); - try{ - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/structureAndComplete", params, "UTF-8"); - } catch(Exception e){ - try { - json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/structureAndComplete", params, "UTF-8"); - } catch(Exception ex){ - ex.printStackTrace(); - } - } - - if (json != null) { - int code = json.getInt("status"); - String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); - if(json.containsKey("result")){ - basicModel.setResult(json.get("result")); - } - mav.setModel(basicModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - /** - * 地址信息分类接口 - * @param model - * @return - */ - public Object communitySummaryAction(CommunitySummaryRequestDto model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - - HttpRequest request = new HttpRequest(); - JSONObject json = null; - try{ - Map headers = new HashMap(); - headers.put("Content-Type", "application/json"); - - JSONObject reqBody = new JSONObject(); - reqBody.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); - reqBody.put("address", model.getAddress()); - reqBody.put("area", model.getArea()); - reqBody.put("maxFloor", model.getMaxFloor()); - reqBody.put("housePurpose", model.getHousePurpose()); - reqBody.put("memo", model.getMemo()); - - String result = request.postWithBody("http://192.168.0.100:32080/FangJiaAddressService/communitySummary", reqBody ,headers, "UTF-8"); - if(result != null){ - try{ - json = JSONObject.fromObject(result); - } catch(Exception e){ - json = null; - } - } - } catch(Exception e){ - e.printStackTrace(); - } - - if (json != null) { - int code = json.getInt("status"); - String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); - if(json.containsKey("result")){ - basicModel.setResult(json.get("result")); - } - mav.setModel(basicModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - /** - * 楼盘评级 - * @param model - * @return - */ - public Object buildingRatingAction(CommunitySummaryRequestDto model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - - HttpRequest request = new HttpRequest(); - JSONObject json = null; - try{ - Map headers = new HashMap(); - headers.put("Content-Type", "application/json"); - - JSONObject reqBody = new JSONObject(); - reqBody.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); - reqBody.put("address", model.getAddress()); - reqBody.put("area", model.getArea()); - reqBody.put("maxFloor", model.getMaxFloor()); - reqBody.put("housePurpose", model.getHousePurpose()); - reqBody.put("memo", model.getMemo()); - String result = request.postWithBody("http://192.168.0.100:32080/FangJiaAddressService/buildingRating", reqBody, headers, "UTF-8"); - if(result != null){ - try{ - json = JSONObject.fromObject(result); - } catch(Exception e){ - json = null; - } - } - } catch(Exception e){ - e.printStackTrace(); - } - - if (json != null) { - int code = json.getInt("status"); - String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); - if(json.containsKey("result")){ - basicModel.setResult(json.get("result")); - } - mav.setModel(basicModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - /** - * 财力评级 - * @param model - * @return - */ - public Object financialRatingAction(CommunitySummaryRequestDto model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } - - HttpRequest request = new HttpRequest(); - JSONObject json = null; - try{ - Map headers = new HashMap(); - headers.put("Content-Type", "application/json"); - - JSONObject reqBody = new JSONObject(); - reqBody.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); - reqBody.put("address", model.getAddress()); - reqBody.put("area", model.getArea()); - reqBody.put("maxFloor", model.getMaxFloor()); - reqBody.put("housePurpose", model.getHousePurpose()); - reqBody.put("memo", model.getMemo()); - String result = request.postWithBody("http://192.168.0.100:32080/FangJiaAddressService/financialRating", reqBody, headers,"UTF-8"); - if(result != null){ - try{ - json = JSONObject.fromObject(result); - } catch(Exception e){ - json = null; - } - } - } catch(Exception e){ - e.printStackTrace(); - } - - if (json != null) { - int code = json.getInt("status"); - String msg = json.getString("msg"); - BasicModel basicModel = new BasicModel(code, msg); - if(json.containsKey("result")){ - basicModel.setResult(json.get("result")); - } - mav.setModel(basicModel); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - public Object similarityAction(AddesssMatchModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getAddress_1()) || StringUtils.isBlank(model.getAddress_2())) { - mav.setModel(BasicModel.buildBadRequestModel("两个地址均不能为空")); - return mav; - } - model.setAddress(model.getAddress_1()); - String result1 = addressMatchProxyService.standard(convertModelToMap(model)); - model.setAddress(model.getAddress_2()); - String result2 = addressMatchProxyService.standard(convertModelToMap(model)); - if (result1 != null && result2 != null) { - Map resultMap = addressService.addressSimilarity(result1, result2); - mav.setModel(BasicModel.buildOKModel().setResult(resultMap)); - } else { - mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); - } - return mav; - } - - public Object parseCityAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - if (StringUtils.isBlank(model.getProvince())) { - mav.setModel(BasicModel.buildBadRequestModel("province不能为空")); - return mav; - } - if (StringUtils.isBlank(model.getDistrict())) { - mav.setModel(BasicModel.buildBadRequestModel("district不能为空")); - return mav; - } - CityParseBo bo = addressService.cityParse(model.getProvince(), model.getDistrict()); - if (bo.getCity() != null) { - UniversalDto dto = UniversalDto.newDto(); - dto.append("city", bo.getCity()); - mav.setModel(BasicModel.buildOKModel().setResult(dto)); - } else { - mav.setModel(BasicModel.buildModel(40001, bo.getMsg())); - } - return mav; - } - - public Object realStandardAction(AddressModel model) { - - RestfulModelAndView mav = new RestfulModelAndView(); - if (!OpenConfig.getConfig().addressMatchEnabled()) { - mav.setModel(BasicModel.buildBadRequestModel("不支持该服务")); - return mav; - } - if (StringUtils.isBlank(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); - return mav; - } + private AddressService addressService; + private DistrictService districtService; + private EvaluationService evaluationService; + private CommDataService commDataService; + private RegionBlockService regionBlockService; + private BaiduApiService baiduApiService; + private AddressParser addressParser; + private ServerAreaService serverAreaService; + private AddressParserService addressParserService; + private WaitCrawlKeywordsService waitCrawlKeywordsService; + private HouseLoudongService houseLoudongService; + private FjtEvaluationService fjtEvaluationService; + private AddressMatchProxyService addressMatchProxyService; + + private final static String AK = OpenConfig.getConfig().getBaiduAk(); + private final static Logger LOGGER = LoggerFactory.getLogger(AddressController.class); + + private static Map> districts_cache = new HashMap>(); + + private static final String FJW_LEVEL = "5CAE1FAC646CB2D8"; + private static final String GRADE_AREA = "区域评分"; + private static final String GRADE_CITY = "城市评分"; + private static final String GRADE_NATION = "全国评分"; + private static final String GRADE_CONSUME = "消费评分"; + + public final static OpenConfig CONFIG = OpenConfig.getConfig(); + private static final String ES_USER = "developer"; + private static final String ES_PASSWORD = "5e8edd851d2fdfbd7415232c67367cc3"; + + /** + * @param model + * @return + * @deprecated see parse2Action + */ + @Authority(role = Role.USER) + public Object parseAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setModel(addressParser.parse(model.getCity(), model.getAddress(), model.getTarget(), model.isNearby())); + return mav; + } + + @Authority(role = Role.USER) + public Object parse2Action(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + if (ServerAreaData.getServerAreaByCity(model.getCity()) == null) { + HashMap resMap = new HashMap(); + resMap.put("status", 0); + resMap.put("precise", -1); + resMap.put("searchKey", model.getAddress()); + mav.setModel(resMap); + return mav; + } + mav.setModel(addressParser.parse2(model.getCity(), model.getAddress(), model.getTarget(), model.isNearby())); + return mav; + } + + /** + * 解析地址,能够返回多个结果 参数有:city 城市 address 地址 includeMaps + * 匹配的结果是否包含来自地图的数据,true表示结果包含来自地图的数据 max 返回的结果集中最多条数 + * + * @param model + * @return + */ + @Authority(role = Role.USER) + public Object parseAsListAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setModel( + addressParser.parseAsList(model.getCity(), model.getAddress(), model.isIncludeMaps(), model.getMax())); + return mav; + } + + @Authority(role = Role.USER) + public Object cacheFlushAction(AddesssMatchModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + String result = addressMatchProxyService.cacheFlush(convertModelToMap(model)); + mav.setModel(result); + return mav; + } + + @Authority(role = Role.USER) + public Object analyzeAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getCity())) { + mav.setModel(BasicModel.buildBadRequestModel("城市不能为空")); + return mav; + } + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + HttpRequest request = new HttpRequest(); + Map params = new HashMap(); + params.put("address", model.getAddress()); + params.put("city", model.getCity()); + try { + JSONObject result = request.getJsonContent("http://192.168.0.19:38080/FangJiaHelper/address/analyze/api", params, "UTF-8"); + mav.setModel(BasicModel.buildOKModel().setResult(result)); + } catch (HttpRequestException e) { + e.printStackTrace(); + } + return mav; + } + + public Object rateAction(@Valid RateModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + JSONArray dataList; + try { + dataList = JSONArray.fromObject(model.getData()); + } catch (Exception e) { + mav.setModel(BasicModel.buildBadRequestModel("数据格式错误")); + return mav; + } + List metaDatas = new ArrayList(dataList.size()); + JSONObject item; + AddressMatchMetaData metaData; + Map idMap = new HashMap(dataList.size()); + for (int i = 0; i < dataList.size(); i++) { + item = dataList.getJSONObject(i); + metaData = new AddressMatchMetaData(); + if (item.containsKey("city")) { + metaData.setCity(item.getString("city")); + } else { + metaData.setCity(model.getCity()); + } + if (item.containsKey("district")) { + metaData.setDistrict(item.getString("district")); + } + metaData.setMainName(item.getString("name")); + metaData.addName(item.getString("name"), MatchText.MAIN_NAME_PRIORITY); + if (item.containsKey("address")) { + Map addrWeightMap = analyseAddress(model.getCity(), item.getString("address")); + for (String addr : addrWeightMap.keySet()) { + metaData.addAddress(addr, addrWeightMap.get(addr)); + } + } + if (item.containsKey("uid")) { + metaData.setId(item.getString("uid")); + idMap.put(metaData.getId(), item); + } + if (item.containsKey("lng")) { + metaData.setLng(item.getDouble("lng")); + } + if (item.containsKey("lat")) { + metaData.setLat(item.getDouble("lat")); + } + metaData.setBuildingType(BuildingType.DISTRICT); + metaDatas.add(metaData); + } + AddressRate addressRate = addressParserService.rate(model.getCity(), model.getAddress(), metaDatas); + List results = new ArrayList(metaDatas.size()); + for (AddressMatchMetaData meta : addressRate.getMetaData()) { + JSONObject result = idMap.get(meta.getId()); + results.add(result); + } + mav.setModel(BasicModel.buildOKModel().setResult(results)); + return mav; + } + + private Map analyseAddress(String city, String address) { + + if (StringUtils.isBlank(address)) { + return Collections.EMPTY_MAP; + } + try { + Address addr = addressParserService.standardize(city, address); + if (!addr.isAvailable()) { + return Collections.EMPTY_MAP; + } + Map addrWeightMap = new HashMap(); + + if (StringUtils.isNotBlank(addr.getStreet())) { + String street = addr.getStreet(); + List streets = new ArrayList(); + streets.add(street); + if (street.endsWith("弄")) { + addrWeightMap.put(street, MatchText.MAIN_ADDR_PRIORITY); + addrWeightMap.put(street.replaceAll("弄$", "号"), MatchText.GEN_ADDR_PRIORITY); + streets.add(street.replaceAll("弄$", "号")); + } + if (StringUtils.isNotBlank(addr.getStreetNumber())) { + for (String s : streets) { + if (addr.getStreetNumber().endsWith("号")) { + addrWeightMap.put(s + addr.getStreetNumber().replaceAll("号$", "弄"), + MatchText.GEN_ADDR_PRIORITY); + } else if (street.endsWith("弄")) { + addrWeightMap.put(s + addr.getStreetNumber().replaceAll("弄$", "号"), + MatchText.GEN_ADDR_PRIORITY); + } + } + } + + if (CollectionUtils.isNotEmpty(addr.getStreetNumbers())) { + addrWeightMap.put(street + addr.getStreetNumber(), MatchText.MAIN_ADDR_PRIORITY); + for (String s : streets) { + for (String streetNumber : addr.getStreetNumbers()) { + if (streetNumber.endsWith("号")) { + addrWeightMap.put(s + streetNumber.replaceAll("号$", "弄"), MatchText.GEN_ADDR_PRIORITY); + } else if (street.endsWith("弄")) { + addrWeightMap.put(s + streetNumber.replaceAll("弄$", "号"), MatchText.GEN_ADDR_PRIORITY); + } + } + } + } + + } else { + addrWeightMap.put(addr.getMiniAddress(), MatchText.MAIN_ADDR_PRIORITY); + } + return addrWeightMap; + } catch (Exception e) { + + } + return Collections.EMPTY_MAP; + + } + + public Object standardizeAction(AddressModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + Address address = addressParserService.standardize(model.getCity(), model.getAddress()); + mav.setModel(BasicModel.buildOKModel().setResult(address)); + return mav; + } + + public Object realCertificateAction(AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (!OpenConfig.getConfig().addressMatchEnabled()) { + mav.setModel(BasicModel.buildBadRequestModel("不支持该服务")); + return mav; + } + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + MatchParams matchParams = new MatchParams(); + matchParams.setCity(model.getCity()); + matchParams.setAddress(model.getAddress()); + matchParams.setAddressParserGoal(AddressParserGoal.Certificate); + matchParams.setPreciseLevel(PreciseLevel.STRICT); + Building building = addressParserService.certificate(matchParams); + Address address = building.getSearchAddress(); + UniversalDto dto = UniversalDto.newDto(); + dto.append("province", address.getProvince()); + dto.append("city", address.getCity()); + if (address.getDistrict() != null) { + dto.append("district", address.getDistrict()); + } else { + dto.append("district", building.getDistrict()); + } + dto.append("developmentZone", address.getDevelopmentZone()); + dto.append("township", address.getTownship()); + dto.append("street", address.getStreet()); + dto.append("streetNumber", address.getStreetNumber()); + dto.append("name", building.getSuggestName()); + dto.append("buildingNumber", address.getBuildingNumber()); + dto.append("unitNumber", address.getUnitNumber()); + dto.append("roomNumber", address.getRoomNumber()); + dto.append("formattedAddress", address.getFormattedAddress()); + dto.append("certified", address.getCertified()); + dto.append("floor", address.getFloor()); + mav.setModel(BasicModel.buildOKModel().setResult(dto)); + return mav; + } + + public Object certificateAction(AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + String result = addressMatchProxyService.certificate(convertModelToMap(model)); + if (result != null) { + mav.setModel(result); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + public Object authAction(AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + String result = addressMatchProxyService.auth(convertModelToMap(model)); + if (result != null) { + mav.setModel(result); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + public Object realAuthAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + if (!OpenConfig.getConfig().addressMatchEnabled()) { + mav.setModel(BasicModel.buildBadRequestModel("不支持该服务")); + return mav; + } + MatchParams matchParams = new MatchParams(); + matchParams.setCity(model.getCity()); + matchParams.setAddress(model.getAddress()); + matchParams.setAddressParserGoal(AddressParserGoal.Certificate); + matchParams.setUseMap(true); + Building building = addressParserService.certificate(matchParams); + Address address = building.getSearchAddress(); + UniversalDto dto = UniversalDto.newDto(); + dto.append("province", address.getProvince()); + dto.append("city", address.getCity()); + dto.append("district", address.getDistrict()); + dto.append("developmentZone", address.getDevelopmentZone()); + dto.append("township", address.getTownship()); + dto.append("street", address.getStreet()); + dto.append("streetNumber", address.getStreetNumber()); + dto.append("buildingNumber", address.getBuildingNumber()); + dto.append("unitNumber", address.getUnitNumber()); + dto.append("roomNumber", address.getRoomNumber()); + dto.append("formattedAddress", address.getFormattedAddress()); + List certified = address.getCertified(); + if (certified.contains("roomNumber")) { + dto.append("authLevel", "A"); + } else if (certified.contains("buildingNumber")) { + dto.append("authLevel", "B"); + } else { + dto.append("authLevel", "C"); + } + mav.setModel(BasicModel.buildOKModel().setResult(dto)); + return mav; + } + + public Map analyseAddress(String address) { + Map ret = new HashMap(); + ret.put("address", address); + if (districts_cache.isEmpty()) { + List serverAreas = serverAreaService.findAll(); + for (ServerArea serverArea : serverAreas) { + if (StringUtils.isBlank(serverArea.getProvince())) { + continue; + } + String city = serverArea.getDisplay(); + String province = serverArea.getProvince(); + List cities = districts_cache.get(province); + if (cities == null) { + cities = new ArrayList(); + districts_cache.put(province, cities); + } + if (!cities.contains(city)) { + cities.add(city); + } + } + } + + for (Entry> p : districts_cache.entrySet()) { + if (address.startsWith(p.getKey())) { + ret.put("province", p.getKey()); + List cities = p.getValue(); + if (cities.size() == 1 && cities.contains(p.getKey())) {// 直辖市 + ret.put("city", p.getKey()); + } else { + String temp = address.substring(p.getKey().length());// 移除省份 + if (temp.startsWith("省") || temp.startsWith("市") || temp.startsWith("县") || temp.startsWith("区")) { + temp = temp.substring(1); + } + for (String c : cities) { + if (temp.startsWith(c)) { + ret.put("city", c); + break; + } + } + } + break; + } + } + return ret; + } + + @Authority(role = Role.USER) + public Object matchAction(AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + String result = addressMatchProxyService.parser(convertModelToMap(model)); + if (result != null) { + JSONObject json = JSONObject.fromObject(result); + BasicModel resultModel = new BasicModel(json.getInt("code"), json.getString("msg")); + resultModel.setResult(json.get("result")); + mav.setModel(resultModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + /** + * 地址匹配第二个版本,基于第一个版本的逻辑,对匹配出的结果进行正确性的判断 + * + * @param model + * @return + * @author yinjihuan + */ + @Authority(role = Role.USER) + public Object matchV2Action(AddesssMatchModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + String result = addressMatchProxyService.parser(convertModelToMap(model)); + JSONObject json = JSONObject.fromObject(result); + BasicModel resultModel = new BasicModel(json.getInt("code"), json.getString("msg")); + if (result != null) { + JSONObject jsonResult = (JSONObject) json.get("result"); + if (jsonResult != null && jsonResult.getDouble("credit") > 0) { + CheckMatchDistrictCorrectParam param = new CheckMatchDistrictCorrectParam(); + String city = jsonResult.getString("city"); + String region = jsonResult.getString("district"); + String name = jsonResult.getString("name"); + param.setCity(city); + param.setRegion(region); + param.setName(name); + param.setInputAddress(model.getAddress()); + if (jsonResult.containsKey("lng")) { + param.setBlng(jsonResult.getDouble("lng")); + } + if (jsonResult.containsKey("lat")) { + param.setBlat(jsonResult.getDouble("lat")); + } + param.setDebug(model.isDebug()); + District district = districtService.findDistrict(new DistrictKey(city, region, name), "district"); + if (district != null && district.getLng() != null && district.getLng() > 0) { + param.setGlng(district.getLng() / 10000000000.0); + param.setGlat(district.getLat() / 10000000000.0); + } + MatchDistrictResult matchResult = addressMatchProxyService.checkMatchDistrictCorrect(param); + jsonResult.put("matchResult", matchResult); + if (jsonResult.containsKey("category")) { + if ("office".equals(jsonResult.getString("category"))) { + jsonResult.put("propertyType", "写字楼"); + } else if ("shop".equals(jsonResult.getString("category"))) { + jsonResult.put("propertyType", "商铺"); + } + } + } else if (jsonResult != null) { + // 判断是否为自然村 + boolean matchedVillage = false; + try { + if (jsonResult.get("searchAddress") != null) { + JSONObject searchAddress = (JSONObject) jsonResult.get("searchAddress"); + String city = searchAddress.containsKey("city") ? searchAddress.getString("city") : null; + String region = searchAddress.containsKey("district") ? searchAddress.getString("district") : null; + String name = searchAddress.containsKey("keywords") ? searchAddress.getString("keywords") : null; + String township = searchAddress.containsKey("township") ? searchAddress.getString("township") : null; + if (StringUtils.isNotBlank(city) && StringUtils.isNotBlank(region) && StringUtils.isNotBlank(name)) { + List villages = findVillage(city, region, name); + if (CollectionUtils.isNotEmpty(villages)) { + if (villages.size() == 1 || StringUtils.isBlank(township)) { + JSONObject village = villages.get(0).getJSONObject("_source"); + jsonResult.put("id", villages.get(0).getString("_id")); + jsonResult.put("province", village.getString("province")); + jsonResult.put("city", village.getString("city")); + jsonResult.put("district", village.getString("region")); + jsonResult.put("township", village.getString("township")); + jsonResult.put("name", village.getString("name")); + jsonResult.put("lng", village.getJSONObject("location").getDouble("lon")); + jsonResult.put("lat", village.getJSONObject("location").getDouble("lat")); + jsonResult.put("propertyType", "自然村"); + matchedVillage = true; + } else { + for (JSONObject source : villages) { + JSONObject village = source.getJSONObject("_source"); + if (village.getString("township").contains(township) || township.contains(village.getString("township"))) { + jsonResult.put("id", source.getString("_id")); + jsonResult.put("province", village.getString("province")); + jsonResult.put("city", village.getString("city")); + jsonResult.put("district", village.getString("region")); + jsonResult.put("township", village.getString("township")); + jsonResult.put("name", village.getString("name")); + jsonResult.put("lng", village.getJSONObject("location").getDouble("lon")); + jsonResult.put("lat", village.getJSONObject("location").getDouble("lat")); + jsonResult.put("propertyType", "自然村"); + matchedVillage = true; + break; + } + } + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + if (matchedVillage == false) { + jsonResult.put("matchResult", new MatchDistrictResult()); + } + } + resultModel.setResult(json.get("result")); + mav.setModel(resultModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + public Object realMatchAction(@Valid AddesssMatchModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (!OpenConfig.getConfig().addressMatchEnabled()) { + mav.setModel(BasicModel.buildBadRequestModel("不支持该服务")); + return mav; + } + String address = model.getAddress(); + address = address.replaceAll("@@", "#");// 框架无法处理参数带有#的Buge 用@@代替 + BuildingType buildingType = null; + if (StringUtils.isNotBlank(model.getCategory())) { + if ("property".equals(model.getCategory())) { + model.setCategory("district"); + } + try { + buildingType = BuildingType.valueOf(model.getCategory().toUpperCase()); + } catch (Exception e) { + + } + } + PreciseLevel preciseLevel = PreciseLevel.FUZZY; + if ("strict".equals(model.getPreciseLevel())) { + preciseLevel = PreciseLevel.STRICT; + } + MatchParams params = new MatchParams(); + params.setCity(model.getCity()); + params.setSuggestDistrict(model.getSuggestDistrict()); + params.setSuggestName(model.getSuggestName()); + params.setAddress(address); + params.setBuildingType(buildingType); + params.setPreciseLevel(preciseLevel); + params.setProvince(model.getProvince()); + params.setUseMap(model.isUseMap()); + params.setDebugName(model.getDebugName()); + long start = System.currentTimeMillis(); + Building building = addressParserService.parser(params); + long end = System.currentTimeMillis(); + if (end - start > 200) { + LOGGER.warn("匹配parser耗时:\t" + (end - start) + "ms"); + } + if ("true".equalsIgnoreCase(model.getVerify())) { + verify(building); + } + BasicModel baseModel = BasicModel.buildOKModel(); + Map result = convertBuildingToMap(building); + if (!APIConstant.SUPER_USER_TOKEN.equals(model.getToken())) { + submitFetchTask(building); + result.remove("precise"); + result.remove("searchAddress"); + result.remove("map"); + } + baseModel.setResult(result); + mav.setModel(baseModel); + return mav; + } + + Map convertBuildingToMap(Building building) { + Map result = new LinkedHashMap(); + if (building != null) { + result.put("id", building.getId()); + result.put("credit", building.getCredit()); + result.put("precise", building.getPrecise()); + result.put("province", building.getProvince()); + result.put("city", building.getCity()); + result.put("district", building.getDistrict()); + result.put("name", building.getName()); + result.put("suggestName", building.getSuggestName()); + result.put("map", building.getMap()); + result.put("propertyType", building.getPropertyType()); + result.put("township", building.getTownship()); + result.put("suggestAddress", building.getSuggestAddress()); + if ("district".equals(building.getCategory())) { + result.put("category", "property"); + } else { + result.put("category", building.getCategory()); + } + result.put("address", building.getAddress()); + result.put("block", building.getBlock()); + result.put("lng", building.getLng()); + result.put("lat", building.getLat()); + result.put("alias", building.getAlias()); + result.put("searchAddress", building.getSearchAddress()); + } + return result; + } + + public Object cleanCacheAction(final AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (!OpenConfig.getConfig().addressMatchEnabled()) { + mav.setModel(BasicModel.buildBadRequestModel("不支持该服务")); + return mav; + } + new Thread() { + @Override + public void run() { + addressParserService.clearCache(model.getCity()); + } + }.start(); + mav.setModel(BasicModel.buildOKModel().setMsg("开始刷新缓存")); + return mav; + } + + @Authority(role = Role.NONE) + public Object realMatchAllAction(@Valid AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (!OpenConfig.getConfig().addressMatchEnabled()) { + mav.setModel(BasicModel.buildBadRequestModel("不支持该服务")); + return mav; + } + String address = model.getAddress(); + address = address.replaceAll("@@", "#");// 框架无法处理参数带有#的Buge 用@@代替 + BuildingType buildingType = null; + if (StringUtils.isNotBlank(model.getCategory())) { + if ("property".equals(model.getCategory())) { + model.setCategory("district"); + } + buildingType = BuildingType.valueOf(model.getCategory().toUpperCase()); + } + PreciseLevel preciseLevel = PreciseLevel.FUZZY; + if ("strict".equals(model.getPreciseLevel())) { + preciseLevel = PreciseLevel.STRICT; + } + MatchParams params = new MatchParams(); + params.setCity(model.getCity()); + params.setSuggestDistrict(model.getSuggestDistrict()); + params.setAddress(address); + params.setBuildingType(buildingType); + params.setPreciseLevel(preciseLevel); + params.setProvince(model.getProvince()); + params.setSuggestName(model.getSuggestName()); + AddressParseResult addressParseResult = addressParserService.parserAll(params); + List buildings = addressParseResult.getBuildings(); + List> buildingObjs = new ArrayList>(buildings.size()); + for (Building building : buildings) { + buildingObjs.add(convertBuildingToMap(building)); + } + BasicModel baseModel = BasicModel.buildOKModel(); + baseModel.setResult(buildingObjs); + mav.setModel(baseModel); + return mav; + } + + @Authority(role = Role.USER) + public Object matchAllAction(AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + String result = addressMatchProxyService.parserAll(convertModelToMap(model)); + if (result != null) { + mav.setModel(result); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + public Map convertModelToMap(AddesssMatchModel model) { + + Map params = new HashMap(); + Class clzz = model.getClass(); + for (Field field : clzz.getDeclaredFields()) { + field.setAccessible(true); + String paramName = field.getName(); + try { + Object val = field.get(model); + if (val != null) { + params.put(paramName, val.toString()); + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + return params; + } + + private void verify(Building building) { + String city = building.getCity(); + String region = building.getDistrict(); + String name = null; + if (building.getPrecise() > -1) { + name = building.getName(); + } else { + name = building.getSearchAddress().getOrgKeywords(); + } + if (StringUtils.isNotBlank(region) && StringUtils.isNotBlank(name)) { + String buildingNumber = AddressParserUtil + .standardizeBuildingNumber(building.getSearchAddress().getOrgBuildingNumber()); + if (buildingNumber != null) { + if (houseLoudongService.findHouseLoudong(city, region, name, buildingNumber, null, null) != null) { + building.getSearchAddress().setBuildingNumberCertified(true); + } else if (fjtEvaluationService.findFjtEvaluationByConditions(city, region, name, buildingNumber, + null) != null) { + building.getSearchAddress().setBuildingNumberCertified(true); + } else if (evaluationService.findEvaluationByNum(city, region, name, buildingNumber, null) != null) { + building.getSearchAddress().setBuildingNumberCertified(true); + } + } + + String roomNumber = AddressParserUtil.standardizeRoomNumber(building.getSearchAddress().getOrgRoomNumber()); + if (roomNumber != null) { + if (houseLoudongService.findHouseLoudong(city, region, name, null, null, roomNumber) != null) { + building.getSearchAddress().setRoomNumberCertified(true); + } else if (fjtEvaluationService.findFjtEvaluationByConditions(city, region, name, null, + roomNumber) != null) { + building.getSearchAddress().setRoomNumberCertified(true); + } else if (evaluationService.findEvaluationByNum(city, region, name, null, roomNumber) != null) { + building.getSearchAddress().setRoomNumberCertified(true); + } + } + } + } + + @Authority(role = Role.NONE) + public Object sendFetchTaskAction(AddressModel model) { + + RestfulModelAndView json = new RestfulModelAndView(); + WaitCrawlKeywords waitCrawlKeywords = new WaitCrawlKeywords(); + waitCrawlKeywords.setCity(model.getCity()); + waitCrawlKeywords.setDateCreated(new Date()); + waitCrawlKeywords.setRead(0); + waitCrawlKeywords.setKeywords(model.getAddress()); + waitCrawlKeywordsService.save(waitCrawlKeywords); + json.setModel(waitCrawlKeywords); + + return json; + } + + private void submitFetchTask(Building building) { + if (building.getPrecise() == -1) { + List keywords = new ArrayList(); + Address address = building.getSearchAddress(); + if (StringUtils.isNotBlank(address.getKeywords()) && address.getKeywords().length() > 2) { + keywords.add(address.getKeywords()); + } else if (address.getOrgAddress().length() > 2 && address.getOrgAddress().length() < 10) {// 一般小区名不会超过10个字 + keywords.add(address.getOrgAddress()); + } + if (address.isStandardAddress()) { + if (address.getStreetNumbers() != null) { + for (String b : address.getStreetNumbers()) { + keywords.add(address.getStreet() + b); + } + } else { + keywords.add(address.getStreet()); + } + } + keywords = DataUtil.uniqueList(keywords); + for (String k : keywords) { + WaitCrawlKeywords waitCrawlKeywords = new WaitCrawlKeywords(); + waitCrawlKeywords.setCity(address.getCity()); + waitCrawlKeywords.setDateCreated(new Date()); + waitCrawlKeywords.setRead(0); + waitCrawlKeywords.setKeywords(k); + waitCrawlKeywordsService.save(waitCrawlKeywords); + } + } + } + + /** + * 从Excel表中加载测试数据 + * + * @return + */ + private List> loadTestDataFromExcel(String excelFileName) { + List> ret = new ArrayList>(); + FileInputStream fileInputStream = null; + try { + fileInputStream = new FileInputStream(excelFileName); + HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream); + HSSFSheet sheet = workbook.getSheetAt(0); + // 行号 + boolean isFirstRow = true; + for (Row row : sheet) { + if (isFirstRow) { + // 第一行,过掉 + isFirstRow = false; + continue; + } + + // 得到列数 + // row.getPhysicalNumberOfCells(); + String in_name = row.getCell(1).toString(); + if (in_name.equals("")) { + // 跳过空内容 + continue; + } + Map data = new HashMap(); + // 第0列:城市 + data.put("city", row.getCell(0).toString()); + // 第一列:输入地址 + data.put("in_name", in_name); + // 第二列:期望名称,用于验证 + Cell cell = row.getCell(2); + if (cell != null) { + data.put("out_name", cell.toString()); + } + ret.add(data); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (fileInputStream != null) { + try { + fileInputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return ret; + } + + /** + * 从Excel表中加载测试数据 + * + * @return + */ + private List> loadJingDongTestDataFromExcel(String excelFileName) { + + List> ret = new ArrayList>(); + FileInputStream fileInputStream = null; + try { + fileInputStream = new FileInputStream(excelFileName); + HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream); + HSSFSheet sheet = workbook.getSheetAt(0); + // 行号 + boolean isFirstRow = true; + for (Row row : sheet) { + if (isFirstRow) {// 第一行,过掉 + isFirstRow = false; + continue; + } + String province = row.getCell(0).toString(); + String city = row.getCell(1).toString(); + String in_address = row.getCell(2).toString(); + if (StringUtils.isBlank(in_address) || StringUtils.isBlank(city) || StringUtils.isBlank(province)) { // 跳过空内容 + System.out.println("-->" + row.getRowNum()); + continue; + } + + Map formate = analyseAddress(in_address); + Map data = new HashMap(); + data.put("in_address", in_address); + data.put("city", city); + String formattedAddress = new String(in_address); + List huanxian = Arrays.asList("中环外环之间", "内环以内", "内环中环之间", "中环以内", "外环以外", "(内环高速以里)", "外环外其它地区", + "五环以外", "六环以内", "内环到三环里", "内环到二环里", "二环里", "三环到四环之间", "二环到三环", "四环到五环之间", "二环到三环", "五环至六环之间", + "五环到六环之间", "五环到六环之间", "三环以内", "四环到五环内", "六环以外(其他地区)", "六环以外(张家湾镇、台湖镇、漷县镇)", "六环以外(宋庄镇)", + "一环到二环", "六环以外", "四环至五环之间", "六环外(马驹桥镇)"); + for (String a : huanxian) { + formattedAddress = formattedAddress.replace(a, ""); + } + data.put("formatted_in_address", formattedAddress); + data.put("province", province); + if (formate.get("city") != null) { + data.put("formatedCity", formate.get("city")); + } else { + if (city.endsWith("市") || city.endsWith("县")) { + city = city.substring(0, city.length() - 1); + } else { + if (province.endsWith("市")) { + city = province.substring(0, province.length() - 1); + } else { + city = province; + } + } + data.put("formatedCity", city); + } + ret.add(data); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (fileInputStream != null) { + try { + fileInputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return ret; + } + + private JSONObject addTerm(String name, String value) { + JSONObject term = new JSONObject(); + JSONObject match = new JSONObject(); + match.put(name, value); + term.put("term", match); + return term; + } + + private JSONObject addMatchPhrase(String name, String value) { + JSONObject term = new JSONObject(); + JSONObject match = new JSONObject(); + match.put(name, value); + term.put("match_phrase", match); + return term; + } + + /*** + * 获取自然村 + * @param city + * @param region + * @param name + * @return + */ + private List findVillage(String city, String region, String name) { + JSONObject reqBody = new JSONObject(); + reqBody.put("from", 0); + reqBody.put("size", 5); + JSONObject query = new JSONObject(); + JSONObject bool = new JSONObject(); + JSONArray must = new JSONArray(); + must.add(addTerm("city", city)); + must.add(addTerm("region", region)); + must.add(addTerm("name", name)); + bool.put("must", must); + query.put("bool", bool); + reqBody.put("query", query); + Base64 token = new Base64(); + String authenticationEncoding = token.encodeAsString(("" + ES_USER + ":" + ES_PASSWORD + "").getBytes()); + HttpRequest request = new HttpRequest(); + Map headers = new HashMap(); + headers.put("Content-Type", "application/json"); + headers.put("Authorization", "Basic " + authenticationEncoding + ""); + try { + String response = request.postWithBody("http://192.168.0.45:9200/village/_search", reqBody, headers, "UTF-8"); + JSONObject json = JSONObject.fromObject(response); + if (!json.containsKey("hits") || !json.getJSONObject("hits").containsKey("hits")) { + return Collections.emptyList(); + } + JSONArray hits = json.getJSONObject("hits").getJSONArray("hits"); + List results = new ArrayList(); + for (int i = 0; i < hits.size(); i++) { + JSONObject jsonObject = hits.getJSONObject(i); + results.add(jsonObject); + } + return results; + + } catch (HttpRequestException e) { + e.printStackTrace(); + } + return Collections.emptyList(); + } + + /** + * 加载测试数据 + * + * @return + */ + private List> loadTestData() { + BufferedReader reader = null; + List> ret = new ArrayList>(); + try { + reader = new BufferedReader( + new InputStreamReader(new FileInputStream("D:\\data\\addr\\test20140923.txt"), "utf-8")); + boolean isFirst = true; + while (true) { + String line = reader.readLine(); + if (line == null) { + break; + } + if (isFirst) { + isFirst = false; + int c = line.charAt(0); + if (c == 65279) { + // 去掉UTF-8中头标示 + line = line.substring(1); + } + } + ret.add(parseTestData(line)); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException e) { + + } + } + } + return ret; + } + + /** + * 解析测试数据,其中输入字符串为以TAB分隔的字符串,例如: in_name:经济技术开发区贵园北里丁区 out_name:贵园北里 + * + * @param s + * @return + */ + private Map parseTestData(String s) { + Map ret = new HashMap(); + String[] columns = s.split("\t"); + for (String column : columns) { + int index = column.indexOf(":"); + String key; + String value; + if (index > 0) { + key = column.substring(0, index); + value = column.substring(index + 1); + ret.put(key, value); + } + } + return ret; + } + + @Authority(role = Role.USER) + public Object parseAddressAction(AddressModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (model.getCity() == null || model.getAddress() == null) { + return mav; + } + District district = addressService.parseAddress(model.getCity(), model.getAddress()); + if (district != null) { + Map resMap = new HashMap(); + resMap.put("city", district.getCity()); + resMap.put("region", district.getRegion()); + resMap.put("districtName", district.getName()); + resMap.put("address", district.getAddress()); + mav.setModel(resMap); + } + return mav; + } + + @Authority(role = Role.USER) + public Object geocoderAction(AddressModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + + if (model.getCity() == null || model.getAddress() == null) { + return mav; + } + + double[] lngLat = addressService.getLngLat(model.getCity(), model.getAddress(), AK); + Map resMap = new HashMap(); + resMap.put("lng", lngLat[0]); + resMap.put("lat", lngLat[1]); + mav.setModel(resMap); + return mav; + } + + @Authority(role = Role.USER) + public Object geocoderBaiduToGoogleAction(AddressModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + + if (model.getCity() == null || model.getAddress() == null) { + return mav; + } + + double[] lngLat = addressService.getLngLat(model.getCity(), model.getAddress(), AK); + Map resMap = new HashMap(); + resMap.put("lng", lngLat[0]); + resMap.put("lat", lngLat[1]); + mav.setModel(resMap); + return mav; + } + + @Deprecated + @Authority(role = Role.USER) + public Object addressEvaluationAction(AddressModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + + if (model.getCity() == null || model.getAddress() == null || model.getArea() == null) { + return mav; + } + + Map resMap = new HashMap(); + resMap.put("totalPrice", + addressService.evaluationByAddress(model.getCity(), model.getAddress(), model.getArea(), AK)); + mav.setModel(resMap); + return mav; + } + + @Deprecated + @Authority(role = Role.USER) + public Object addressEvaluation2Action(AddressModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + + if (model.getCity() == null || model.getAddress() == null || model.getArea() == null) { + return mav; + } + + Date weekend = DateUtil.getThisSunday(new Date()); + if (model.getWeekend() != null) { + weekend = DateUtil.getThisSunday(model.getWeekend()); + } + + Map resMap = new HashMap(); + resMap.put("totalPrice", 0); + + District district = addressService.parseAddress(model.getCity(), model.getAddress()); + if (district == null) { + double[] lngLatBaidu = addressService.getLngLat(model.getCity(), model.getAddress(), AK); + if (lngLatBaidu == null) { + mav.setModel(resMap); + return mav; + } + double[] lngLatGoogle = addressService.geoconvBaiduToGoogle(lngLatBaidu[0], lngLatBaidu[1]); + double lng = lngLatGoogle[0]; + double lat = lngLatGoogle[1]; + List params = new ArrayList(); + SdQuery sdQuery = new SdQuery(); + if (lat < -90 && lat > 90 && lng < -180 && lng > 180) { + mav.setModel(resMap); + return mav; + } + params.add(new QueryParam("city", model.getCity())); + params.add(new QueryParam("visible", 0)); + sdQuery.setPoint(lat + "," + lng); + sdQuery.setField("lat_lng"); + sdQuery.setDistance("" + (500 / 1000d)); + params.add(new QueryParam(QueryParam.SD_PARAM_NAME, sdQuery)); + List districts = districtService.findAllByParams(params, 0, 3); + + int totalPrice = 0; + int tc = 0; + for (District dis : districts) { + Evaluation evaluation = new Evaluation(); + evaluation.setCity(dis.getCity()); + evaluation.setRegion(dis.getRegion()); + evaluation.setDistrictName(dis.getName()); + evaluation.setArea(model.getArea()); + evaluation.setSource("api_diZhiGuJia"); + evaluation = evaluationService.saveEvaluation(evaluation, weekend); + if (evaluation.getTotalPrice() != null && evaluation.getTotalPrice() > 0) { + totalPrice += evaluation.getTotalPrice(); + tc++; + } + } + if (tc > 0) { + resMap.put("totalPrice", totalPrice / tc); + } + // } + } else { + Evaluation evaluation = new Evaluation(); + evaluation.setCity(district.getCity()); + evaluation.setRegion(district.getRegion()); + evaluation.setDistrictName(district.getName()); + evaluation.setArea(model.getArea()); + evaluation.setSource("api_diZhiGuJia"); + evaluation = evaluationService.saveEvaluation(evaluation, weekend); + resMap.put("totalPrice", evaluation.getTotalPrice()); + + District dist = districtService.findDistrict( + new DistrictKey(district.getCity(), district.getRegion(), district.getName()), "district"); + if (null != dist) { + if (null != dist.getCarSiteCount() && dist.getCarSiteCount() > 0) { + resMap.put("carSiteCount", dist.getCarSiteCount()); + } + } + + CommData commData = commDataService.findCommDataByCity(district.getCity(), district.getRegion(), + district.getName(), "district"); + if (null != commData && commData.getLastCount() > 0) { + resMap.put("householdCount", commData.getLastCount()); + } + } + mav.setModel(resMap); + return mav; + } + + @Authority(role = Role.USER) + public Object addressStandardParserAction(AddressModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + Map resMap = addressService.parseSelectAddressInfo(model.getCity(), model.getAddress()); + mav.setModel(resMap); + return mav; + } + + @Authority(role = Role.USER) + public Object addressStandardAction(AddressModel model) throws Exception { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + + model.setAddress(AddressParserUtils.filteSpecialChar(model.getAddress())); + Map resMap = addressService.parseSelectAddressInfo(model.getCity(), model.getAddress()); + resMap.put("oldAddress", model.getAddress()); + + if (resMap.get("city") == null || model.getAddress() == null) { + return mav; + } + + District district = null; + // 根据地址查找小区 + if (resMap.get("address") != null) { + district = addressService.parseAddress(resMap.get("city").toString(), resMap.get("address").toString()); + } + // 根据地址中提取出的小区名称查小区 + String oldName = resMap.get("oldName") != null ? resMap.get("oldName").toString() : null;// 地址中疑似小区 + if (district == null && null != oldName) { + district = addressService.parseAddress(resMap.get("city").toString(), oldName); + // 百度查小区 + if (district == null && null != oldName) { + Map ret = baiduApiService.mapSearchSimple(resMap.get("city").toString(), oldName, AK); + List rets = (List) ret.get("content"); + if (null != rets) { + boolean flag = false; + for (Map vo : rets) { + List> vs = (List>) vo.get("cla"); + if (vs == null) { + continue; + } + for (List list : vs) { + String s = list.get(1); + if (s.indexOf("小区") != -1 || s.indexOf("楼盘") != -1) { + flag = true; + resMap.put("name", oldName); + String baiduAddress = (String) vo.get("addr"); + if (StringUtils.isNotBlank(baiduAddress)) { + + if (StringUtils.isBlank((String) resMap.get("address"))) { + resMap.put("address", baiduAddress); + } + + } + + break; + } + } + } + + if (!flag && resMap.get("address") == null) { + resMap.put("address", oldName); + } + } + } + } + + if (district != null) { + District dist = districtService.findDistrict( + new DistrictKey(district.getCity(), district.getRegion(), district.getName()), "district"); + if (dist != null) { + district = dist; + } + resMap.put("status", "0"); + } else { + resMap.put("status", "1"); + } + + // 当businessMatch=1,并且进行小区匹配没有成功的情况下,进行商铺写字楼匹配 通过keyword查找 + if (null != model.getBusinessMatch() && model.getBusinessMatch() == 1 && resMap.get("status").equals("1") + && StringUtils.isNotBlank((String) resMap.get("city"))) { + if (StringUtils.isNotBlank(oldName)) { + district = districtService.findFirstByKeyword((String) resMap.get("city"), oldName); + } + + if (null == district && StringUtils.isNotBlank((String) resMap.get("address"))) { + district = districtService.findFirstByKeyword((String) resMap.get("city"), + (String) resMap.get("address")); + } + } + + if (district != null) { + + resMap.put("name", district.getName()); + resMap.put("region", district.getRegion()); + resMap.put("block", district.getBlock()); + resMap.put("cat", district.getCategory()); + resMap.put("alias", district.getAlias()); + + String tempAddress = (String) resMap.get("address"); + if (StringUtils.isBlank(tempAddress)) { + resMap.put("address", district.getAddress()); + } else { + if (tempAddress.indexOf("弄") == -1 && tempAddress.indexOf("号") == -1 || tempAddress.indexOf("街") == -1 + || tempAddress.indexOf("路") == -1) { + resMap.put("address", district.getAddress()); + } + } + } + + String lastAddress = (String) resMap.get("address"); + if (StringUtils.isNotBlank(lastAddress)) { + if (lastAddress.length() < 2) { + resMap.put("address", null); + } else { + resMap.put("address", AddressParserUtils.filteSpecialChar(resMap.get("address").toString())); + } + + } + resMap.remove("louDong"); + mav.setModel(resMap); + return mav; + } + + public Object address2DistrictAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + + String orgCity = model.getCity(); + String orgAddress = AddressParserUtils.filteSpecialChar(model.getAddress()); + if (StringUtils.isBlank(orgCity) || StringUtils.isBlank(orgAddress)) { + return mav; + } + + Map resMap = addressService.parseSelectAddressInfo(orgCity, orgAddress); + resMap.put("oldAddress", orgAddress); + resMap.remove("louDong"); + + if (null == resMap.get("city")) { + return mav; + } + + String city = (String) resMap.get("city"); + District district = null; + // 小区库匹配 + String address = (String) resMap.get("address"); + if (StringUtils.isNotBlank(address)) { + // 地址、小区名、别名匹配 + List params = new ArrayList(4); + params.add(new QueryParam("city", city)); + params.add(new QueryParam("category", "district")); + params.add(new QueryParam("visible", 0)); + + TermQuery q1 = new TermQuery(new Term("name", address)); + TermQuery q2 = new TermQuery(new Term("alias", address)); + TermQuery q3 = new TermQuery(new Term("address", address)); + BooleanQuery bq = new BooleanQuery(); + bq.add(q1, Occur.SHOULD); + bq.add(q2, Occur.SHOULD); + bq.add(q3, Occur.SHOULD); + params.add(new QueryParam(QueryParam.SR_PARAM_NAME, new SrQuery(bq))); + + List ds = districtService.findAllByParams(params, 0, 1); + if (CollectionUtils.isNotEmpty(ds)) { + district = ds.get(0); + } + } + + // 根据地址中提取出的小区名称查小区 + String oldName = StringUtils.trim((String) resMap.get("oldName")); + if (null == district && StringUtils.isNotBlank(oldName)) { + // 小区名、别名匹配 + List params = new ArrayList(4); + params.add(new QueryParam("city", city)); + params.add(new QueryParam("category", "district")); + params.add(new QueryParam("visible", 0)); + + TermQuery q1 = new TermQuery(new Term("name", oldName)); + TermQuery q2 = new TermQuery(new Term("alias", oldName)); + BooleanQuery bq = new BooleanQuery(); + bq.add(q1, Occur.SHOULD); + bq.add(q2, Occur.SHOULD); + params.add(new QueryParam(QueryParam.SR_PARAM_NAME, new SrQuery(bq))); + + List ds = districtService.findAllByParams(params, 0, 1); + if (CollectionUtils.isNotEmpty(ds)) { + district = ds.get(0); + } + } + + // 地址库匹配 + if (null == district) { + // todo + } + + if (null == district) { + resMap.put("status", 1); + } else { + resMap.put("status", 0); + resMap.put("name", district.getName()); + resMap.put("region", district.getRegion()); + resMap.put("block", district.getBlock()); + resMap.put("cat", district.getCategory()); + resMap.put("alias", district.getAlias()); + + String tempAddress = (String) resMap.get("address"); + if (StringUtils.isBlank(tempAddress)) { + resMap.put("address", district.getAddress()); + } else { + if (tempAddress.indexOf("弄") == -1 && tempAddress.indexOf("号") == -1 || tempAddress.indexOf("街") == -1 + || tempAddress.indexOf("路") == -1) { + resMap.put("address", district.getAddress()); + } + } + } + + String lastAddress = (String) resMap.get("address"); + if (StringUtils.isNotBlank(lastAddress)) { + if (lastAddress.length() < 2) { + resMap.put("address", null); + } else { + resMap.put("address", AddressParserUtils.filteSpecialChar(resMap.get("address").toString())); + } + } + + mav.setModel(resMap); + return mav; + } + + private String findStandardRegion(String city, String region) { + + List regionBloks = regionBlockService.getRegionBlockListByCity(city, null); + String s_region = ""; + if (regionBloks.size() > 0) { + for (RegionBlock regionBlock : regionBloks) { + List patterns = regionBlock.getPattern(); + if (null != patterns && patterns.contains(region)) { + s_region = regionBlock.getName(); + break; + } else { + if (regionBlock.getName().indexOf(region) != -1) { + s_region = region; + break; + } + } + } + } else { + s_region = region; + } + return s_region; + } + + /** + * 地址联想提示 (高德官方) /address/su 参数:address city + * 返回:[{"id":"XXXXXXXXX","city":"上海",region:"长宁","name":"xxx","address":"协和路"}] + * + * @return + */ + public Object suAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + try { + List list = addressService.suAmap(model.getCity().trim(), model.getAddress().trim());// su()是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(list); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } + + /** + * 地址真实性检查 (高德官方) /address/check 参数:chooseId address city + * 返回:{type:"存在|不存在|存疑",data:{"id":"XXXXXXXXX","city":"上海",region:"长宁","name":"xxx","address":"协和路"}} + * 存疑的时候才有data返回,返回高德搜索的第一条数据 (超过的时候,找到最大号码返回) + * + * @return + */ + public Object checkAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } + try { + AddressCheckBo bo = addressService.checkAmap(model.getChooseId(), city, model.getAddress().trim());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatAddressCheckBo(bo, city, model)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } + + /** + * 为返回值格式化掉cityCode和AddressId,用于评级和反欺诈 + * + * @param bo + * @return + */ + private AddressCheckBo formatAddressCheckBo2(AddressCheckBo bo, String city, AddressModel model) { + AddressCheck check = bo.getData(); + if (null != check) { + check.setCityCode(null); + if (StringUtils.isEmpty(check.getCity()) || "[]".equals(check.getCity())) { + check.setCity(city); + } + // if (StringUtils.isEmpty(check.getAddress()) || + // "[]".equals(check.getAddress())) { + // check.setAddress(check.getName()); + // } + // 检查相关参数 + if (FJW_LEVEL.equals(model.getDataLevel())) { + bo.setData(check); + } else { + check.setDistrictName(null); + check.setKeyWords(null); + check.setKeyWordsUse(null); + check.setRegion(null); + check.setProvionce(null); + check.setNameUse(null); + check.setAddressUse(null); + check.setAddress2(null); + check.setName2(null); + check.setType(null); + check.setFormatAddress(null); + check.setFormatAddress2(null); + check.setLocation2(null); + check.setLevel(null); + check.setScoreIncity(null); + check.setScoreInnation(null); + check.setPriceScore(null); + check.setAreaScore(null); + check.setEstateScore(null); + bo.setData(check); + } + } + if ("不存在".equals(bo.getType())) { + bo.setType("地址未找到:抱歉,在" + city + "没有找到与'" + model.getAddress() + "'相关的地点"); + } + return bo; + } + + /** + * 查询高德城市及城市编码 + * + * @return + */ + public Object cityAllAction() { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + List list = addressService.findAllCityAmap(); + BasicModel model = new BasicModel(HttpStatusCodeEnum.OK); + model.setResult(list); + mav.setModel(model); + return mav; + } + + /** + * 地址联想提示 (代理) + * + * @return + */ + public Object suAmapAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + try { + List list = addressService.su(model.getCity().trim(), model.getAddress().trim()); + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(list); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } + + /** + * 地址真实性检查 (代理) + * + * @return + */ + public Object checkAmapAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } + try { + AddressCheckBo bo = addressService.check(model.getChooseId(), city, model.getAddress().trim()); + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatAddressCheckBo(bo, city, model)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } + + /** + * 地址评级 + * + * @param model (city+address)+addressId + * @return { "code": 200, "msg": "ok", "result": { "data": { "address": "匹配地址", + * "city": "城市", "keyWords": "用户输入", "keyWordsUse": "用户输入格式化", "lat": + * 经纬度, "lng": 经纬度, "name": "匹配POIName", "score": 评分 }, "type": "可能存在" } + * } + */ + public Object gradeAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } + + try { + AddressCheckBo bo = addressService.gradeAmap(model.getChooseId(), city, model.getAddress().trim());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatAddressCheckBo2(bo, city, model)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } + + /** + * 地址反欺诈 (地址验真+周边查询) + * + * @param model (city+address)+addressId + * @return { "code": 200, "msg": "ok", "result": { "data": { "address": "匹配地址", + * "city": "城市", "keyWords": "用户输入", "keyWordsUse": "用户输入格式化", "lat": + * 纬度, "lng": 经度, "name": "匹配POIName", "poiList":[ { "name" : + * "文洋大厦停车场(协和路)", "type" : "类型", "address" : "协和路1033号", "lat": 纬度, + * "lng": 经度, "distance":距离 },... ] }, "type": "存在" } } + */ + public Object antiFraudAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } + + try { + AddressCheckBo bo = addressService.antiFraudAmap(model.getChooseId(), city, model.getAddress().trim(), + model.getType(), model.getRadius(), model.getNumber(), model.getPageNo());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatAddressCheckBo2(bo, city, model)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } + + /** + * 地址反欺诈 (地址验真+周边查询) + * + * @param model (city+address)+addressId + * @return { "code": 200, "msg": "ok", "result": { "data": { "address": + * "德州路220弄小区", "addressId": "d525e60aab2e84909d2fd998b0af5e8e", "city": + * "上海市", "keyWords": "德州路220弄", "keyWordsUse": "德州路220弄", "lat": + * 31.167814, "lng": 121.495784, "name": "上海后来居上家庭公寓(德州路分店)", "poiMap": + * { "加油站": [ { "address": "杨思路648号", "distance": "642.0m", "lat": + * 31.162078, "lng": 121.496522, "name": "中国石化加油站(杨思路)", "type": "加油站" + * }, { "address": "杨思路2号", "distance": "1.6km", "lat": 31.15627, "lng": + * 121.485031, "name": "中国石油杨思加油站(杨思路)", "type": "加油站" }, ... ] } ... }, + * "type": "存在" } } + */ + public Object antiFraudBAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } + + try { + AddressCheckBo bo = addressService.antiFraudAmapB(model.getChooseId(), city, model.getAddress().trim(), + model.getType(), model.getRadius(), model.getNumber());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatAddressCheckBo2(bo, city, model)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } + + public Object standardAction(AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + String result = addressMatchProxyService.standard(convertModelToMap(model)); + if (result != null) { + JSONObject json = JSONObject.fromObject(result); + int code = json.getInt("code"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + /** + * 地址标准化接口V2 + * + * @param model + * @return + */ + public Object standard2Action(AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); + params.put("address", model.getAddress()); + params.put("showCode", model.getShowCode()); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/structure", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/structure", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("status"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + /** + * 招商证券POC测试接口封装 + */ + public Object cmbTestAction(AddesssMatchModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); + params.put("address", model.getAddress()); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/cmbTest", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/cmbTest", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("status"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + /** + * 五级地址标准化接口 + * + * @param model + * @return + */ + public Object fiveDivisionStructureAction(AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); + params.put("address", model.getAddress()); + // 地址验证无效也输出标准化结果 + params.put("flag", "true"); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/fiveDivisionStructure", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/fiveDivisionStructure", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("status"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + /** + * 五级行政区划V2地址标准化接口 + * + * @param model + * @return + */ + public Object fiveDivisionStructure2Action(AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); + params.put("address", model.getAddress()); + // 地址验证无效也输出标准化结果 + params.put("flag", "true"); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/fiveDivisionStructure/v2", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/fiveDivisionStructure/v2", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("status"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + + /** + * 详细地址标准化接口 + * + * @param model + * @return + */ + public Object divisionStructureAction(AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); + params.put("address", model.getAddress()); + // 地址验证无效也输出标准化结果 + params.put("flag", "true"); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/divisionStructure", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/divisionStructure", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("status"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + /** + * 地址标准化专用测试接口 + * + * @param model + * @return + */ + public Object structureAndCompleteAction(AddesssMatchModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); + params.put("address", model.getAddress()); + // 地址验证无效也输出标准化结果 + params.put("flag", "true"); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/structureAndComplete", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/structureAndComplete", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("status"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + /** + * 地址信息分类接口 + * + * @param model + * @return + */ + public Object communitySummaryAction(CommunitySummaryRequestDto model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + try { + Map headers = new HashMap(); + headers.put("Content-Type", "application/json"); + + JSONObject reqBody = new JSONObject(); + reqBody.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); + reqBody.put("address", model.getAddress()); + reqBody.put("area", model.getArea()); + reqBody.put("maxFloor", model.getMaxFloor()); + reqBody.put("housePurpose", model.getHousePurpose()); + reqBody.put("memo", model.getMemo()); + + String result = request.postWithBody("http://192.168.0.100:32080/FangJiaAddressService/communitySummary", reqBody, headers, "UTF-8"); + if (result != null) { + try { + json = JSONObject.fromObject(result); + } catch (Exception e) { + json = null; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + if (json != null) { + int code = json.getInt("status"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + /** + * 楼盘评级 + * + * @param model + * @return + */ + public Object buildingRatingAction(CommunitySummaryRequestDto model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + try { + Map headers = new HashMap(); + headers.put("Content-Type", "application/json"); + + JSONObject reqBody = new JSONObject(); + reqBody.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); + reqBody.put("address", model.getAddress()); + reqBody.put("area", model.getArea()); + reqBody.put("maxFloor", model.getMaxFloor()); + reqBody.put("housePurpose", model.getHousePurpose()); + reqBody.put("memo", model.getMemo()); + String result = request.postWithBody("http://192.168.0.100:32080/FangJiaAddressService/buildingRating", reqBody, headers, "UTF-8"); + if (result != null) { + try { + json = JSONObject.fromObject(result); + } catch (Exception e) { + json = null; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + if (json != null) { + int code = json.getInt("status"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + /** + * 财力评级 + * + * @param model + * @return + */ + public Object financialRatingAction(CommunitySummaryRequestDto model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress()) || "null".equals(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + try { + Map headers = new HashMap(); + headers.put("Content-Type", "application/json"); + + JSONObject reqBody = new JSONObject(); + reqBody.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : CONFIG.getDefaultCity()); + reqBody.put("address", model.getAddress()); + reqBody.put("area", model.getArea()); + reqBody.put("maxFloor", model.getMaxFloor()); + reqBody.put("housePurpose", model.getHousePurpose()); + reqBody.put("memo", model.getMemo()); + String result = request.postWithBody("http://192.168.0.100:32080/FangJiaAddressService/financialRating", reqBody, headers, "UTF-8"); + if (result != null) { + try { + json = JSONObject.fromObject(result); + } catch (Exception e) { + json = null; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + if (json != null) { + int code = json.getInt("status"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + public Object similarityAction(AddesssMatchModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress_1()) || StringUtils.isBlank(model.getAddress_2())) { + mav.setModel(BasicModel.buildBadRequestModel("两个地址均不能为空")); + return mav; + } + model.setAddress(model.getAddress_1()); + String result1 = addressMatchProxyService.standard(convertModelToMap(model)); + model.setAddress(model.getAddress_2()); + String result2 = addressMatchProxyService.standard(convertModelToMap(model)); + if (result1 != null && result2 != null) { + Map resultMap = addressService.addressSimilarity(result1, result2); + mav.setModel(BasicModel.buildOKModel().setResult(resultMap)); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + public Object parseCityAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getProvince())) { + mav.setModel(BasicModel.buildBadRequestModel("province不能为空")); + return mav; + } + if (StringUtils.isBlank(model.getDistrict())) { + mav.setModel(BasicModel.buildBadRequestModel("district不能为空")); + return mav; + } + CityParseBo bo = addressService.cityParse(model.getProvince(), model.getDistrict()); + if (bo.getCity() != null) { + UniversalDto dto = UniversalDto.newDto(); + dto.append("city", bo.getCity()); + mav.setModel(BasicModel.buildOKModel().setResult(dto)); + } else { + mav.setModel(BasicModel.buildModel(40001, bo.getMsg())); + } + return mav; + } + + public Object realStandardAction(AddressModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (!OpenConfig.getConfig().addressMatchEnabled()) { + mav.setModel(BasicModel.buildBadRequestModel("不支持该服务")); + return mav; + } + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } /*if (StringUtils.isBlank(model.getCity())) { mav.setModel(BasicModel.buildBadRequestModel("城市不能为空")); return mav; }*/ - MatchParams matchParams = new MatchParams(); - matchParams.setCity(model.getCity()); - matchParams.setAddress(model.getAddress()); - matchParams.setAddressParserGoal(AddressParserGoal.Match); - matchParams.setPreciseLevel(PreciseLevel.STRICT); - matchParams.setProvince(model.getProvince()); + MatchParams matchParams = new MatchParams(); + matchParams.setCity(model.getCity()); + matchParams.setAddress(model.getAddress()); + matchParams.setAddressParserGoal(AddressParserGoal.Match); + matchParams.setPreciseLevel(PreciseLevel.STRICT); + matchParams.setProvince(model.getProvince()); // matchParams.setUseMap(true); - matchParams.setUseAliyunApi(false); + matchParams.setUseAliyunApi(false); // matchParams.setUseCrf(true); - matchParams.setContainsLocation(model.isContainsLocation()); - Building building = addressParserService.standard(matchParams); - Address address = building.getSearchAddress(); - UniversalDto dto = UniversalDto.newDto(); - dto.append("province", address.getProvince()); - dto.append("city", address.getCity()); - if (address.getDistrict() != null) { - dto.append("district", address.getDistrict()); - } else { - dto.append("district", building.getDistrict()); - } - dto.append("developmentZone", address.getDevelopmentZone()); - dto.append("township", address.getTownship()); - dto.append("street", address.getStreet()); - dto.append("streetNumber", address.getStreetNumber()); - if(StringUtils.isBlank(building.getSuggestName())){ - if(StringUtils.isNotBlank(address.getParsedPropertyName())){ - dto.append("name", address.getParsedPropertyName()); - }else if(StringUtils.isNotBlank(address.getOrgKeywords())){ - dto.append("name", address.getOrgKeywords()); - } - }else{ - dto.append("name", building.getSuggestName()); - } - if(StringUtils.isBlank(address.getStreet()) && StringUtils.isNotBlank(building.getAddress())){ - String addr = building.getAddress(); - String street = AddressParserUtil.extractStreet(addr); - if(street != null){ - dto.append("street", street); - if(addr.length() != street.length()){ - dto.append("streetNumber", AddressParserUtil.match(AddressParserUtil.STREET_NUMBER_CONNECTOR_PATTERN, addr)); - } - }else if(StringUtils.isNotBlank(building.getStreet())){ - dto.append("street", building.getStreet()); - if(StringUtils.isNotBlank(building.getStreetno())){ - dto.append("streetNumber", building.getStreetno()); - } - } - } - dto.append("buildingNumber", address.getBuildingNumber()); - dto.append("floor", address.getFloor()); - dto.append("unitNumber", address.getUnitNumber()); - dto.append("roomNumber", address.getRoomNumber()); - dto.append("formattedAddress", address.getFormattedAddress()); - if(matchParams.isContainsLocation()){ - dto.append("lat", building.getLat()); - dto.append("lng", building.getLng()); - } - mav.setModel(BasicModel.buildOKModel().setResult(dto)); - return mav; - } + matchParams.setContainsLocation(model.isContainsLocation()); + Building building = addressParserService.standard(matchParams); + Address address = building.getSearchAddress(); + UniversalDto dto = UniversalDto.newDto(); + dto.append("province", address.getProvince()); + dto.append("city", address.getCity()); + if (address.getDistrict() != null) { + dto.append("district", address.getDistrict()); + } else { + dto.append("district", building.getDistrict()); + } + dto.append("developmentZone", address.getDevelopmentZone()); + dto.append("township", address.getTownship()); + dto.append("street", address.getStreet()); + dto.append("streetNumber", address.getStreetNumber()); + if (StringUtils.isBlank(building.getSuggestName())) { + if (StringUtils.isNotBlank(address.getParsedPropertyName())) { + dto.append("name", address.getParsedPropertyName()); + } else if (StringUtils.isNotBlank(address.getOrgKeywords())) { + dto.append("name", address.getOrgKeywords()); + } + } else { + dto.append("name", building.getSuggestName()); + } + if (StringUtils.isBlank(address.getStreet()) && StringUtils.isNotBlank(building.getAddress())) { + String addr = building.getAddress(); + String street = AddressParserUtil.extractStreet(addr); + if (street != null) { + dto.append("street", street); + if (addr.length() != street.length()) { + dto.append("streetNumber", AddressParserUtil.match(AddressParserUtil.STREET_NUMBER_CONNECTOR_PATTERN, addr)); + } + } else if (StringUtils.isNotBlank(building.getStreet())) { + dto.append("street", building.getStreet()); + if (StringUtils.isNotBlank(building.getStreetno())) { + dto.append("streetNumber", building.getStreetno()); + } + } + } + dto.append("buildingNumber", address.getBuildingNumber()); + dto.append("floor", address.getFloor()); + dto.append("unitNumber", address.getUnitNumber()); + dto.append("roomNumber", address.getRoomNumber()); + dto.append("formattedAddress", address.getFormattedAddress()); + if (matchParams.isContainsLocation()) { + dto.append("lat", building.getLat()); + dto.append("lng", building.getLng()); + } + mav.setModel(BasicModel.buildOKModel().setResult(dto)); + return mav; + } - /** - * 进行地址的取舍 - * - * @param bo - * @return - */ - private AddressCheckBo formatAddressCheckBo(AddressCheckBo bo, String city, AddressModel model) { - AddressCheck check = bo.getData(); - if (null != check) { - check.setCityCode(null); - if (StringUtils.isEmpty(check.getCity()) || "[]".equals(check.getCity())) { - check.setCity(city); - } - // 检查相关参数 - if (FJW_LEVEL.equals(model.getDataLevel())) { - bo.setData(check); - } else { - // 添加地址和address的取舍 - chooseAddressAndName(check); - formatAddressAndName(check); + /** + * 进行地址的取舍 + * + * @param bo + * @return + */ + private AddressCheckBo formatAddressCheckBo(AddressCheckBo bo, String city, AddressModel model) { + AddressCheck check = bo.getData(); + if (null != check) { + check.setCityCode(null); + if (StringUtils.isEmpty(check.getCity()) || "[]".equals(check.getCity())) { + check.setCity(city); + } + // 检查相关参数 + if (FJW_LEVEL.equals(model.getDataLevel())) { + bo.setData(check); + } else { + // 添加地址和address的取舍 + chooseAddressAndName(check); + formatAddressAndName(check); - check.setDistrictName(null); - check.setKeyWords(null); - check.setKeyWordsUse(null); - check.setRegion(null); - check.setProvionce(null); - check.setNameUse(null); - check.setAddressUse(null); - check.setAddress2(null); - check.setName2(null); - check.setType(null); - check.setFormatAddress(null); - check.setFormatAddress2(null); - check.setLocation2(null); - check.setLevel(null); - bo.setData(check); - } - } - if ("不存在".equals(bo.getType())) { - bo.setType("地址未找到:抱歉,在" + city + "没有找到与'" + model.getAddress() + "'相关的地点"); - } - return bo; - } + check.setDistrictName(null); + check.setKeyWords(null); + check.setKeyWordsUse(null); + check.setRegion(null); + check.setProvionce(null); + check.setNameUse(null); + check.setAddressUse(null); + check.setAddress2(null); + check.setName2(null); + check.setType(null); + check.setFormatAddress(null); + check.setFormatAddress2(null); + check.setLocation2(null); + check.setLevel(null); + bo.setData(check); + } + } + if ("不存在".equals(bo.getType())) { + bo.setType("地址未找到:抱歉,在" + city + "没有找到与'" + model.getAddress() + "'相关的地点"); + } + return bo; + } - private void chooseAddressAndName(AddressCheck check) { - boolean isNameOk = false; - boolean isAddressOk = false; - String keyWords = check.getKeyWords(); - // 再我方拆词接口 - String name = check.getName(); - String address = check.getAddress(); - if (!isNameOk && isCorrectName(name)) { - check.setName(name); - isNameOk = true; - } - if (!isAddressOk && isCorrectAddress(address)) { - check.setAddress(address); - isAddressOk = true; - } - if (isNameOk && isAddressOk) { - return; - } - // 优先级先高德POI - String namePoi = check.getNameUse(); - String addressPoi = check.getAddressUse(); - if (!isNameOk && isCorrectNamePoi(namePoi, keyWords)) { - check.setName(namePoi); - isNameOk = true; - } - if (!isAddressOk && isCorrectAddressPoi(addressPoi, keyWords)) { - check.setAddress(addressPoi); - isAddressOk = true; - } - if (isNameOk && isAddressOk) { - return; - } - // 再高德地址编码 - String namePoi2 = check.getName2(); - String addressPoi2 = check.getAddress2(); - if (!isNameOk && isCorrectNamePoi(namePoi2, keyWords)) { - check.setName(namePoi2); - isNameOk = true; - } - if (!isAddressOk && isCorrectAddressPoi(addressPoi2, keyWords)) { - check.setAddress(addressPoi2); - isAddressOk = true; - } - if (isNameOk && isAddressOk) { - return; - } - // 最后高德标准化地址拆分 - String formateAddress = check.getFormatAddress(); - if (StringUtils.isNotEmpty(formateAddress)) { - Map resultMap = addressService.splitAddress(check.getCity(), formateAddress); - String nameNew = resultMap.get("name"); - String addressNew = resultMap.get("address"); - if (!isNameOk && isCorrectName(nameNew) && isCorrectNamePoi(nameNew, keyWords)) { - check.setName(nameNew); - isNameOk = true; - } - if (!isAddressOk && isCorrectAddress(addressNew) && isCorrectAddressPoi(addressNew, keyWords)) { - check.setAddress(addressNew); - isAddressOk = true; - } - } + private void chooseAddressAndName(AddressCheck check) { + boolean isNameOk = false; + boolean isAddressOk = false; + String keyWords = check.getKeyWords(); + // 再我方拆词接口 + String name = check.getName(); + String address = check.getAddress(); + if (!isNameOk && isCorrectName(name)) { + check.setName(name); + isNameOk = true; + } + if (!isAddressOk && isCorrectAddress(address)) { + check.setAddress(address); + isAddressOk = true; + } + if (isNameOk && isAddressOk) { + return; + } + // 优先级先高德POI + String namePoi = check.getNameUse(); + String addressPoi = check.getAddressUse(); + if (!isNameOk && isCorrectNamePoi(namePoi, keyWords)) { + check.setName(namePoi); + isNameOk = true; + } + if (!isAddressOk && isCorrectAddressPoi(addressPoi, keyWords)) { + check.setAddress(addressPoi); + isAddressOk = true; + } + if (isNameOk && isAddressOk) { + return; + } + // 再高德地址编码 + String namePoi2 = check.getName2(); + String addressPoi2 = check.getAddress2(); + if (!isNameOk && isCorrectNamePoi(namePoi2, keyWords)) { + check.setName(namePoi2); + isNameOk = true; + } + if (!isAddressOk && isCorrectAddressPoi(addressPoi2, keyWords)) { + check.setAddress(addressPoi2); + isAddressOk = true; + } + if (isNameOk && isAddressOk) { + return; + } + // 最后高德标准化地址拆分 + String formateAddress = check.getFormatAddress(); + if (StringUtils.isNotEmpty(formateAddress)) { + Map resultMap = addressService.splitAddress(check.getCity(), formateAddress); + String nameNew = resultMap.get("name"); + String addressNew = resultMap.get("address"); + if (!isNameOk && isCorrectName(nameNew) && isCorrectNamePoi(nameNew, keyWords)) { + check.setName(nameNew); + isNameOk = true; + } + if (!isAddressOk && isCorrectAddress(addressNew) && isCorrectAddressPoi(addressNew, keyWords)) { + check.setAddress(addressNew); + isAddressOk = true; + } + } - if (!isNameOk) { - check.setName(null); - } + if (!isNameOk) { + check.setName(null); + } - if (!isAddressOk) { - check.setAddress(null); - } - } + if (!isAddressOk) { + check.setAddress(null); + } + } - private void formatAddressAndName(AddressCheck check) { - String nameEnd = check.getName(); - String addressEnd = check.getAddress(); - // name处理 - if (StringUtils.isNotEmpty(nameEnd)) { - if (isStartWithNum(nameEnd) || isEndWithNum(nameEnd)) { - nameEnd = null; - } else { - // 去掉楼结尾的 - nameEnd = check.getName(); - // 先去头部楼层 - String floorNum = isContainsFloorNum(nameEnd); - if (StringUtils.isNotEmpty(floorNum) && nameEnd.startsWith(floorNum)) { - nameEnd = nameEnd.substring(floorNum.length(), nameEnd.length()); - } - // 再去尾部楼层 - String floorNum2 = isContainsFloorNum(nameEnd); - if (StringUtils.isNotEmpty(floorNum2) && nameEnd.endsWith(floorNum2)) { - nameEnd = nameEnd.substring(0, nameEnd.lastIndexOf(floorNum2)); - } - // 再判断是否带数字- - String numData = isContainsNumData(nameEnd); - if (StringUtils.isNotEmpty(numData) && nameEnd.endsWith(numData)) { - nameEnd = nameEnd.substring(0, nameEnd.lastIndexOf(numData)); - } - // 处理后是否超过三个字符 - if (nameEnd.length() < 3) { - nameEnd = null; - } else if (nameEnd.endsWith("旁")) { - nameEnd = nameEnd.substring(0, nameEnd.lastIndexOf("旁")); - } - } - check.setName(nameEnd); - } + private void formatAddressAndName(AddressCheck check) { + String nameEnd = check.getName(); + String addressEnd = check.getAddress(); + // name处理 + if (StringUtils.isNotEmpty(nameEnd)) { + if (isStartWithNum(nameEnd) || isEndWithNum(nameEnd)) { + nameEnd = null; + } else { + // 去掉楼结尾的 + nameEnd = check.getName(); + // 先去头部楼层 + String floorNum = isContainsFloorNum(nameEnd); + if (StringUtils.isNotEmpty(floorNum) && nameEnd.startsWith(floorNum)) { + nameEnd = nameEnd.substring(floorNum.length(), nameEnd.length()); + } + // 再去尾部楼层 + String floorNum2 = isContainsFloorNum(nameEnd); + if (StringUtils.isNotEmpty(floorNum2) && nameEnd.endsWith(floorNum2)) { + nameEnd = nameEnd.substring(0, nameEnd.lastIndexOf(floorNum2)); + } + // 再判断是否带数字- + String numData = isContainsNumData(nameEnd); + if (StringUtils.isNotEmpty(numData) && nameEnd.endsWith(numData)) { + nameEnd = nameEnd.substring(0, nameEnd.lastIndexOf(numData)); + } + // 处理后是否超过三个字符 + if (nameEnd.length() < 3) { + nameEnd = null; + } else if (nameEnd.endsWith("旁")) { + nameEnd = nameEnd.substring(0, nameEnd.lastIndexOf("旁")); + } + } + check.setName(nameEnd); + } - // 地址处理 - if (StringUtils.isNotEmpty(addressEnd)) { - // 检查是否路结尾,以及关键字中是否带路号 - if (addressEnd.endsWith("路")) { - String streetNum = isContainsAddressNum(check.getKeyWords()); - if (StringUtils.isNotEmpty(streetNum)) { - check.setAddress(addressEnd + streetNum); - } - } - } - } + // 地址处理 + if (StringUtils.isNotEmpty(addressEnd)) { + // 检查是否路结尾,以及关键字中是否带路号 + if (addressEnd.endsWith("路")) { + String streetNum = isContainsAddressNum(check.getKeyWords()); + if (StringUtils.isNotEmpty(streetNum)) { + check.setAddress(addressEnd + streetNum); + } + } + } + } - private boolean isStartWithNum(String keyWords) { - Pattern p = Pattern.compile("^[0-9]+"); - Matcher m = p.matcher(keyWords); - if (m.find()) { - return true; - } - return false; - } + private boolean isStartWithNum(String keyWords) { + Pattern p = Pattern.compile("^[0-9]+"); + Matcher m = p.matcher(keyWords); + if (m.find()) { + return true; + } + return false; + } - private boolean isEndWithNum(String keyWords) { - Pattern p = Pattern.compile("[0-9]+$"); - Matcher m = p.matcher(keyWords); - if (m.find()) { - return true; - } - return false; - } + private boolean isEndWithNum(String keyWords) { + Pattern p = Pattern.compile("[0-9]+$"); + Matcher m = p.matcher(keyWords); + if (m.find()) { + return true; + } + return false; + } - private String isContainsAddressNum(String keyWords) { - String num = null; - Pattern p = Pattern.compile("路[0-9]+-{1}[0-9]+号"); - Matcher m = p.matcher(keyWords); - if (m.find()) { - num = m.group(0); - num = num.substring(1, num.length()); - } - return num; - } + private String isContainsAddressNum(String keyWords) { + String num = null; + Pattern p = Pattern.compile("路[0-9]+-{1}[0-9]+号"); + Matcher m = p.matcher(keyWords); + if (m.find()) { + num = m.group(0); + num = num.substring(1, num.length()); + } + return num; + } - private static final String ERROR_NAME = "工业区&商住楼&开发区&金融街&汽配城&商贸中心&发展中心&公寓楼&商贸城&国际大厦&开发区&综合楼&商贸中心&综合大楼&创业园"; + private static final String ERROR_NAME = "工业区&商住楼&开发区&金融街&汽配城&商贸中心&发展中心&公寓楼&商贸城&国际大厦&开发区&综合楼&商贸中心&综合大楼&创业园"; - private boolean isCorrectName(String name) { - if (StringUtils.isEmpty(name)) {// 为空 - return false; - } else if (name.length() < 3) {// 字符少于三个 - return false; - } else if (StringUtils.isNumeric(name) || isDigit(name)) {// 字符为数字 - return false; - } else if (!isContainsChineseWord(name)) { // 不包含汉字 - return false; - } else if (name.startsWith("之")) {// 以之开头,带数字的 - String c = name.substring(1, 2);// 取之后一个字符 - // 判断是否为数字或字母 - if (StringUtils.isNumeric(c) || isDigit(c) || c.matches("[a-zA-Z]+")) { - return false; - } - } else if (name.endsWith("路")) { - return false; - } else if (ERROR_NAME.contains(name)) { - return false; - } - return true; - } + private boolean isCorrectName(String name) { + if (StringUtils.isEmpty(name)) {// 为空 + return false; + } else if (name.length() < 3) {// 字符少于三个 + return false; + } else if (StringUtils.isNumeric(name) || isDigit(name)) {// 字符为数字 + return false; + } else if (!isContainsChineseWord(name)) { // 不包含汉字 + return false; + } else if (name.startsWith("之")) {// 以之开头,带数字的 + String c = name.substring(1, 2);// 取之后一个字符 + // 判断是否为数字或字母 + if (StringUtils.isNumeric(c) || isDigit(c) || c.matches("[a-zA-Z]+")) { + return false; + } + } else if (name.endsWith("路")) { + return false; + } else if (ERROR_NAME.contains(name)) { + return false; + } + return true; + } - private String isContainsFloorNum(String keyWords) { - String num = null; - Pattern p = Pattern.compile( - "[0-9]+楼|[一|二|三|四|五|六|七|八|九|十]+楼|[a-zA-Z]+楼|[0-9]+幢|[一|二|三|四|五|六|七|八|九|十]+幢|[a-zA-Z]+幢|[0-9]+号|[一|二|三|四|五|六|七|八|九|十]+号|[a-zA-Z]+号"); - Matcher m = p.matcher(keyWords); - if (m.find()) { - num = m.group(0); - } - return num; - } + private String isContainsFloorNum(String keyWords) { + String num = null; + Pattern p = Pattern.compile( + "[0-9]+楼|[一|二|三|四|五|六|七|八|九|十]+楼|[a-zA-Z]+楼|[0-9]+幢|[一|二|三|四|五|六|七|八|九|十]+幢|[a-zA-Z]+幢|[0-9]+号|[一|二|三|四|五|六|七|八|九|十]+号|[a-zA-Z]+号"); + Matcher m = p.matcher(keyWords); + if (m.find()) { + num = m.group(0); + } + return num; + } - private String isContainsNumData(String keyWords) { - String num = null; - Pattern p = Pattern.compile("[0-9]+-|[一|二|三|四|五|六|七|八|九|十]+-|[a-zA-Z]+-"); - Matcher m = p.matcher(keyWords); - if (m.find()) { - num = m.group(0); - } - return num; - } + private String isContainsNumData(String keyWords) { + String num = null; + Pattern p = Pattern.compile("[0-9]+-|[一|二|三|四|五|六|七|八|九|十]+-|[a-zA-Z]+-"); + Matcher m = p.matcher(keyWords); + if (m.find()) { + num = m.group(0); + } + return num; + } - private boolean isCorrectNamePoi(String name, String keyWords) { - if (StringUtils.isEmpty(name)) {// 为空 - return false; - } else if (name.length() < 3) {// 字符少于三个 - return false; - } else if (!keyWords.contains(name)) { - return false; - } else if (StringUtils.isNumeric(name) || isDigit(name)) {// 字符为数字 - return false; - } else if (!isContainsChineseWord(name)) { // 不包含汉字 - return false; - } else if (name.startsWith("之")) {// 以之开头,带数字的 - String c = name.substring(1, 2);// 取楼前一个字符 - // 判断是否为数字或字母 - if (StringUtils.isNumeric(c) || isDigit(c) || c.matches("[a-zA-Z]+")) { - return false; - } - } else if (name.endsWith("路")) { - return false; - } else if (ERROR_NAME.contains(name)) { - return false; - } - return true; - } + private boolean isCorrectNamePoi(String name, String keyWords) { + if (StringUtils.isEmpty(name)) {// 为空 + return false; + } else if (name.length() < 3) {// 字符少于三个 + return false; + } else if (!keyWords.contains(name)) { + return false; + } else if (StringUtils.isNumeric(name) || isDigit(name)) {// 字符为数字 + return false; + } else if (!isContainsChineseWord(name)) { // 不包含汉字 + return false; + } else if (name.startsWith("之")) {// 以之开头,带数字的 + String c = name.substring(1, 2);// 取楼前一个字符 + // 判断是否为数字或字母 + if (StringUtils.isNumeric(c) || isDigit(c) || c.matches("[a-zA-Z]+")) { + return false; + } + } else if (name.endsWith("路")) { + return false; + } else if (ERROR_NAME.contains(name)) { + return false; + } + return true; + } - private boolean isCorrectAddress(String address) { // 市区镇县省结尾 - if (StringUtils.isEmpty(address)) {// 为空 - return false; - } else if (address.length() < 3) {// 字符少于三个 - return false; - } else if (StringUtils.isNumeric(address) || isDigit(address)) {// 字符为数字 - return false; - } else if (!isContainsChineseWord(address)) { // 不包含汉字 - return false; - } else if (address.endsWith("省") || address.endsWith("市") || address.endsWith("区") || address.endsWith("县") - || address.endsWith("乡") || address.endsWith("镇") || address.endsWith("村") || address.endsWith("街道")) { // 带数字/字母的楼结尾 - return false; - } - return true; - } + private boolean isCorrectAddress(String address) { // 市区镇县省结尾 + if (StringUtils.isEmpty(address)) {// 为空 + return false; + } else if (address.length() < 3) {// 字符少于三个 + return false; + } else if (StringUtils.isNumeric(address) || isDigit(address)) {// 字符为数字 + return false; + } else if (!isContainsChineseWord(address)) { // 不包含汉字 + return false; + } else if (address.endsWith("省") || address.endsWith("市") || address.endsWith("区") || address.endsWith("县") + || address.endsWith("乡") || address.endsWith("镇") || address.endsWith("村") || address.endsWith("街道")) { // 带数字/字母的楼结尾 + return false; + } + return true; + } - private boolean isCorrectAddressPoi(String address, String keyWords) { // 市区镇县省结尾 - if (StringUtils.isEmpty(address)) {// 为空 - return false; - } else if (address.length() < 3) {// 字符少于三个 - return false; - } else if (!keyWords.contains(address)) { - return false; - } else if (StringUtils.isNumeric(address) || isDigit(address)) {// 字符为数字 - return false; - } else if (!isContainsChineseWord(address)) { // 不包含汉字 - return false; - } else if (address.endsWith("省") || address.endsWith("市") || address.endsWith("区") || address.endsWith("县") - || address.endsWith("乡") || address.endsWith("镇") || address.endsWith("村") || address.endsWith("街道")) { // 带数字/字母的楼结尾 - return false; - } - return true; - } + private boolean isCorrectAddressPoi(String address, String keyWords) { // 市区镇县省结尾 + if (StringUtils.isEmpty(address)) {// 为空 + return false; + } else if (address.length() < 3) {// 字符少于三个 + return false; + } else if (!keyWords.contains(address)) { + return false; + } else if (StringUtils.isNumeric(address) || isDigit(address)) {// 字符为数字 + return false; + } else if (!isContainsChineseWord(address)) { // 不包含汉字 + return false; + } else if (address.endsWith("省") || address.endsWith("市") || address.endsWith("区") || address.endsWith("县") + || address.endsWith("乡") || address.endsWith("镇") || address.endsWith("村") || address.endsWith("街道")) { // 带数字/字母的楼结尾 + return false; + } + return true; + } - private static boolean isDigit(String content) { - boolean flag = false; - Pattern p = Pattern.compile("^[一|二|三|四|五|六|七|八|九|十]+$"); - Matcher m = p.matcher(content); - if (m.matches()) { - flag = true; - } - return flag; - } + private static boolean isDigit(String content) { + boolean flag = false; + Pattern p = Pattern.compile("^[一|二|三|四|五|六|七|八|九|十]+$"); + Matcher m = p.matcher(content); + if (m.matches()) { + flag = true; + } + return flag; + } - private boolean isContainsChineseWord(String content) { - boolean flag = false; - Pattern p = Pattern.compile("^.*[\\u4E00-\\u9FA5]+.*$"); - Matcher m = p.matcher(content); - if (m.matches()) { - flag = true; - } - return flag; - } + private boolean isContainsChineseWord(String content) { + boolean flag = false; + Pattern p = Pattern.compile("^.*[\\u4E00-\\u9FA5]+.*$"); + Matcher m = p.matcher(content); + if (m.matches()) { + flag = true; + } + return flag; + } - /** - * 地址真实性检查 (高德官方)(非银联) - * - * @return - */ - public Object checkAddressAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } - try { - AddressCheckBo bo = addressService.checkAmapAddress(model.getChooseId(), city, model.getAddress().trim());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatAddressCheckBo3(bo, city, model)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + /** + * 地址真实性检查 (高德官方)(非银联) + * + * @return + */ + public Object checkAddressAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } + try { + AddressCheckBo bo = addressService.checkAmapAddress(model.getChooseId(), city, model.getAddress().trim());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatAddressCheckBo3(bo, city, model)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - /** - * 为返回值格式化掉cityCode和AddressId,用于地址验真(非银联版) - * - * @param bo - * @return - */ - private AddressCheckBo formatAddressCheckBo3(AddressCheckBo bo, String city, AddressModel model) { - AddressCheck check = bo.getData(); - if (null != check) { - check.setCityCode(null); - if (StringUtils.isEmpty(check.getCity()) || "[]".equals(check.getCity())) { - check.setCity(city); - } - // 检查相关参数 - if (FJW_LEVEL.equals(model.getDataLevel())) { - bo.setData(check); - } else { - bo.setData(null); - } - } - if ("不存在".equals(bo.getType())) { - bo.setType("地址未找到:抱歉,在" + city + "没有找到与'" + model.getAddress() + "'相关的地点"); - } - return bo; - } + /** + * 为返回值格式化掉cityCode和AddressId,用于地址验真(非银联版) + * + * @param bo + * @return + */ + private AddressCheckBo formatAddressCheckBo3(AddressCheckBo bo, String city, AddressModel model) { + AddressCheck check = bo.getData(); + if (null != check) { + check.setCityCode(null); + if (StringUtils.isEmpty(check.getCity()) || "[]".equals(check.getCity())) { + check.setCity(city); + } + // 检查相关参数 + if (FJW_LEVEL.equals(model.getDataLevel())) { + bo.setData(check); + } else { + bo.setData(null); + } + } + if ("不存在".equals(bo.getType())) { + bo.setType("地址未找到:抱歉,在" + city + "没有找到与'" + model.getAddress() + "'相关的地点"); + } + return bo; + } - /** - * 为返回值格式化掉cityCode和AddressId,用于评级和反欺诈(非银联版) - * - * @param bo - * @return - */ - private AddressCheckBo formatAddressCheckBo4(AddressCheckBo bo, String city, AddressModel model, String type) { - AddressCheck check = bo.getData(); - if (null != check) { - check.setCityCode(null); - if (StringUtils.isEmpty(check.getCity()) || "[]".equals(check.getCity())) { - check.setCity(city); - } - // 检查相关参数 - if (FJW_LEVEL.equals(model.getDataLevel())) { - bo.setData(check); - } else { - check.setDistrictName(null); - check.setKeyWords(null); - check.setKeyWordsUse(null); - check.setRegion(null); - check.setProvionce(null); - check.setNameUse(null); - check.setAddressUse(null); - check.setAddress2(null); - check.setName2(null); - check.setType(null); - check.setFormatAddress(null); - check.setFormatAddress2(null); - check.setLocation2(null); - check.setAddress(null); - check.setAddressId(null); - check.setName(null); - check.setLevel(null); - if (GRADE_AREA.equals(type)) { - check.setScoreIncity(null); - check.setScoreInnation(null); - } else if (GRADE_CITY.equals(type)) { - double score = check.getScoreIncity(); - check.setScore(score); - check.setScoreIncity(null); - check.setScoreInnation(null); - } else if (GRADE_NATION.equals(type)) { - double score = check.getScoreInnation(); - check.setScore(score); - check.setScoreIncity(null); - check.setScoreInnation(null); - }else if(GRADE_CONSUME.equals(type)) { - check.setScoreIncity(null); - check.setScoreInnation(null); - check.setAreaScore(null); - check.setEstateScore(null); - check.setPriceScore(null); - } - bo.setData(check); - } - } - if ("不存在".equals(bo.getType())) { - bo.setType("地址未找到:抱歉,在" + city + "没有找到与'" + model.getAddress() + "'相关的地点"); - } - return bo; - } + /** + * 为返回值格式化掉cityCode和AddressId,用于评级和反欺诈(非银联版) + * + * @param bo + * @return + */ + private AddressCheckBo formatAddressCheckBo4(AddressCheckBo bo, String city, AddressModel model, String type) { + AddressCheck check = bo.getData(); + if (null != check) { + check.setCityCode(null); + if (StringUtils.isEmpty(check.getCity()) || "[]".equals(check.getCity())) { + check.setCity(city); + } + // 检查相关参数 + if (FJW_LEVEL.equals(model.getDataLevel())) { + bo.setData(check); + } else { + check.setDistrictName(null); + check.setKeyWords(null); + check.setKeyWordsUse(null); + check.setRegion(null); + check.setProvionce(null); + check.setNameUse(null); + check.setAddressUse(null); + check.setAddress2(null); + check.setName2(null); + check.setType(null); + check.setFormatAddress(null); + check.setFormatAddress2(null); + check.setLocation2(null); + check.setAddress(null); + check.setAddressId(null); + check.setName(null); + check.setLevel(null); + if (GRADE_AREA.equals(type)) { + check.setScoreIncity(null); + check.setScoreInnation(null); + } else if (GRADE_CITY.equals(type)) { + double score = check.getScoreIncity(); + check.setScore(score); + check.setScoreIncity(null); + check.setScoreInnation(null); + } else if (GRADE_NATION.equals(type)) { + double score = check.getScoreInnation(); + check.setScore(score); + check.setScoreIncity(null); + check.setScoreInnation(null); + } else if (GRADE_CONSUME.equals(type)) { + check.setScoreIncity(null); + check.setScoreInnation(null); + check.setAreaScore(null); + check.setEstateScore(null); + check.setPriceScore(null); + } + bo.setData(check); + } + } + if ("不存在".equals(bo.getType())) { + bo.setType("地址未找到:抱歉,在" + city + "没有找到与'" + model.getAddress() + "'相关的地点"); + } + return bo; + } - /** - * 地址评级(非银联) - */ - public Object gradeAddressAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + /** + * 地址评级(非银联) + */ + public Object gradeAddressAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } - try { - AddressCheckBo bo = addressService.gradeAmapAddress(model.getChooseId(), city, model.getAddress().trim());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatAddressCheckBo4(bo, city, model, GRADE_AREA)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + try { + AddressCheckBo bo = addressService.gradeAmapAddress(model.getChooseId(), city, model.getAddress().trim());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatAddressCheckBo4(bo, city, model, GRADE_AREA)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - /** - * 地址评级(非银联)(城市评分) - */ - public Object gradeCityAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + /** + * 地址评级(非银联)(城市评分) + */ + public Object gradeCityAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } - try { - AddressCheckBo bo = addressService.gradeAmapAddress(model.getChooseId(), city, model.getAddress().trim());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatAddressCheckBo4(bo, city, model, GRADE_CITY)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + try { + AddressCheckBo bo = addressService.gradeAmapAddress(model.getChooseId(), city, model.getAddress().trim());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatAddressCheckBo4(bo, city, model, GRADE_CITY)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - /** - * 地址评级(非银联)(国家评分) - */ - public Object gradeNationAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + /** + * 地址评级(非银联)(国家评分) + */ + public Object gradeNationAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } - try { - AddressCheckBo bo = addressService.gradeAmapAddress(model.getChooseId(), city, model.getAddress().trim());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatAddressCheckBo4(bo, city, model, GRADE_NATION)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + try { + AddressCheckBo bo = addressService.gradeAmapAddress(model.getChooseId(), city, model.getAddress().trim());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatAddressCheckBo4(bo, city, model, GRADE_NATION)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - /** - * 地址反欺诈 (地址验真+周边查询)(非银联) - */ - public Object antiFraudAddressAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + /** + * 地址反欺诈 (地址验真+周边查询)(非银联) + */ + public Object antiFraudAddressAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } - try { - AddressCheckBo bo = addressService.antiFraudAmapAddress(model.getChooseId(), city, - model.getAddress().trim(), model.getType(), model.getRadius(), model.getNumber(), - model.getPageNo());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatAddressCheckBo4(bo, city, model, null)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + try { + AddressCheckBo bo = addressService.antiFraudAmapAddress(model.getChooseId(), city, + model.getAddress().trim(), model.getType(), model.getRadius(), model.getNumber(), + model.getPageNo());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatAddressCheckBo4(bo, city, model, null)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - /** - * 地址反欺诈 (地址验真+周边查询)(非银联) - */ - public Object antiFraudAddressBAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + /** + * 地址反欺诈 (地址验真+周边查询)(非银联) + */ + public Object antiFraudAddressBAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } - try { - AddressCheckBo bo = addressService.antiFraudAmapAddressB(model.getChooseId(), city, - model.getAddress().trim(), model.getType(), model.getRadius(), model.getNumber());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatAddressCheckBo4(bo, city, model, null)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + try { + AddressCheckBo bo = addressService.antiFraudAmapAddressB(model.getChooseId(), city, + model.getAddress().trim(), model.getType(), model.getRadius(), model.getNumber());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatAddressCheckBo4(bo, city, model, null)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - /** - * 地址真实性检查 (v10版) - * - * @return - */ - public Object checkTruthAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } - try { - AddressCheckTruth tr = addressService.checkTruth(model.getChooseId(), city, model.getAddress().trim());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatCheckTruth(tr, city, model)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + /** + * 地址真实性检查 (v10版) + * + * @return + */ + public Object checkTruthAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } + try { + AddressCheckTruth tr = addressService.checkTruth(model.getChooseId(), city, model.getAddress().trim());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatCheckTruth(tr, city, model)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - private AddressCheckTruth formatCheckTruth(AddressCheckTruth tr, String city, AddressModel model) { - if (null != tr) { - if (StringUtils.isEmpty(tr.getCity()) || "[]".equals(tr.getCity())) { - tr.setCity(city); - } - // 检查相关参数 - if (!FJW_LEVEL.equals(model.getDataLevel())) { - tr.setKeyWords(null); - tr.setKeyWordsUse(null); - tr.setDistrictName(null); - } - } - return tr; - } + private AddressCheckTruth formatCheckTruth(AddressCheckTruth tr, String city, AddressModel model) { + if (null != tr) { + if (StringUtils.isEmpty(tr.getCity()) || "[]".equals(tr.getCity())) { + tr.setCity(city); + } + // 检查相关参数 + if (!FJW_LEVEL.equals(model.getDataLevel())) { + tr.setKeyWords(null); + tr.setKeyWordsUse(null); + tr.setDistrictName(null); + } + } + return tr; + } - /** - * 地址评级(v10) - */ - public Object gradeTruthAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + /** + * 地址评级(v10) + */ + public Object gradeTruthAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } - try { - AddressCheckTruth bo = addressService.gradeTruth(model.getChooseId(), city, model.getAddress().trim());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatGradeTruth(bo, city, model, GRADE_AREA)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + try { + AddressCheckTruth bo = addressService.gradeTruth(model.getChooseId(), city, model.getAddress().trim());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatGradeTruth(bo, city, model, GRADE_AREA)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - /** - * 地址评级(v10)(城市评分) - */ - public Object gradeTruthCityAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + /** + * 地址评级(v10)(城市评分) + */ + public Object gradeTruthCityAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } - try { - AddressCheckTruth bo = addressService.gradeTruth(model.getChooseId(), city, model.getAddress().trim());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatGradeTruth(bo, city, model, GRADE_CITY)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + try { + AddressCheckTruth bo = addressService.gradeTruth(model.getChooseId(), city, model.getAddress().trim());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatGradeTruth(bo, city, model, GRADE_CITY)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - /** - * 地址评级(v10)(国家评分) - */ - public Object gradeTruthNationAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + /** + * 地址评级(v10)(国家评分) + */ + public Object gradeTruthNationAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } - try { - AddressCheckTruth bo = addressService.gradeTruth(model.getChooseId(), city, model.getAddress().trim());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatGradeTruth(bo, city, model, GRADE_NATION)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + try { + AddressCheckTruth bo = addressService.gradeTruth(model.getChooseId(), city, model.getAddress().trim());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatGradeTruth(bo, city, model, GRADE_NATION)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - /** - * 为返回值格式化掉cityCode和AddressId,用于评级和反欺诈(非银联版) - * - * @param tr - * @param city - * @param model - * @param type - * @return - */ - private AddressCheckTruth formatGradeTruth(AddressCheckTruth tr, String city, AddressModel model, String type) { - if (null != tr) { - if (StringUtils.isEmpty(tr.getCity()) || "[]".equals(tr.getCity())) { - tr.setCity(city); - } - // 检查相关参数 - if (!FJW_LEVEL.equals(model.getDataLevel())) { - tr.setKeyWords(null); - tr.setKeyWordsUse(null); - tr.setDistrictName(null); - if (GRADE_AREA.equals(type)) { - tr.setScoreIncity(null); - tr.setScoreInnation(null); - } else if (GRADE_CITY.equals(type)) { - double score = tr.getScoreIncity(); - tr.setScore(score); - tr.setScoreIncity(null); - tr.setScoreInnation(null); - } else if (GRADE_NATION.equals(type)) { - double score = tr.getScoreInnation(); - tr.setScore(score); - tr.setScoreIncity(null); - tr.setScoreInnation(null); - }else if(GRADE_CONSUME.equals(type)) { - tr.setScoreIncity(null); - tr.setScoreInnation(null); - tr.setAreaScore(null); - tr.setEstateScore(null); - tr.setPriceScore(null); - } - } - } - return tr; - } + /** + * 为返回值格式化掉cityCode和AddressId,用于评级和反欺诈(非银联版) + * + * @param tr + * @param city + * @param model + * @param type + * @return + */ + private AddressCheckTruth formatGradeTruth(AddressCheckTruth tr, String city, AddressModel model, String type) { + if (null != tr) { + if (StringUtils.isEmpty(tr.getCity()) || "[]".equals(tr.getCity())) { + tr.setCity(city); + } + // 检查相关参数 + if (!FJW_LEVEL.equals(model.getDataLevel())) { + tr.setKeyWords(null); + tr.setKeyWordsUse(null); + tr.setDistrictName(null); + if (GRADE_AREA.equals(type)) { + tr.setScoreIncity(null); + tr.setScoreInnation(null); + } else if (GRADE_CITY.equals(type)) { + double score = tr.getScoreIncity(); + tr.setScore(score); + tr.setScoreIncity(null); + tr.setScoreInnation(null); + } else if (GRADE_NATION.equals(type)) { + double score = tr.getScoreInnation(); + tr.setScore(score); + tr.setScoreIncity(null); + tr.setScoreInnation(null); + } else if (GRADE_CONSUME.equals(type)) { + tr.setScoreIncity(null); + tr.setScoreInnation(null); + tr.setAreaScore(null); + tr.setEstateScore(null); + tr.setPriceScore(null); + } + } + } + return tr; + } - /** - * 地址反欺诈 (地址验真+周边查询)(v10) - */ - public Object antiFraudTruthAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + /** + * 地址反欺诈 (地址验真+周边查询)(v10) + */ + public Object antiFraudTruthAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } - try { - AddressCheckTruth tr = addressService.antiFraudTruth(model.getChooseId(), city, model.getAddress().trim(), - model.getType(), model.getRadius(), model.getNumber(), model.getPageNo());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatCheckTruth(tr, city, model)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + try { + AddressCheckTruth tr = addressService.antiFraudTruth(model.getChooseId(), city, model.getAddress().trim(), + model.getType(), model.getRadius(), model.getNumber(), model.getPageNo());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatCheckTruth(tr, city, model)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - /** - * 地址反欺诈 (地址验真+周边查询)(v10) - */ - public Object antiFraudTruthBAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + /** + * 地址反欺诈 (地址验真+周边查询)(v10) + */ + public Object antiFraudTruthBAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } - try { - AddressCheckTruth tr = addressService.antiFraudTruthB(model.getChooseId(), city, model.getAddress().trim(), - model.getType(), model.getRadius(), model.getNumber());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatCheckTruth(tr, city, model)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } - - /** - * 地址线下消费评级 - * @param model - * @return - */ - @Deprecated - public Object gradeConsumeOfflineAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + try { + AddressCheckTruth tr = addressService.antiFraudTruthB(model.getChooseId(), city, model.getAddress().trim(), + model.getType(), model.getRadius(), model.getNumber());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatCheckTruth(tr, city, model)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - try { - AddressCheckBo bo = addressService.gradeConsumeOffline(model.getChooseId(), city, model.getAddress().trim());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatAddressCheckBo4(bo, city, model, GRADE_CONSUME)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } - - /** - * 地址消费评级(v10) - */ - @Deprecated - public Object gradeConsumeTruthAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + /** + * 地址线下消费评级 + * + * @param model + * @return + */ + @Deprecated + public Object gradeConsumeOfflineAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } - try { - AddressCheckTruth bo = addressService.gradeConsumeTruth(model.getChooseId(), city, model.getAddress().trim());// check是走代理 - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(formatGradeTruth(bo, city, model, GRADE_CONSUME)); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + try { + AddressCheckBo bo = addressService.gradeConsumeOffline(model.getChooseId(), city, model.getAddress().trim());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatAddressCheckBo4(bo, city, model, GRADE_CONSUME)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - /** - * 地址周边消费评级接口 - *

通过用户输入的地址,得到该地址的经纬度,找到该地址附近的三个非商住小区的小区消费评级评分,取一个平均分。

- * @author yinjihuyan - * @param model - * @return - */ - public Object aroundConsumeGradeAction(AddressModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); - return mav; - } - // 查询城市是否高德支持 - String city = addressService.findCityAmap(model.getCity().trim()); - if (StringUtils.isEmpty(city)) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); - return mav; - } + /** + * 地址消费评级(v10) + */ + @Deprecated + public Object gradeConsumeTruthAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } - try { - AddressCheckTruth truth = addressService.aroundConsumeGrade(city, model.getAddress()); - if ("F".equals(truth.getLevel())) { - mav.setModel(BasicModel.buildBadRequestModel(truth.getCheckMsg())); - return mav; - } - AroundConsumeGradeBo bo = new AroundConsumeGradeBo(); - bo.setCity(truth.getCity()); - bo.setDistrict(truth.getDistrict()); - bo.setScore(truth.getScore()); - bo.setRegionScore(truth.getRegionScore()); - bo.setLng(truth.getLng()); - bo.setLat(truth.getLat()); - if (FJW_LEVEL.equals(model.getDataLevel())) { - bo.setDistrictNames(truth.getDistrictName()); - } - BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); - model1.setResult(bo); - mav.setModel(model1); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); - } - return mav; - } + try { + AddressCheckTruth bo = addressService.gradeConsumeTruth(model.getChooseId(), city, model.getAddress().trim());// check是走代理 + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(formatGradeTruth(bo, city, model, GRADE_CONSUME)); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } - @Authority(role = Role.USER) - public Object riskAction(AddesssMatchModel model) { - RestfulModelAndView mav = new RestfulModelAndView(); + /** + * 地址周边消费评级接口 + *

通过用户输入的地址,得到该地址的经纬度,找到该地址附近的三个非商住小区的小区消费评级评分,取一个平均分。

+ * + * @param model + * @return + * @author yinjihuyan + */ + public Object aroundConsumeGradeAction(AddressModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isEmpty(model.getCity()) || StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市和地址不能为空!")); + return mav; + } + // 查询城市是否高德支持 + String city = addressService.findCityAmap(model.getCity().trim()); + if (StringUtils.isEmpty(city)) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市输入不标准!")); + return mav; + } + + try { + AddressCheckTruth truth = addressService.aroundConsumeGrade(city, model.getAddress()); + if ("F".equals(truth.getLevel())) { + mav.setModel(BasicModel.buildBadRequestModel(truth.getCheckMsg())); + return mav; + } + AroundConsumeGradeBo bo = new AroundConsumeGradeBo(); + bo.setCity(truth.getCity()); + bo.setDistrict(truth.getDistrict()); + bo.setScore(truth.getScore()); + bo.setRegionScore(truth.getRegionScore()); + bo.setLng(truth.getLng()); + bo.setLat(truth.getLat()); + if (FJW_LEVEL.equals(model.getDataLevel())) { + bo.setDistrictNames(truth.getDistrictName()); + } + BasicModel model1 = new BasicModel(HttpStatusCodeEnum.OK); + model1.setResult(bo); + mav.setModel(model1); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + mav.setModel(BasicModel.buildBadRequestModel("网络异常,建议再次请求!")); + } + return mav; + } + + @Authority(role = Role.USER) + public Object riskAction(AddesssMatchModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); // if (StringUtils.isEmpty(model.getCity())) { // mav.setModel(BasicModel.buildBadRequestModel("参数错误,城市不能为空!")); // return mav; // } - if (StringUtils.isEmpty(model.getAddress())) { - mav.setModel(BasicModel.buildBadRequestModel("参数错误,地址不能为空!")); - return mav; - } - BasicModel resultModel = new BasicModel(HttpStatusCodeEnum.OK); - Map resultMap = new HashMap(); - try { - Map params = new HashMap(); - if (StringUtils.isNotBlank(model.getCity())) { - params.put("city", model.getCity()); - } - params.put("address", model.getAddress()); - params.put("useMap", "false"); - String result = addressMatchProxyService.parser(params); - if (result != null) { - JSONObject json = JSONObject.fromObject(result); - if (json.getInt("code") == 200) { - JSONObject resultJson = json.getJSONObject("result"); - JSONObject searchAddress = resultJson.getJSONObject("searchAddress"); - if (resultJson.getDouble("credit") > 0) { - District district = districtService.findByNameAndAlias(resultJson.getString("city"), resultJson.getString("district"), resultJson.getString("name"), "district"); - if (district != null) { - resultMap.put("riskLevel", "A"); - resultModel.setResult(resultMap); - mav.setModel(resultModel); - return mav; - } - } - StringBuffer searchKey = new StringBuffer(); - if (searchAddress.containsKey("street")) { - searchKey.append(searchAddress.getString("street")); - } - if (searchAddress.containsKey("streetNumber")) { - searchKey.append(searchAddress.getString("streetNumber")); - } - if (StringUtils.isNotBlank(searchKey.toString()) && searchAddress.has("city") && StringUtils.isNotBlank(searchAddress.getString("city"))) { + if (StringUtils.isEmpty(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("参数错误,地址不能为空!")); + return mav; + } + BasicModel resultModel = new BasicModel(HttpStatusCodeEnum.OK); + Map resultMap = new HashMap(); + try { + Map params = new HashMap(); + if (StringUtils.isNotBlank(model.getCity())) { + params.put("city", model.getCity()); + } + params.put("address", model.getAddress()); + params.put("useMap", "false"); + String result = addressMatchProxyService.parser(params); + if (result != null) { + JSONObject json = JSONObject.fromObject(result); + if (json.getInt("code") == 200) { + JSONObject resultJson = json.getJSONObject("result"); + JSONObject searchAddress = resultJson.getJSONObject("searchAddress"); + if (resultJson.getDouble("credit") > 0) { + District district = districtService.findByNameAndAlias(resultJson.getString("city"), resultJson.getString("district"), resultJson.getString("name"), "district"); + if (district != null) { + resultMap.put("riskLevel", "A"); + resultModel.setResult(resultMap); + mav.setModel(resultModel); + return mav; + } + } + StringBuffer searchKey = new StringBuffer(); + if (searchAddress.containsKey("street")) { + searchKey.append(searchAddress.getString("street")); + } + if (searchAddress.containsKey("streetNumber")) { + searchKey.append(searchAddress.getString("streetNumber")); + } + if (StringUtils.isNotBlank(searchKey.toString()) && searchAddress.has("city") && StringUtils.isNotBlank(searchAddress.getString("city"))) { // JSONObject jsonObject = addressMatchProxyService.searchByAmap(searchAddress.getString("city"), model.getAddress()); // JSONArray poisData = jsonObject.getJSONArray("pois"); // for (int i = 0; i < poisData.size(); i++) { @@ -3336,120 +3341,120 @@ public class AddressController { // continue; // } // } - String city = searchAddress.getString("city"); - List poiList = this.findPois(city, searchKey.toString()); - if (CollectionUtils.isNotEmpty(poiList)) { - resultMap.put("riskLevel", "A"); - } else { - resultMap.put("riskLevel", "B"); - } - resultModel.setResult(resultMap); - mav.setModel(resultModel); - return mav; - } - } - } - } catch (Exception ex) { - LOGGER.error("风险识别出错:" + ex.getMessage(), ex); - } + String city = searchAddress.getString("city"); + List poiList = this.findPois(city, searchKey.toString()); + if (CollectionUtils.isNotEmpty(poiList)) { + resultMap.put("riskLevel", "A"); + } else { + resultMap.put("riskLevel", "B"); + } + resultModel.setResult(resultMap); + mav.setModel(resultModel); + return mav; + } + } + } + } catch (Exception ex) { + LOGGER.error("风险识别出错:" + ex.getMessage(), ex); + } - resultMap.put("riskLevel","C"); - resultModel.setResult(resultMap); - mav.setModel(resultModel); - return mav; - } + resultMap.put("riskLevel", "C"); + resultModel.setResult(resultMap); + mav.setModel(resultModel); + return mav; + } - private List findPois(String city, String address) { - JSONObject reqBody = new JSONObject(); - reqBody.put("from", 0); - reqBody.put("size", 1); - JSONObject query = new JSONObject(); - JSONObject bool = new JSONObject(); - JSONArray must = new JSONArray(); - must.add(addTerm("city", city)); - must.add(addMatchPhrase("address", address)); - bool.put("must", must); - query.put("bool", bool); - reqBody.put("query", query); - Base64 token = new Base64(); - String authenticationEncoding = token.encodeAsString((""+ES_USER+":"+ES_PASSWORD+"").getBytes()); - HttpRequest request = new HttpRequest(); - Map headers = new HashMap(); - headers.put("Content-Type", "application/json"); - headers.put("Authorization", "Basic "+authenticationEncoding+""); - try { - String response = request.postWithBody("http://192.168.0.45:9200/association/_search", reqBody, headers, "UTF-8"); - JSONObject json = JSONObject.fromObject(response); - if(!json.containsKey("hits") || !json.getJSONObject("hits").containsKey("hits")){ - return Collections.emptyList(); - } - JSONArray hits = json.getJSONObject("hits").getJSONArray("hits"); - List results = new ArrayList(); - for(int i=0 ;i < hits.size(); i++){ - JSONObject jsonObject = hits.getJSONObject(i); - results.add(jsonObject); - } - return results; + private List findPois(String city, String address) { + JSONObject reqBody = new JSONObject(); + reqBody.put("from", 0); + reqBody.put("size", 1); + JSONObject query = new JSONObject(); + JSONObject bool = new JSONObject(); + JSONArray must = new JSONArray(); + must.add(addTerm("city", city)); + must.add(addMatchPhrase("address", address)); + bool.put("must", must); + query.put("bool", bool); + reqBody.put("query", query); + Base64 token = new Base64(); + String authenticationEncoding = token.encodeAsString(("" + ES_USER + ":" + ES_PASSWORD + "").getBytes()); + HttpRequest request = new HttpRequest(); + Map headers = new HashMap(); + headers.put("Content-Type", "application/json"); + headers.put("Authorization", "Basic " + authenticationEncoding + ""); + try { + String response = request.postWithBody("http://192.168.0.45:9200/association/_search", reqBody, headers, "UTF-8"); + JSONObject json = JSONObject.fromObject(response); + if (!json.containsKey("hits") || !json.getJSONObject("hits").containsKey("hits")) { + return Collections.emptyList(); + } + JSONArray hits = json.getJSONObject("hits").getJSONArray("hits"); + List results = new ArrayList(); + for (int i = 0; i < hits.size(); i++) { + JSONObject jsonObject = hits.getJSONObject(i); + results.add(jsonObject); + } + return results; - } catch (HttpRequestException e) { - e.printStackTrace(); - } - return Collections.emptyList(); - } + } catch (HttpRequestException e) { + e.printStackTrace(); + } + return Collections.emptyList(); + } - public void setAddressService(AddressService addressService) { - this.addressService = addressService; - } + public void setAddressService(AddressService addressService) { + this.addressService = addressService; + } - public void setEvaluationService(EvaluationService evaluationService) { - this.evaluationService = evaluationService; - } + public void setEvaluationService(EvaluationService evaluationService) { + this.evaluationService = evaluationService; + } - public void setDistrictService(DistrictService districtService) { - this.districtService = districtService; - } + public void setDistrictService(DistrictService districtService) { + this.districtService = districtService; + } - public void setCommDataService(CommDataService commDataService) { - this.commDataService = commDataService; - } + public void setCommDataService(CommDataService commDataService) { + this.commDataService = commDataService; + } - public void setRegionBlockService(RegionBlockService regionBlockService) { - this.regionBlockService = regionBlockService; - } + public void setRegionBlockService(RegionBlockService regionBlockService) { + this.regionBlockService = regionBlockService; + } - public void setBaiduApiService(BaiduApiService baiduApiService) { - this.baiduApiService = baiduApiService; - } + public void setBaiduApiService(BaiduApiService baiduApiService) { + this.baiduApiService = baiduApiService; + } - public void setAddressParser(AddressParser addressParser) { - this.addressParser = addressParser; - } + public void setAddressParser(AddressParser addressParser) { + this.addressParser = addressParser; + } - public void setServerAreaService(ServerAreaService serverAreaService) { - this.serverAreaService = serverAreaService; - } + public void setServerAreaService(ServerAreaService serverAreaService) { + this.serverAreaService = serverAreaService; + } - public AddressParserService getAddressParserService() { - return addressParserService; - } + public AddressParserService getAddressParserService() { + return addressParserService; + } - public void setAddressParserService(AddressParserService addressParserService) { - this.addressParserService = addressParserService; - } + public void setAddressParserService(AddressParserService addressParserService) { + this.addressParserService = addressParserService; + } - public void setWaitCrawlKeywordsService(WaitCrawlKeywordsService waitCrawlKeywordsService) { - this.waitCrawlKeywordsService = waitCrawlKeywordsService; - } + public void setWaitCrawlKeywordsService(WaitCrawlKeywordsService waitCrawlKeywordsService) { + this.waitCrawlKeywordsService = waitCrawlKeywordsService; + } - public void setFjtEvaluationService(FjtEvaluationService fjtEvaluationService) { - this.fjtEvaluationService = fjtEvaluationService; - } + public void setFjtEvaluationService(FjtEvaluationService fjtEvaluationService) { + this.fjtEvaluationService = fjtEvaluationService; + } - public void setHouseLoudongService(HouseLoudongService houseLoudongService) { - this.houseLoudongService = houseLoudongService; - } + public void setHouseLoudongService(HouseLoudongService houseLoudongService) { + this.houseLoudongService = houseLoudongService; + } - public void setAddressMatchProxyService(AddressMatchProxyService addressMatchProxyService) { - this.addressMatchProxyService = addressMatchProxyService; - } + public void setAddressMatchProxyService(AddressMatchProxyService addressMatchProxyService) { + this.addressMatchProxyService = addressMatchProxyService; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/ComprehensiveQueryController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/ComprehensiveQueryController.java new file mode 100644 index 000000000..9d891b609 --- /dev/null +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/ComprehensiveQueryController.java @@ -0,0 +1,1359 @@ +package com.fangjia.open.controllers; + +import com.fangjia.core.util.*; +import com.fangjia.dal.mongo.model.AdministrativeDivision; +import com.fangjia.dal.common.DistrictKey; +import com.fangjia.dal.mongo.fangjia.model.ServerArea; +import com.fangjia.dal.mongo.model.ApiUserCfg; +import com.fangjia.dal.mongo.model.DistrictFacilitys; +import com.fangjia.dal.mongo.model.Evaluation; +import com.fangjia.dal.mongo.model.bkoff.Loudong; +import com.fangjia.dal.mongo.open.model.ApiUserAuthority; +import com.fangjia.dal.mongo.open.model.EvaluateRatio; +import com.fangjia.dal.seaweed.model.District; +import com.fangjia.open.dto.HouseValueInformationDto; +import com.fangjia.open.dto.UniversalDto; +import com.fangjia.open.dto.addressGovernance.MatchedBuildingDto; +import com.fangjia.open.interceptors.AuthenticationBean; +import com.fangjia.open.interceptors.Authority; +import com.fangjia.open.interceptors.Role; +import com.fangjia.open.model.*; +import com.fangjia.open.util.CommonDtoUtils; +import com.fangjia.open.util.CommonUtils; +import com.fangjia.open.ws.query.SampleQuery; +import com.fangjia.service.api.AddressMatchProxyService; +import com.fangjia.service.api.ApiUserCfgService; +import com.fangjia.service.bo.Collateral; +import com.fangjia.service.bo.DistrictStatBo; +import com.fangjia.service.bo.Sample; +import com.fangjia.service.datastore.*; +import com.fangjia.service.datastore.bean.CollateralSampleQueryBean; +import com.fangjia.service.district.*; +import com.fangjia.service.mongo.bkoff.HouseLoudongService; +import com.fangjia.service.mongo.bkoff.LoudongService; +import com.fangjia.service.mongo.fangjia.*; +import com.fangjia.service.open.*; +import com.fangjia.service.web.AddressService; +import net.sf.json.JSONObject; +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.time.DateUtils; +import org.slf4j.Logger; +import org.sothis.web.mvc.ActionContext; + +import javax.servlet.http.HttpServletRequest; +import java.text.ParseException; +import java.util.*; + +import static com.poseidon.util.TypeConverter.convertToString; + +/** + * @author 13607 + * @since 2023/12/12 10:29 + */ +@Authority(role = Role.USER) +public class ComprehensiveQueryController { + private DistrictService districtService; + + private DistrictStatService districtStatService; + + private FangjiaOfficialAreaService fangjiaOfficialAreaService; + private AddressMatchProxyService addressMatchProxyService; + + private static final Logger LOGGER = LoggerFactory.getLogger(PropertyController.class); + private HouseLoudongService houseLoudongService; + private LoudongService loudongService; + private EvaluationService evaluationService; + private BatchEvaluateService batchEvaluateService; + private ApiUserAuthorityService apiUserAuthorityService; + private AverageStatisticsService averageStatisticsService; + private ServerAreaService serverAreaService; + private ApiUserCfgService apiUserCfgService; + private OpenApiLogService openApiLogService; + private EvaluateFactorService evaluateFactorService; + + private CzbankSampleService czbankSampleService; + + private DistrictFacilitysService districtFacilitysService; + + private static final int DEFAULT_PAGE_SIZE = 20; + private static final String[] PROPERTY_SEARCH_API_FIELDS = {"address", "city", "region", "name", "lat2", "lng2", "lat", "lng", "block", "estateType2", "addrAlias"}; + static final int BAI_DU_GEO = 1;// 百度系坐标 + static final int GAO_DE_GEO = 2;// 高德系坐标 + + private AdministrativeDivisionService administrativeDivisionService; + + + private EvaluateRatioService evaluateRatioService; + + private static final int EVALUATE_SHOW_DETAIL = 1; + private static final Map PROPERTY_TYPES = new HashMap() { + { + put(null, "普通住宅"); + put("0", "普通住宅"); + put("1", "别墅"); + put("2", "商住"); + } + }; + + private static final Map DIRECTION = new HashMap() { + { + put(null, "南"); + put("1", "西南"); + put("2", "东南"); + put("3", "南"); + put("4", "西北"); + put("5", "东北"); + put("6", "东"); + put("7", "西"); + put("8", "北"); + put("9", "东西"); + put("10", "南北"); + } + }; + + private static final Map FITMENT = new HashMap() { + { + put(null, "简装"); + put("1", "毛坯"); + put("2", "简装"); + put("3", "精装"); + put("4", "豪装"); + } + }; + + private static final Map EVALUATION_MODEL_FITMENT = new HashMap() { + { + put(null, "简单装修"); + put("简装", "简单装修"); + put("毛坯", "毛坯"); + put("精装", "精装修"); + put("豪装", "豪华装修"); + } + }; + + private static final Map SIGHT = new HashMap() { + { + put(null, "一般"); + put("1", "景观房"); + put("2", "侧景观房"); + put("3", "一般"); + put("4", "差"); + } + }; + + private static final Map NOISE = new HashMap() { + { + put(null, "无噪音"); + put("0", "无噪音"); + put("1", "噪音较小"); + put("2", "噪音大"); + } + }; + private static final Map FACILITIES = new HashMap() { + { + put("0", "健身房"); + put("1", "游泳池"); + put("2", "会所"); + put("3", "网球场"); + put("4", "球场"); + put("5", "棋牌室"); + put("6", "停车场"); + put("7", "图书馆"); + put("8", "活动中心"); + } + }; + + private static final Map NEGATIVE_FACTOR = new HashMap() { + { + put(null, "无"); + put("1", "很近"); + put("2", "较近"); + put("3", "无"); + } + }; + + + Map listKeyMap = new HashMap() { + { + put("school", "schools"); + put("hospital", "hospitals"); + put("bank", "banks"); + put("supermarket", "supermarkets"); + put("market", "markets"); + put("beautySalon", "beautySalons"); + put("gym", "gyms"); + put("park", "parks"); + put("bus", "buses"); + put("metro", "metros"); + put("dock", "docks"); + put("airport", "airports"); + put("trainStation", "trainStations"); + put("restaurant", "restaurants"); + put("hotel", "hotels"); + } + }; + + private static final Map CITYLEVEL_MAP = new HashMap() { + { + put("1000", "one");// 一线 + put("1500", "newOne");// 新一线 + put("2000", "two");// 二线 + put("3000", "three");// 三线 + put("4000", "four");// 四线 + put("5000", "five");// 五线 + } + }; + + public Object houseValueInformationAction(HouseInfomationModel model, HttpServletRequest httpServletRequest) { + + // 原小区均价 + HouseValueInformationDto houseValueInformation = new HouseValueInformationDto(); + RestfulModelAndView mav = new RestfulModelAndView(); + + if (StringUtils.isBlank(model.getAddress()) || StringUtils.isBlank(String.valueOf(model.getSize()))) { + mav.setModel(BasicModel.buildBadRequestModel("地址(address),面积(size)为必填字段")); + return mav; + } + + String cityStr = model.getCity(); + if (StringUtils.isNotBlank(cityStr) && cityStr.matches("\\d+")) { + AdministrativeDivision administrativeDivision = administrativeDivisionService.findcityByCode(cityStr); + String city = administrativeDivision.getCityShort(); + if (StringUtils.isBlank(city)) { + mav.setModel(BasicModel.buildBadRequestModel("城市代码错误")); + return mav; + } + model.setCity(city); + } + + HttpRequest httpRequest = new HttpRequest(); + JSONObject json = null; + Map communityAvgPriceParams = new HashMap(); + communityAvgPriceParams.put("city", model.getCity()); + communityAvgPriceParams.put("address", model.getAddress()); + communityAvgPriceParams.put("category", model.getCategory()); +// communityAvgPriceParams.put("useMap", String.valueOf(model.isUseMap())); + communityAvgPriceParams.put("suggestName", String.valueOf(model.getName())); + communityAvgPriceParams.put("preciseLevel", "strict"); + communityAvgPriceParams.put("token", "F54F52381C49BB9EB4A33EB1B65604AE4B71A28AEE53518A94A2F360408B9056D57553931D15CE6DDE765562DAD286BA38E05A4CDAFC51C3D527A4959BF8E75A3B95DB7108FCEA340DDE61925616DB55118E1851E67D83EAD800460D100D6B667A4ED8EE67C8F7FB"); + JSONObject matchResponse = null; + try { + matchResponse = httpRequest.getJsonContent("http://open.fangjia.com/address/match", communityAvgPriceParams, "UTF-8"); +// matchResponse = httpRequest.getJsonContent("http://192.168.0.19:31080/FangJiaAddressService/v2/match", communityAvgPriceParams, "UTF-8"); + } catch (HttpRequestException e) { + + } + if (matchResponse == null || !matchResponse.containsKey("result") || !matchResponse.getJSONObject("result").containsKey("id")) { + mav.setModel(BasicModel.buildBadRequestModel("该地址不支持估价!")); + return mav; + } + String id = matchResponse.getJSONObject("result").getString("id"); + District district = districtService.findById(id); + if (district == null) { + mav.setModel(BasicModel.buildBadRequestModel("该地址不支持估价!")); + return mav; + } + + MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, matchResponse.getJSONObject("result")); + DistrictStatBo statBo = districtStatService.findCurrentDistrictStat(new DistrictKey(district)); + if (null != statBo) { + if (statBo.getDistrictStat() != null) { + // 有2B价格,使用2B价格 + Integer avgPrice2b = statBo.getDistrictStat().getAvg_price_2b(); + if (avgPrice2b != null && avgPrice2b > 0) { + dto.setAvgPrice(avgPrice2b); + } else { + dto.setAvgPrice(statBo.getDistrictStat().getAvgPrice()); + } + } else if (statBo.getVillaDistrictStat() != null) { + // 有2B价格,使用2B价格 + Integer avgPrice2b = statBo.getVillaDistrictStat().getAvg_price_2b(); + if (avgPrice2b != null && avgPrice2b > 0) { + dto.setAvgPrice(avgPrice2b); + } else { + dto.setAvgPrice(statBo.getVillaDistrictStat().getAvgPrice()); + } + } + + } + // 保存小区均价的返回结果 + houseValueInformation.setCommunityAvgPrice(dto); + + //原房屋价值评估 + //根据model给PropertyEvaluationModel赋值 + PropertyEvaluationModel propertyEvaluationModel = createPropertyEvaluationModelFromHouseInfomationModel(model); + boolean villaFlag = DataUtil.isVilla(propertyEvaluationModel.getSize(), propertyEvaluationModel.getName(), propertyEvaluationModel.getHeight(), propertyEvaluationModel.getRoom()); + String propertyType = district.getEstateType2(); + if (villaFlag && StringUtils.isNotBlank(propertyType) && !propertyType.equals("别墅")) { + District bieShuDistrict = districtService.findByNameAndAlias(district.getCity(), district.getRegion(), district.getName() + "别墅", "district"); + if (bieShuDistrict != null) { + district = bieShuDistrict; + } + } + //添加城市 + propertyEvaluationModel.setCity(district.getCity()); + propertyEvaluationModel.setDistrict(district.getRegion()); + propertyEvaluationModel.setName(district.getName()); + try { + evaluateAction(propertyEvaluationModel, httpServletRequest, houseValueInformation, mav); + } catch (IllegalAccessException e) { + + } +// houseValueInformation.setAddressValue(modelAndView); + + //房源样本 + + //构造sampleQuery对象 + SampleQuery sampleQuery = new SampleQuery(); + sampleQuery.setCity(model.getCity()); + sampleQuery.setStrctureArea(model.getSize()); + sampleQuery.setAddress(model.getAddress()); + +// RestfulModelAndView houseCaseMav = new RestfulModelAndView(); + List querys = null; + try { + querys = convertSampileQueryToBean(district, sampleQuery); + } catch (Exception e) { + mav.setModel(BasicModel.buildBadRequestModel(e.getMessage())); + return mav; + } + if (null == sampleQuery.getMax()) { + sampleQuery.setMax(10); + } + // 此处慢 + long start = System.currentTimeMillis(); + List collaterals = czbankSampleService.findSample2(querys, sampleQuery.getMax()); + long end = System.currentTimeMillis(); + System.out.println("用时:" + (end - start)); + Collateral collateral = collaterals.get(0); + List samples = collateral.getSample(); + UniversalDto houseCaseDto = UniversalDto.newDto(); + if (null != collateral.getMaxPrice()) { + houseCaseDto.append("maxUnitPrice", collateral.getMaxPrice()); + } + if (null != collateral.getMinPrice()) { + houseCaseDto.append("minUnitPrice", collateral.getMinPrice()); + } + houseCaseDto.append("datas", samples); +// if(samples!= null && samples.size()>=2){ +// Sample minSample = samples.get(samples.size()-2); +// Sample maxSample = samples.get(samples.size()-1); +// dto.append("minUnitPrice", minSample.getUnitPrice()); +// dto.append("maxUnitPrice", maxSample.getUnitPrice()); +// } +// if(samples.size()>2){ +// dto.append("datas", samples.subList(0, samples.size()-2)); +// }else{ +// dto.append("datas", samples); +// } + +// houseCaseMav.setModel(BasicModel.buildOKModel().setResult(dto)); +// return houseCaseMav; + + //将房源数据放到结果集 + houseValueInformation.setHouseCase(houseCaseDto); + + // 原周边POI + DistrictFacilitys facilitys = districtFacilitysService.findByDistrict(district); + // 将周边POI数据放到结果集 + houseValueInformation.setSurroundingPoi(facilitys); + mav.setModel(BasicModel.buildOKModel().setResult(houseValueInformation)); + return mav; + } + + private PropertyEvaluationModel createPropertyEvaluationModelFromHouseInfomationModel(HouseInfomationModel model) { + PropertyEvaluationModel propertyModel = new PropertyEvaluationModel(); + propertyModel.setCity(model.getCity()); + propertyModel.setAddress(model.getAddress()); + propertyModel.setSize(model.getSize()); + + if (StringUtils.isNotBlank(model.getDistrict())) { + propertyModel.setDistrict(model.getDistrict()); + } + if (StringUtils.isNotBlank(model.getName())) { + propertyModel.setName(model.getName()); + } + if (StringUtils.isNotBlank(model.getBuildingNumber())) { + propertyModel.setBuildingNumber(model.getBuildingNumber()); + } + if (StringUtils.isNotBlank(model.getUnitNumber())) { + propertyModel.setUnitNumber(model.getUnitNumber()); + } + if (model.getFloor() != null && model.getFloor() != 0) { + propertyModel.setFloor(model.getFloor()); + } + if (model.getMaxFloor() != null && model.getMaxFloor() != 0) { + propertyModel.setMaxFloor(model.getMaxFloor()); + } + if (model.getRoom() != null && model.getRoom() != 0) { + propertyModel.setRoom(model.getRoom()); + } + if (model.getHall() != 0) { + propertyModel.setHall(model.getHall()); + } + if (model.getToilet() != 0) { + propertyModel.setToilet(model.getToilet()); + } + if (model.getCalDate() != null) { + propertyModel.setCalDate(model.getCalDate()); + } + if (model.getPropertyType() != null) { + propertyModel.setPropertyType(model.getPropertyType()); + } + if (StringUtils.isNotBlank(model.getDirection())) { + propertyModel.setDirection(model.getDirection()); + } + if (StringUtils.isNotBlank(model.getDecoration())) { + propertyModel.setDecoration(model.getDecoration()); + } + + if (model.getDecorationCost() != null && model.getDecorationCost() != 0) { + propertyModel.setDecorationCost(model.getDecorationCost()); + } + + if (model.getDecorationAge() != 0) { + propertyModel.setDecorationAge(model.getDecorationAge()); + } + if (StringUtils.isNotBlank(model.getView())) { + propertyModel.setView(model.getView()); + } + if (StringUtils.isNotBlank(model.getNoise())) { + propertyModel.setNoise(model.getNoise()); + } + if (model.getGardenSize() != null && model.getGardenSize() != 0) { + propertyModel.setGardenSize(model.getGardenSize()); + } + if (model.getBasementSize() != null && model.getBasementSize() != 0) { + propertyModel.setBasementSize(model.getBasementSize()); + } + if (model.getOuterSize() != null && model.getOuterSize() != 0) { + propertyModel.setOuterSize(model.getOuterSize()); + } + if (model.getAtticSize() != null && model.getAtticSize() != 0) { + propertyModel.setAtticSize(model.getAtticSize()); + } + if (StringUtils.isNotBlank(model.getNegativeFactor())) { + propertyModel.setNegativeFactor(model.getNegativeFactor()); + } + if (model.getAge() != 0) { + propertyModel.setAge(model.getAge()); + } + if (model.getCarportPrice() != null && model.getCarportPrice() != 0) { + propertyModel.setCarportPrice(model.getCarportPrice()); + } + + if (StringUtils.isNotBlank(model.getFacilities())) { + propertyModel.setFacilities(model.getFacilities()); + } + if (StringUtils.isNotBlank(model.getInsidePosition())) { + propertyModel.setInsidePosition(model.getInsidePosition()); + } + return propertyModel; + } + + private List convertSampileQueryToBean(District district, SampleQuery... queries) throws Exception { + + List queryBeans = new ArrayList(queries.length); + for (SampleQuery q : queries) { + + CollateralSampleQueryBean queryBean = new CollateralSampleQueryBean(); + BeanUtils.copyProperties(q, queryBean); + queryBean.setProperty(district); + String estateType = queryBean.getProperty().getEstateType2(); + queryBean.setPropertyTypeCode("01"); + if (StringUtils.isNotBlank(estateType)) { + if (estateType.equals("普通住宅")) { + queryBean.setPropertyTypeCode("01"); + } else if (estateType.equals("别墅")) { + queryBean.setPropertyTypeCode("02"); + } else if (estateType.equals("商住")) { + queryBean.setPropertyTypeCode("03"); + } + } + + Integer decrCondCode = queryBean.getDecrCondCode(); + if (decrCondCode == null) { + decrCondCode = 2; + } + if (decrCondCode > 5 || decrCondCode < 1) { + throw new Exception("decrCondCode取值非法"); + } + Integer towardDirectCode = queryBean.getTowardDirectCode(); + if (towardDirectCode == null) { + towardDirectCode = 3; + } + if (towardDirectCode > 10 || towardDirectCode < 1) { + throw new Exception("towardDirectCode取值非法"); + } + queryBeans.add(queryBean); + } + return queryBeans; + } + + private void adjustPriceByRatio(District district, Evaluation evaluation) { + + try { + ApiUserCfg apiUserCfg_pt = apiUserCfgService.findByUserId(Long.valueOf(evaluation.getFromUserId()), ApiUserCfg.ApiUserCfgKey.PRICE_TYPE); + if (apiUserCfg_pt != null && apiUserCfg_pt.getCfgValue() != null) { + String priceType = apiUserCfg_pt.getCfgValue().toString(); + // 评估价则系数调整 + if (StringUtils.isNotBlank(priceType) && "evaluate".equals(priceType)) { + EvaluateRatio evaluateRatio = null; + if (StringUtils.isNotBlank(district.getRegion())) { + evaluateRatio = evaluateRatioService.findByCityAndRegion(district.getCity(), district.getRegion()); + } + if (evaluateRatio == null) { + evaluateRatio = evaluateRatioService.findByCity(district.getCity()); + } + if (evaluateRatio != null) { + // 系数添加 + long totalPrice = evaluation.getBigTotalPrice(); + totalPrice = (long) (totalPrice * (1 + evaluateRatio.getRatio())); + evaluation.setBigTotalPrice(totalPrice); + evaluation.setAvgPrice((int) (totalPrice / evaluation.getArea())); + } + } + } + } catch (Exception ex) { + LOGGER.error("系数下调异常{}", ex.getMessage()); + } + } + + public Object evaluateAction(PropertyEvaluationModel model, HttpServletRequest request, HouseValueInformationDto houseValueInformation, RestfulModelAndView mav) + throws NumberFormatException, IllegalAccessException { +// RestfulModelAndView mav = new RestfulModelAndView(); +// mav.setViewType("rest"); + if (StringUtils.isBlank(model.getName()) + || StringUtils.isBlank(model.getDistrict()) || model.getSize() <= 0) { + mav.setModel(BasicModel.buildBadRequestModel("参数非法:区域,小区名,面积(size)为必填项")); +// return mav; + } + if (model.getCity().endsWith("市")) { + model.setCity(model.getCity().replaceAll("市$", "")); + } + if (StringUtils.isNotBlank(request.getParameter("calDate"))) { + Date calDate = null; + try { + calDate = DateUtils.parseDate(request.getParameter("calDate"), new String[]{"yyyy-MM-dd"}); + } catch (ParseException e) { + + } + if (calDate == null) { + mav.setModel(BasicModel.buildBadRequestModel("calDate:数据类型不合法")); + return mav; + } else { + model.setCalDate(calDate); + } + } + /* 先到CPDB库中查找小区 */ + District district = districtService.findByNameAndAlias(model.getCity(), model.getDistrict(), model.getName(), + "district"); + if (district == null) { + if (model.getDistrict().contains("市辖区") || model.getDistrict().contains(model.getCity())) { + district = districtService.findByNameAndAlias(model.getCity(), null, model.getName(), "district"); + } + if (district == null) { + mav.setModel(BasicModel.buildBadRequestModel("该小区不存在")); + return mav; + } + } + model.setName(district.getName()); + + if (model.getCarportPrice() != null && (model.getCarportPrice() < 0 || model.getCarportPrice() > 1000000)) { + mav.setModel(BasicModel.buildBadRequestModel("carportPrice(车位)取值不合法")); + return mav; + } + if (model.getMaxFloor() != null && (model.getMaxFloor() <= 0 || model.getMaxFloor() > 59)) { + mav.setModel(BasicModel.buildBadRequestModel("maxFloor取值非法,正确范围[1,60)")); + return mav; + } + + if (model.getFloor() != null && (model.getFloor() <= 0 || model.getFloor() > 59)) { + mav.setModel(BasicModel.buildBadRequestModel("floor取值非法,正确范围[1,60)")); + return mav; + } + if (model.getMaxFloor() != null && model.getFloor() != null && model.getFloor() > model.getMaxFloor()) { + mav.setModel(BasicModel.buildBadRequestModel("所在楼层不能大于总楼层")); + return mav; + } + + if (model.getFloor() == null) { + JSONObject structureOb = addressMatchProxyService.addressStructure(district.getCity(), model.getAddress()); + if (structureOb != null) { + if (structureOb.containsKey("buildingNumber")) { + model.setBuildingNumber(structureOb.getString("buildingNumber")); + } + + if (structureOb.containsKey("roomNumber")) { + String roomNumber = structureOb.getString("roomNumber"); + model.setFloor(getFloor(roomNumber)); + } + + } + } + + if (model.getMaxFloor() == null && model.getFloor() != null && StringUtils.isNotBlank(model.getBuildingNumber())) { + Loudong loudong = loudongService.findForEvaluate(district.getId(), model.getBuildingNumber(), model.getUnitNumber()); + if (loudong != null && loudong.getFloors() >= model.getFloor()) { + model.setMaxFloor(loudong.getFloors()); + } + } + model.setRegion(district.getRegion()); + model.setDistrictName(district.getName()); + if (StringUtils.isBlank(model.getPropertyType())) { + if (district.getEstateType2() != null && district.getEstateType2().contains("别墅")) { + model.setPropertyType("1"); + } + } + + if (model.getCalDate() != null) { + if (new Date().before(model.getCalDate())) { + model.setCalDate(DateUtil.getFirstDayOfWeek(new Date())); + } else { + model.setCalDate(DateUtil.getFirstDayOfWeek(model.getCalDate())); + } + } else { + model.setCalDate(DateUtil.getFirstDayOfWeek(new Date())); + } + + + Evaluation evaluation = evaluationService.evaluate(district, buildEvaluation(model, request), + model.getCalDate()); + Double cityPriceCredit = null; + if (StringUtils.isNotBlank(evaluation.getFromUserId())) { + try { + ApiUserAuthority apiUserAuthority = apiUserAuthorityService + .findByUserId(Long.valueOf(evaluation.getFromUserId())); + if (apiUserAuthority.getCityCreditMap() != null + && apiUserAuthority.getCityCreditMap().containsKey(evaluation.getCity())) { + cityPriceCredit = apiUserAuthority.getCityCreditMap().get(evaluation.getCity()); + if (cityPriceCredit > 1 || cityPriceCredit < 0) { + cityPriceCredit = null; + } + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + + this.adjustPriceByRatio(district, evaluation); + } + + // 调整面积不同面积价格 + try { + DistrictStatBo districtStatBo = districtStatService.findDistrictStat(new DistrictKey(district)); + int orgAvgPrice = 0; + if (districtStatBo != null) { + if (StringUtils.isNotBlank(district.getEstateType2()) && district.getEstateType2().contains("别墅") && districtStatBo.getVillaDistrictStat() != null) { + orgAvgPrice = districtStatBo.getVillaDistrictStat().getAvgPrice(); + } else if (districtStatBo.getDistrictStat() != null) { + orgAvgPrice = districtStatBo.getDistrictStat().getAvgPrice(); + } + } + if (evaluation != null && evaluation.getAvgPrice() != null && evaluation.getAvgPrice() > 0) { + int factorPrice = evaluation.getAvgPrice(); + int avgPrice = evaluateFactorService.recompose(district.getCity(), district.getRegion(), evaluation.getArea(), factorPrice, orgAvgPrice); + // 有2B价格用2B价格,没有用2C + Integer minPrice = 0; + Integer maxPrice = 0; + if (evaluation.getAvgPrice2b() != null && evaluation.getAvgPrice2b() > 0) { + minPrice = (int) (evaluation.getAvgPrice2b() * 0.95); + maxPrice = (int) (evaluation.getAvgPrice2b() * 1.05); + } else { + minPrice = (int) (evaluation.getAvgPrice() * 0.95); + maxPrice = (int) (evaluation.getAvgPrice() * 1.05); + } + // 偏离度超过5%不进行调整 + if (minPrice != 0 && maxPrice != 0 && minPrice <= avgPrice && avgPrice <= maxPrice) { + evaluation.setAvgPrice(avgPrice); + evaluation.setBigTotalPrice((long) (avgPrice * evaluation.getArea())); + } + } + } catch (Exception ex) { + LOGGER.error("调整面积不同面积价格异常{}", ex.getMessage()); + } + + if (evaluation.getTotalPrice() != null && evaluation.getTotalPrice() != 0 + && (cityPriceCredit == null || evaluation.getCredit() >= cityPriceCredit)) { + Map districtPriceMap = new HashMap(); + districtPriceMap.put("city", district.getCity()); + districtPriceMap.put("district", district.getRegion()); + districtPriceMap.put("name", district.getName()); + districtPriceMap.put("totalPrice", evaluation.getBigTotalPrice()); + if (evaluation.getAvgPrice2b() != null && evaluation.getAvgPrice2b() != 0) { + districtPriceMap.put("avgPrice", evaluation.getAvgPrice2b()); + } else { + districtPriceMap.put("avgPrice", evaluation.getAvgPrice()); + } + + // 根据城市等 级设置D级可信度 + ApiUserAuthority apiUserAuthority = apiUserAuthorityService + .findByUserId(Long.valueOf(evaluation.getFromUserId())); + if (apiUserAuthority != null && null != apiUserAuthority.getCreditLevelStatus() + && apiUserAuthority.getCreditLevelStatus() == 1) { + double dCredit = 0.61; + if (null != apiUserAuthority.getPriceRatingMap()) { + ServerArea serverArea = serverAreaService.findByDisplay(evaluation.getCity()); + Map rateMap = apiUserAuthority.getPriceRatingMap(); + if (null != rateMap) { + dCredit = rateMap.get(CITYLEVEL_MAP.get(serverArea.getNewCityGrade().toString())); + } + } + Map rMap = getLastEvaluationPrice(district, evaluation, dCredit); + + if (model.getScope() == EVALUATE_SHOW_DETAIL) { + if (null != rMap) { + if (rMap.containsKey("level")) { + districtPriceMap.put("level", rMap.get("level")); + } + if (rMap.containsKey("other_price")) { + districtPriceMap.put("other_price", rMap.get("other_price")); + } + } + } + + Long lastPrice = (Long) rMap.get("lastPrice"); + + if (null != lastPrice) { + districtPriceMap.put("totalPrice", lastPrice); + if (lastPrice > 0 && lastPrice != evaluation.getBigTotalPrice()) { + districtPriceMap.put("avgPrice", (int) (lastPrice / evaluation.getArea())); + } + } else { + mav.setModel(BasicModel.buildOKModel().setMsg("暂时不支持该小区的估价").markNoData()); + return mav; + } + + } else { + districtPriceMap.put("totalPrice", evaluation.getBigTotalPrice()); + } + + if (model.getScope() == EVALUATE_SHOW_DETAIL) { + districtPriceMap.put("evaluateWay", evaluation.getEvaluateWay()); + districtPriceMap.put("credit", evaluation.getCredit()); + districtPriceMap.put("id", evaluation.getId()); + } + // 将评估价放到结果集 + houseValueInformation.setAddressValue(districtPriceMap); +// mav.setModel(BasicModel.buildOKModel().setResult(districtPriceMap)); + try { + if (StringUtils.isNotBlank(evaluation.getFromUserId()) && !evaluation.getFromUserId().equals("1007497")) { + openApiLogService.saveLog(CommonUtils.convertToMap(model), districtPriceMap, evaluation, "/property/evaluate"); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + return mav; + } else { + evaluationService.remove(evaluation.getId()); + mav.setModel(BasicModel.buildOKModel().setMsg("暂时不支持该小区的估价").markNoData()); + return mav; + } + } + + private Integer getFloor(String roomNumber) { + if (StringUtils.isNotBlank(roomNumber) && DataUtil.isNumber(roomNumber)) { + if (roomNumber.length() == 3) { + return Integer.valueOf(roomNumber.substring(0, 1)); + } else if (roomNumber.length() == 4) { + return Integer.valueOf(roomNumber.substring(0, 2)); + } else { + return null; + } + } + return null; + } + + private Evaluation buildEvaluation(PropertyEvaluationModel model, HttpServletRequest request) { + Evaluation evaluation = new Evaluation(); + evaluation.setCity(model.getCity()); + evaluation.setRegion(model.getRegion()); + evaluation.setDistrictName(model.getName()); + evaluation.setDirection(DIRECTION.get(model.getDirection())); + evaluation.setFitment(EVALUATION_MODEL_FITMENT.get(FITMENT.get(StringUtils.isNotBlank(model.getDecoration()) ? + model.getDecoration() : model.getFitment()))); + evaluation.setNoise(NOISE.get(model.getNoise())); + evaluation.setEstateType(PROPERTY_TYPES.get(model.getPropertyType())); + evaluation.setSight(SIGHT.get(model.getView())); + evaluation.setAtticArea(model.getAtticSize()); + evaluation.setTerraceArea(model.getOuterSize()); + evaluation.setBasementArea(model.getBasementSize()); + evaluation.setGardenArea(model.getGardenSize()); + String worryFacility = model.getNegativeFactor(); + evaluation.setWorryFacility(NEGATIVE_FACTOR.get(worryFacility)); + evaluation.setCreationDate(new Date()); + evaluation.setModificationDate(new Date()); + evaluation.setClientNo(model.getClientNo()); + if (0 != model.getAge()) { + evaluation.setAge(model.getAge()); + } + evaluation.setArea(model.getSize()); + if (ArrayUtils.isNotEmpty(model.getBuildQuality())) { + evaluation.setBuildQuality(convertToString(model.getBuildQuality())); + } + if (StringUtils.isNotBlank(model.getBuildType())) { + evaluation.setBuildType(model.getBuildType()); + } + if (StringUtils.isNotBlank(model.getCarport())) { + evaluation.setCarport(model.getCarport()); + } + if (model.getDecorationAge() >= 1 && model.getDecorationAge() <= 5) { + evaluation.setFitmentAge(model.getDecorationAge()); + } + evaluation.setCarportPrice(model.getCarportPrice()); + evaluation.setCity(model.getCity()); + evaluation.setDistrictName(model.getName()); + if (model.getDecorationCost() != null && model.getDecorationCost() > 0) { + evaluation.setFitmentCharge(model.getDecorationCost()); + } + if (0 != model.getHall()) { + evaluation.setHall(model.getHall()); + } + if (null != model.getFloor()) { + evaluation.setFloor(model.getFloor()); + } + if (model.getMaxFloor() != null && 0 != model.getMaxFloor()) { + evaluation.setHeight(model.getMaxFloor()); + } + if (StringUtils.isNotBlank(model.getBuildingNumber())) { + evaluation.setHouseNum(model.getBuildingNumber()); + } + if (StringUtils.isNotBlank(model.getHouseProperty())) { + evaluation.setHouseProperty(model.getHouseProperty()); + } + if (StringUtils.isNotBlank(model.getInsidepos())) { + evaluation.setInsidepos(model.getInsidepos()); + } + if (StringUtils.isNotBlank(model.getLightingVentilation())) { + evaluation.setLightingVentilation(model.getLightingVentilation()); + } + + if (StringUtils.isNotBlank(model.getOtherFactor())) { + evaluation.setOtherFactor(model.getOtherFactor()); + } + evaluation.setRegion(model.getDistrict()); + if (null != model.getRoom()) { + evaluation.setRoom(model.getRoom()); + } + if (StringUtils.isNotBlank(model.getRoomNumber())) { + evaluation.setRoomNum(model.getRoomNumber()); + } + if (StringUtils.isNotBlank(model.getSideset())) { + evaluation.setSideset(model.getSideset()); + } + if (0 != model.getToilet()) { + evaluation.setToilet(model.getToilet()); + } + if (model.getFacilities() != null) { + String facilities = model.getFacilities(); + String[] fs = facilities.split(","); + for (int i = 0; i < fs.length; i++) { + fs[i] = FACILITIES.get(fs[i]); + } + evaluation.setFacilities(convertToString(fs)); + } + + if (StringUtils.isNotBlank(model.getFacade())) { + evaluation.setFacade(model.getFacade()); + } + if (StringUtils.isNotBlank(model.getTraffice())) { + evaluation.setTraffice(model.getTraffice()); + } + if (StringUtils.isNotBlank(model.getShape())) { + evaluation.setShape(model.getShape()); + } + if (StringUtils.isNotBlank(model.getObstacle())) { + evaluation.setObstacle(model.getObstacle()); + } + if (StringUtils.isNotBlank(model.getIndustry())) { + evaluation.setIndustry(model.getIndustry()); + } + if (StringUtils.isNotBlank(model.getSupportDevice())) { + evaluation.setSupportDevice(model.getSupportDevice()); + } + if (StringUtils.isNotBlank(model.getLeftPosition())) { + evaluation.setLeftPosition(model.getLeftPosition()); + } + if (StringUtils.isNotBlank(model.getShopType())) { + evaluation.setShopType(model.getShopType()); + } + if (StringUtils.isNotBlank(model.getShopUnique())) { + evaluation.setShopUnique(model.getShopUnique()); + } + if (StringUtils.isNotBlank(model.getLocation())) { + evaluation.setLocation(model.getLocation()); + } + if (model.isNewDistrict()) { + evaluation.setNewDistrict(model.isNewDistrict()); + } + String ip = AnalyticsUtil.getIpAddress(ActionContext.getContext().getRequest()); + evaluation.setIp(ip); + AuthenticationBean authenticationBean = (AuthenticationBean) request + .getAttribute(AuthenticationBean.ATTR_AUTHENTICATION_BEAN); + if (authenticationBean != null && authenticationBean.apiUser != null) { + evaluation.setFromUserId(String.valueOf(authenticationBean.apiUser.getId())); + } + evaluation.setSource("api_property_evaluation"); + return evaluation; + } + + private Map getLastEvaluationPrice(District district, Evaluation evaluation, double dCredit) + throws NumberFormatException, IllegalAccessException { + Date startDate = DateUtil.parseDate(DateUtil.addMonth(new Date(), -6), "yyyy-MM-dd"); + // 第三方价格 + Map otherPriceRets = averageStatisticsService.findFirstAverageStatictics(district.getCity(), + district.getRegion(), district.getName(), district.getCategory(), startDate); + if (null == otherPriceRets) { + otherPriceRets = new HashMap(); + } + + if (evaluation.getAvgPrice2b()!=null&&evaluation.getAvgPrice2b() > 0){ + otherPriceRets.put("fjw_price", evaluation.getAvgPrice2b()); + }else { + otherPriceRets.put("fjw_price", evaluation.getAvgPrice()); + } + Map levelMap = getPriceLevel(otherPriceRets, evaluation.getCredit()); + Long lastPrice = getLastPrice(levelMap, otherPriceRets, evaluation, dCredit); + + Map rMap = new HashMap(); + rMap.put("lastPrice", lastPrice); + if (null != levelMap && levelMap.containsKey("level")) { + String priceLevel = (String) levelMap.get("level"); + rMap.put("level", priceLevel); + } + rMap.put("other_price", otherPriceRets); + return rMap; + } + + private Map getPriceLevel(Map otherPriceRets, double credit) { + + Integer avgPrice = (Integer) otherPriceRets.get("fjw_price"); + + int keyCount = 0; + int commonCount = 0; + int isExistCount = 0; + + List prices = new ArrayList(); + List smallPrices = new ArrayList(); + + if (null != otherPriceRets.get("fanggugu_price")) { + Integer fangguguPrice = (Integer) otherPriceRets.get("fanggugu_price"); + int mod = avgPrice - fangguguPrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + keyCount++; + } else { + prices.add(fangguguPrice); + } + isExistCount++; + } + if (null != otherPriceRets.get("yungujia_price")) { + Integer yungujiaPrice = (Integer) otherPriceRets.get("yungujia_price"); + int mod = avgPrice - yungujiaPrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + keyCount++; + } else { + prices.add(yungujiaPrice); + } + + isExistCount++; + } + + if (null != otherPriceRets.get("zhugezhaofang_price")) { + Integer zhugezhaofangPrice = (Integer) otherPriceRets.get("zhugezhaofang_price"); + int mod = avgPrice - zhugezhaofangPrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + keyCount++; + } else { + prices.add(zhugezhaofangPrice); + } + + isExistCount++; + } + + if (null != otherPriceRets.get("lianjia_price")) { + Integer lianjiaPrice = (Integer) otherPriceRets.get("lianjia_price"); + int mod = avgPrice - lianjiaPrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + keyCount++; + } else { + prices.add(lianjiaPrice); + } + isExistCount++; + } + if (null != otherPriceRets.get("anjuke_price")) { + Integer anjukePrice = (Integer) otherPriceRets.get("anjuke_price"); + int mod = avgPrice - anjukePrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + commonCount++; + smallPrices.add(anjukePrice); + } else { + prices.add(anjukePrice); + } + + isExistCount++; + } + if (null != otherPriceRets.get("ganji_price")) { + Integer ganjiPrice = (Integer) otherPriceRets.get("ganji_price"); + int mod = avgPrice - ganjiPrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + commonCount++; + smallPrices.add(ganjiPrice); + } else { + prices.add(ganjiPrice); + } + + isExistCount++; + } + if (null != otherPriceRets.get("soufan_price")) { + Integer soufan_price = (Integer) otherPriceRets.get("soufan_price"); + int mod = avgPrice - soufan_price; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + commonCount++; + smallPrices.add(soufan_price); + } else { + prices.add(soufan_price); + } + + isExistCount++; + } + if (null != otherPriceRets.get("tobushi_price")) { + Integer tobushi = (Integer) otherPriceRets.get("tobushi_price"); + int mod = avgPrice - tobushi; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + commonCount++; + smallPrices.add(tobushi); + } else { + prices.add(tobushi); + } + + isExistCount++; + } + + if (null != otherPriceRets.get("zhongyuan_price")) { + Integer zhongyuanPrice = (Integer) otherPriceRets.get("zhongyuan_price"); + int mod = avgPrice - zhongyuanPrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + commonCount++; + smallPrices.add(zhongyuanPrice); + } else { + prices.add(zhongyuanPrice); + } + + isExistCount++; + } + + Map retMap = new HashMap(); + String level = null; + if (keyCount >= 2) { + level = "A"; + } else if (keyCount >= 1 && commonCount >= 1) { + level = "A"; + } else if (keyCount >= 1 || commonCount >= 2) { + level = "B"; + } else if (commonCount >= 1) { + level = "C"; + } else if (isExistCount == 0) { + level = "D"; + } else if (isExistCount >= 1) { + if (isExistCount == 1) { + level = "D"; + } else { + level = "E"; + } + } + + if (credit == 0) { + level = "E"; + } + + if (StringUtils.isNotBlank(level)) { + retMap.put("level", level); + retMap.put("prices", prices); + retMap.put("small_prices", smallPrices); + } + return retMap; + } + + private Long getLastPrice(Map retMap, Map otherPriceRets, Evaluation evaluation, double dCredit) { + Long lastPrice = null; + if (null != retMap) { + String priceLevel = (String) retMap.get("level"); + + if (priceLevel.equals("D")) { + + lastPrice = inputResultByWebsite(otherPriceRets, evaluation, dCredit); + + } else if (priceLevel.equals("E")) { + if (evaluation.getCredit() >= 0.65) { + lastPrice = evaluation.getBigTotalPrice(); + } else { + List prices = (List) retMap.get("prices"); + int avgPrice = 0; + if (prices != null) { + avgPrice = findNewPrice(prices, evaluation.getAvgPrice()); + } + // 在 dCredit与0.65之间 + if (evaluation.getCredit() >= dCredit && dCredit < 0.65) { + if (avgPrice > 0) { + Double newTotalPrice = avgPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else { + if (null != otherPriceRets.get("lianjia_price")) { + Integer lianjiaPrice = (Integer) otherPriceRets.get("lianjia_price"); + Double newTotalPrice = lianjiaPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("zhugezhaofang_price")) { + Integer zhugezhaofangPrice = (Integer) otherPriceRets.get("zhugezhaofang_price"); + Double newTotalPrice = zhugezhaofangPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("yungujia_price")) { + Integer yungujiaPrice = (Integer) otherPriceRets.get("yungujia_price"); + Double newTotalPrice = yungujiaPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("fanggugu_price")) { + Integer fangguguPrice = (Integer) otherPriceRets.get("fanggugu_price"); + Double newTotalPrice = fangguguPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else { + lastPrice = evaluation.getBigTotalPrice(); + } + } + } else if (evaluation.getCredit() < dCredit) {// 在dCredit以下 + if (avgPrice > 0) { + Double newTotalPrice = avgPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else { + if (null != otherPriceRets.get("lianjia_price")) { + Integer lianjiaPrice = (Integer) otherPriceRets.get("lianjia_price"); + Double newTotalPrice = lianjiaPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("zhugezhaofang_price")) { + Integer zhugezhaofangPrice = (Integer) otherPriceRets.get("zhugezhaofang_price"); + Double newTotalPrice = zhugezhaofangPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("yungujia_price")) { + Integer yungujiaPrice = (Integer) otherPriceRets.get("yungujia_price"); + Double newTotalPrice = yungujiaPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("fanggugu_price")) { + Integer fangguguPrice = (Integer) otherPriceRets.get("fanggugu_price"); + Double newTotalPrice = fangguguPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } + } + } + } + + } else if (priceLevel.equals("C")) { + List smallPrices = (List) retMap.get("small_prices"); + if (smallPrices != null) { + smallPrices.add(evaluation.getAvgPrice()); + int avgPrice = sum(smallPrices) / smallPrices.size(); + Double newTotalPrice = avgPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } + } else { + lastPrice = evaluation.getBigTotalPrice(); + } + } + return lastPrice; + } + + private Integer sum(List smallPrices) { + int sum = 0; + for (int price : smallPrices) { + sum += price; + } + return sum; + } + + private Long inputResultByWebsite(Map otherPriceRets, Evaluation evaluation, double dCredit) { + Long lastPrice = null; + if (evaluation.getCredit() >= dCredit) { + lastPrice = evaluation.getBigTotalPrice(); + } else { + if (evaluation.getCredit() < dCredit) { + if (null != otherPriceRets.get("lianjia_price")) { + Integer lianjiaPrice = (Integer) otherPriceRets.get("lianjia_price"); + Double newTotalPrice = lianjiaPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("zhugezhaofang_price")) { + Integer zhugezhaofangPrice = (Integer) otherPriceRets.get("zhugezhaofang_price"); + Double newTotalPrice = zhugezhaofangPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("yungujia_price")) { + Integer yungujiaPrice = (Integer) otherPriceRets.get("yungujia_price"); + Double newTotalPrice = yungujiaPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("fanggugu_price")) { + Integer fangguguPrice = (Integer) otherPriceRets.get("fanggugu_price"); + Double newTotalPrice = fangguguPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else { + lastPrice = evaluation.getBigTotalPrice(); + } + } else { + lastPrice = evaluation.getBigTotalPrice(); + } + } + return lastPrice; + } + + private Integer findNewPrice(List prices, int avgPrice) { + int minValue1 = Integer.MAX_VALUE; + List> values = new ArrayList>(); + int fjw_price = avgPrice; + + // 找出最小差 + for (int i = 0; i < prices.size() - 1; i++) { + int a = prices.get(i); + for (int j = i + 1; j < prices.size(); j++) { + int b = prices.get(j); + int mod = Math.abs(a - b); + if (mod < minValue1) { + minValue1 = mod; + } + } + } + + // 根据最小差找出结果 + for (int i = 0; i < prices.size() - 1; i++) { + int a = prices.get(i); + for (int j = i + 1; j < prices.size(); j++) { + int b = prices.get(j); + int mod = Math.abs(a - b); + if (mod == minValue1) { + values.add(Arrays.asList(a, b)); + } + } + } + + int minValue2 = Integer.MAX_VALUE; + int lastValue = 0; + if (values.size() >= 1) { + for (List value : values) { + int newPrice = (value.get(0) + value.get(1)) / 2; + int mod = Math.abs(fjw_price - newPrice); + if (mod < minValue2) { + minValue2 = mod; + lastValue = newPrice; + } + } + } + + if (lastValue > 0) { + double temp = DataUtil.getDoubleRound(2, minValue1 * 100 / lastValue); + temp = Math.abs(temp); + if (temp > 15) { + lastValue = 0; + } + } + return lastValue; + } + + + public void setEvaluationService(EvaluationService evaluationService) { + this.evaluationService = evaluationService; + } + + public void setDistrictService(DistrictService districtService) { + this.districtService = districtService; + } + + public void setAddressService(AddressService addressService) { + } + + public void setDistrictStatService(DistrictStatService districtStatService) { + this.districtStatService = districtStatService; + } + + protected AddressMatchLogService addressMatchLogService; + + public void setAddressMatchLogService(AddressMatchLogService addressMatchLogService) { + this.addressMatchLogService = addressMatchLogService; + } + + + public BatchEvaluateService getBatchEvaluateService() { + return batchEvaluateService; + } + + public void setBatchEvaluateService(BatchEvaluateService batchEvaluateService) { + this.batchEvaluateService = batchEvaluateService; + } + + public void setAddressMatchProxyService(AddressMatchProxyService addressMatchProxyService) { + this.addressMatchProxyService = addressMatchProxyService; + } + + public void setLoudongService(LoudongService loudongService) { + this.loudongService = loudongService; + } + + public void setApiUserAuthorityService(ApiUserAuthorityService apiUserAuthorityService) { + this.apiUserAuthorityService = apiUserAuthorityService; + } + + public void setAverageStatisticsService(AverageStatisticsService averageStatisticsService) { + this.averageStatisticsService = averageStatisticsService; + } + + public void setServerAreaService(ServerAreaService serverAreaService) { + this.serverAreaService = serverAreaService; + } + + public void setApiUserCfgService(ApiUserCfgService apiUserCfgService) { + this.apiUserCfgService = apiUserCfgService; + } + + public void setOpenApiLogService(OpenApiLogService openApiLogService) { + this.openApiLogService = openApiLogService; + } + + public void setFangjiaOfficialAreaService(FangjiaOfficialAreaService fangjiaOfficialAreaService) { + this.fangjiaOfficialAreaService = fangjiaOfficialAreaService; + } + + + public void setEvaluateRatioService(EvaluateRatioService evaluateRatioService) { + this.evaluateRatioService = evaluateRatioService; + } + + + public void setEvaluateFactorService(EvaluateFactorService evaluateFactorService) { + this.evaluateFactorService = evaluateFactorService; + } + + public void setCzbankSampleService(CzbankSampleService czbankSampleService) { + this.czbankSampleService = czbankSampleService; + } + + public void setDistrictFacilitysService(DistrictFacilitysService districtFacilitysService) { + this.districtFacilitysService = districtFacilitysService; + } + + public void setAdministrativeDivisionService(AdministrativeDivisionService administrativeDivisionService) { + this.administrativeDivisionService = administrativeDivisionService; + } +} + diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/Controller.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/Controller.java index 1c508b26b..95877519f 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/Controller.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/Controller.java @@ -55,38 +55,44 @@ public class Controller { return mav; } - /** - * 缓存刷新接口 - * @return - */ - @Authority(role = Role.NONE) - public Object refreshCacheAction(RefreshCacheModel model){ - RestfulModelAndView mav = new RestfulModelAndView(); - mav.setViewType("rest"); - Token token = FangjiaApiUtil.parse2Token(model.getToken()); - if(token == null){ - mav.setModel(BasicModel.buildUnAuthorizedModel().setMsg("非法的Token")); - return mav; - } - final ThreadLocalData threadLocalData = ThreadLocalData.getInstance(); - threadLocalData.put(ThreadLocalKey.DisableCache, "1"); - // 在验证appKey - ApiUser apiUser = this.apiUserService.findApiUserById(token.getUserId()); - if(apiUser == null){ - mav.setModel(BasicModel.buildUnAuthorizedModel().setMsg("非法的Token")); - return mav; - } - try { - apiUserAuthorityService.findByUserId(apiUser.getId()); - if(StringUtils.isNotBlank(model.getViewConfigUrl())){ - apiUserAuthorityService.findViewConfig(apiUser.getId(), model.getViewConfigUrl()); - } - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - mav.setModel(BasicModel.buildOKModel().setMsg("缓存刷新成功")); - return mav; - } + /** + * 缓存刷新接口 + * + * @return + */ + @Authority(role = Role.NONE) + public Object refreshCacheAction(RefreshCacheModel model) { + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + Token token = FangjiaApiUtil.parse2Token(model.getToken()); + if (token == null) { + mav.setModel(BasicModel.buildUnAuthorizedModel().setMsg("非法的Token")); + return mav; + } + final ThreadLocalData threadLocalData = ThreadLocalData.getInstance(); + threadLocalData.put(ThreadLocalKey.DisableCache, "1"); + // 在验证appKey + ApiUser apiUser = this.apiUserService.findApiUserById(token.getUserId()); + if (apiUser == null) { + mav.setModel(BasicModel.buildUnAuthorizedModel().setMsg("非法的Token")); + return mav; + } + try { + // 获取用户 + User user = userService.findById(apiUser.getId()); + if (null != user && StringUtils.isNotBlank(user.getUserName())) { + userService.findByUserName(user.getUserName()); + } + apiUserAuthorityService.findByUserId(apiUser.getId()); + if (StringUtils.isNotBlank(model.getViewConfigUrl())) { + apiUserAuthorityService.findViewConfig(apiUser.getId(), model.getViewConfigUrl()); + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + mav.setModel(BasicModel.buildOKModel().setMsg("缓存刷新成功")); + return mav; + } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/DistrictController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/DistrictController.java index 395cb8a8d..90bd877e3 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/DistrictController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/DistrictController.java @@ -7,9 +7,12 @@ import javax.servlet.http.HttpServletRequest; import com.fangjia.core.RegionData; import com.fangjia.core.util.DateUtil; +import com.fangjia.core.util.HttpRequest; import com.fangjia.dal.mongo.model.*; +import com.fangjia.open.dto.addressGovernance.MatchedBuildingDto; import com.fangjia.open.model.AvgPriceQueryModel; import com.fangjia.open.model.BasicModel; +import com.fangjia.open.util.CommonDtoUtils; import com.fangjia.service.datastore.RegionStatService; import com.fangjia.service.district.DistrictFacilitysService; import com.fangjia.service.district.DistrictStatRentService; @@ -1164,7 +1167,41 @@ public class DistrictController { } return mav; } - + + + public Object addrFacilitysAction(DistrictSearchModel model, @Param(name = "city") String city, @Param(name = "address") String address) throws Exception{ + RestfulModelAndView mav = new RestfulModelAndView(); + mav.setViewType("rest"); + if (StringUtils.isBlank(address)) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "地址必须输入")); + return mav; + } else { + String cat = "district"; + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", city); + params.put("address", address); + params.put("category", "property"); + //新匹配接口 + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", params, "UTF-8"); + District property = null; + if (json != null && json.size() > 0) { + MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); + property = districtService.findByNameAndAlias(dto.getCity(), dto.getDistrict(), dto.getName(), cat); + if (null == property) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "小区数据不存在")); + return mav; + } + DistrictFacilitys facilitys = districtFacilitysService.findByDistrict(property); + mav.setModel(BasicModel.buildOKModel().setResult(facilitys)); + }else{ + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "小区数据不存在")); + } + } + return mav; + } /** diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/GdBankController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/GdBankController.java new file mode 100644 index 000000000..fd1709bf3 --- /dev/null +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/GdBankController.java @@ -0,0 +1,258 @@ +package com.fangjia.open.controllers; + +import com.fangjia.core.util.HttpRequest; +import com.fangjia.open.interceptors.Authority; +import com.fangjia.open.interceptors.Role; +import com.fangjia.open.model.AddressModel; +import com.fangjia.open.model.BasicModel; +import com.fangjia.open.model.RestfulModelAndView; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import net.sf.json.JSONObject; +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import sun.misc.BASE64Encoder; + +import java.io.IOException; +import java.net.Authenticator; +import java.net.InetSocketAddress; +import java.net.PasswordAuthentication; +import java.net.Proxy; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; + +/** + * 光大接口 + */ +@Authority(role = Role.USER) +public class GdBankController { + + private static final Map areaMap = new HashMap() { + { + // 添加键值对到 Map 中 + put("111", "主城区"); + put("112", "城乡结合区"); + put("121", "镇中心区"); + put("122", "镇乡结合区"); + put("123", "特殊区域"); + put("210", "乡中心区"); + put("220", "村庄"); + } + }; + + /** + * 涉农识别-新规则-光大银行 + * + * @param model + * @return + */ + public Object villageIdentifyAction(AddressModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(BasicModel.buildBadRequestModel("地址不能为空")); + return mav; + } + String type = StringUtils.isNotBlank(model.getType()) ? model.getType() : null; + String address = model.getAddress(); + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", StringUtils.isNotBlank(model.getCity()) ? model.getCity() : null); + params.put("type", type); + params.put("redis", (model.getRadius() != null && model.getRadius() != 0) ? model.getRadius().toString() : null); + params.put("address", model.getAddress()); + params.put("showFullValue", "2"); + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/villageIdentify", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/villageIdentify", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + //我们的结果 + JSONObject result = json.getJSONObject("result"); + if (("是").equals(result.get("countyLevelCity"))) { + result.put("prefectureLevelCity", "否"); + } else if (("否").equals(result.get("countyLevelCity"))) { + result.put("prefectureLevelCity", "是"); + } + // 如果是无效信息或者没有行政区划,则用我们的 + if (result.containsKey("addrVerify") && ("无效".equals(result.getString("addrVerify")) || "没有行政区划".equals(result.getString("addrVerify")))) { + basicModel.setResult(result); + //我们省级及以上有开发区,直接用我们的结果 + } else if (result.containsKey("devDistrictName")) { + basicModel.setResult(result); + } else { + try { + //如果是江苏省或者浙江省 调用齐梁的结果 + if ("江苏省".equals(result.getString("province")) || "浙江省".equals(result.getString("province"))) { + + //结果比较,如果涉农结果不一致 + //调用齐梁 type :1 对公 0 对私 + //我们 type :1 对私 2 对共 + String qltype = "2".equals(type) ? "1" : "0"; + Map map = senRequest(address, qltype); + // 涉农结果不一样 + if (!map.get("verifyFlag").equals(result.get("verifyFlag"))) { + //有市辖建制镇, 或者城市不一样 用我们 + if (result.containsKey("city") && ("是".equals(result.get("administrativeTowns")) || (!result.get("city").equals(map.get("city")) + && StringUtils.isNotBlank(result.getString("city"))))) { + basicModel.setResult(result); + } else { + if (("是").equals(result.get("countyLevelCity"))) { + map.put("prefectureLevelCity", "否"); + } else if (("否").equals(result.get("countyLevelCity"))) { + map.put("prefectureLevelCity", "是"); + } + map.put("addrVerify", "地址有效"); + if (result.containsKey("countyLevelCity")) { + map.put("countyLevelCity", result.getString("countyLevelCity")); + } + map.put("typeName", areaMap.get(map.get("typeCode"))); + basicModel.setResult(map); + } + } else { + basicModel.setResult(result); + } + + } else { + basicModel.setResult(result); + + } + + } catch (Exception e) { + e.printStackTrace(); + basicModel.setResult(result); + } + + } + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + + private static Map senRequest(String address, String type) throws IOException { + String targetURL = "http://146.56.217.44:9010/uams/farmer/all/v3/sign"; + String proxyHost = "tunnel2.qg.net"; + int proxyPort = 14186; + final String proxyUsername = "113BBC06"; + final String proxyPassword = "3B2FBD05B0AF"; + String jsonData = "{\"address\":\"" + address + "\",\"type\":\"" + type + "\"}"; + String authKey = proxyUsername; + String password = proxyPassword; + String auth = authKey + ":" + password; + String authHeader = "Basic " + new BASE64Encoder().encode(auth.getBytes(Charset.forName("UTF-8"))); + + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(targetURL); + Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); + Authenticator.setDefault(new Authenticator() { + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray()); + } + }); + httpPost.setHeader("Content-Type", "application/json"); + httpPost.setHeader("Accept", "*/*"); + httpPost.setHeader("Host", "146.56.217.44:9010"); + httpPost.setHeader("Proxy-Authorization", authHeader); + StringEntity stringEntity = new StringEntity(jsonData, ContentType.APPLICATION_JSON); + httpPost.setEntity(stringEntity); + + CloseableHttpResponse httpResponse = null; + int retryCount = 2; // 设置重试次数 + int retryDelay = 10; // 设置重试延迟时间(毫秒) + boolean success = false; + for (int i = 0; i < retryCount; i++) { + try { + httpResponse = httpClient.execute(httpPost); + success = true; + break; + } catch (IOException e) { + System.err.println("代理请求失败,进行重试..."); + try { + Thread.sleep(retryDelay); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + } + + if (success) { + HttpEntity responseEntity = httpResponse.getEntity(); + String responseString = EntityUtils.toString(responseEntity); + + // 使用 Gson 解析 JSON 字符串 + Gson gson = new Gson(); + JsonObject jsonObject = gson.fromJson(responseString, JsonObject.class); + + + // 创建 Map 存储各个值 + Map dataMap = new HashMap(); + + // 获取各个值并放入 Map +// dataMap.put("code", jsonObject.get("code").getAsString()); +// dataMap.put("msg", jsonObject.get("msg").getAsString()); + JsonElement dataElement = jsonObject.get("data"); + if (dataElement != null && !dataElement.isJsonNull() && dataElement.isJsonObject()) { + JsonObject data = dataElement.getAsJsonObject(); + // 在这里继续处理 data 对象 + + if (data != null && !data.isJsonNull()) { + +// dataMap.put("version", data.get("version").getAsString()); + dataMap.put("province", data.get("province").getAsString()); + dataMap.put("city", data.get("city").getAsString()); + dataMap.put("district", data.get("district").getAsString()); + dataMap.put("town", data.get("town").getAsString()); + dataMap.put("committee", data.get("village").getAsString()); + dataMap.put("provinceCode", data.get("provinceCode").getAsString()); + dataMap.put("cityCode", data.get("cityCode").getAsString()); + dataMap.put("districtCode", data.get("districtCode").getAsString()); + dataMap.put("townCode", data.get("townCode").getAsString()); + dataMap.put("committeeCode", data.get("villageCode").getAsString()); + dataMap.put("typeCode", data.get("areaCode").getAsString()); + dataMap.put("verifyFlag", "0".equals(data.get("farmer").getAsString()) ? "非农" : "农"); + dataMap.put("countyGov", "0".equals(data.get("isGovt").getAsString()) ? "否" : "是"); +// dataMap.put("govtAddr", data.get("govtAddr").isJsonNull() ? null : data.get("govtAddr").getAsString()); // 对于可能为 null 的值,需要判断是否为空 + JsonArray indusParkList = data.get("indusParkList").isJsonNull() ? null : data.get("indusParkList").getAsJsonArray(); + + if (indusParkList != null) { + JsonObject jsonObject1 = gson.fromJson(indusParkList.get(0), JsonObject.class); + dataMap.put("devDistrictName", jsonObject1.get("indusParkName").getAsString()); + dataMap.put("devDistrict", "是"); + } + } + } + + httpResponse.close(); + return dataMap; + } else { + System.err.println("重试次数已用完,请求失败。"); + } + + httpClient.close(); + return null; + } +} diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/GuzhiController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/GuzhiController.java index 870dda5e3..d4f0a3311 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/GuzhiController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/GuzhiController.java @@ -4,6 +4,8 @@ import java.util.Date; import javax.validation.Valid; +import com.fangjia.dal.sql.model.User; +import com.fangjia.service.sql.UserService; import org.apache.commons.lang.StringUtils; import org.bson.types.ObjectId; @@ -39,6 +41,7 @@ public class GuzhiController { private EvaluationService evaluationService; private SmsService smsService; private DistrictService districtService; + private UserService userService; private static final String DING_MSG_ROBOT_ID = "58c62a54d92790b58177c6d6"; @@ -150,7 +153,9 @@ public class GuzhiController { UniversalDto dto = UniversalDto.newDto(); dto.append("caseId", model.getCaseId()); mv.setModel(BasicModel.buildOKModel().setResult(dto)); - String msg = "【房价网-人工估值】接收到新的人工询价,请求请及时处理!城市:" + evaluation.getCity() + + User user = userService.findById(token.getUserId()); + String msg = "【房价网-人工估值】客户: "+user.getDisplayName()+" 提交新的人工询价,请求请及时处理!城市:" + evaluation.getCity() + " 区域:" + evaluation.getRegion() + " 小区名:" + evaluation.getDistrictName(); DingDingMessageUtil.sendTextMessage("065f4a05d5f87eb39a9f9e048eeefb80c1f7560446f8926441de80453c160c60", msg); return mv; @@ -183,4 +188,8 @@ public class GuzhiController { public void setDistrictService(DistrictService districtService) { this.districtService = districtService; } + + public void setUserService(UserService userService) { + this.userService = userService; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/HouseController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/HouseController.java index 1efa12d0f..f3548c9cc 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/HouseController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/HouseController.java @@ -20,14 +20,18 @@ import com.fangjia.open.FangjiaApiUtil; import com.fangjia.open.HttpCode; import com.fangjia.open.OpenHttpCodeEnum; import com.fangjia.open.dto.HouseDto; +import com.fangjia.open.dto.UniversalDto; +import com.fangjia.open.dto.addressGovernance.MatchedBuildingDto; import com.fangjia.open.interceptors.Authority; import com.fangjia.open.interceptors.Role; import com.fangjia.open.model.BasicModel; import com.fangjia.open.model.HousePublishModel; import com.fangjia.open.model.HouseSearchModel; import com.fangjia.open.model.RestfulModelAndView; +import com.fangjia.open.util.CommonDtoUtils; import com.fangjia.open.util.FileDao; import com.fangjia.open.ws.query.CollateralSampleQuery; +import com.fangjia.open.ws.query.SampleQuery; import com.fangjia.open.ws.query.ShopCollateralSampleQuery; import com.fangjia.service.address.AddressParser; import com.fangjia.service.bo.Collateral; @@ -55,6 +59,7 @@ import com.fangjia.service.open.HousePojo; import com.fangjia.service.sql.ApiUserService; import com.fangjia.service.sql.UserService; import com.fangjia.service.web.MenuService; +import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.bson.types.ObjectId; import org.sothis.core.util.Closure; @@ -65,7 +70,6 @@ import java.io.IOException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; - @Authority(role = Role.USER) public class HouseController { @@ -322,6 +326,117 @@ public class HouseController { return queryBeans; } + + private List convertSampileQueryToBean(SampleQuery... queries) throws Exception{ + + List queryBeans = new ArrayList(queries.length); + for(SampleQuery q : queries){ + + CollateralSampleQueryBean queryBean = new CollateralSampleQueryBean(); + BeanUtils.copyProperties(q, queryBean); +// String propertyTypeCode = queryBean.getPropertyTypeCode(); +// if(!Arrays.asList("01", "02", "03").contains(propertyTypeCode)){ +// throw new Exception("propertyTypeCode取值非法"); +// } + String cat = "district"; + + if(StringUtils.isNotBlank(queryBean.getCity()) && StringUtils.isNotBlank(queryBean.getDistrict()) && StringUtils.isNotBlank(queryBean.getBuildingName())){ + District property = districtService.findByNameAndAlias(queryBean.getCity(), queryBean.getDistrict(), queryBean.getBuildingName(), cat); + if(property == null){ + throw new Exception("未找到该小区"); + } + queryBean.setProperty(property); + }else if(StringUtils.isNotBlank(queryBean.getAddress())){ + HttpRequest request = new HttpRequest(); + JSONObject json = null; + String address = queryBean.getAddress().replace(" ","").replace("%",""); + Map params = new HashMap(); + params.put("city", queryBean.getCity()); + params.put("address", address); + params.put("category", "property"); + //新匹配接口 + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", params, "UTF-8"); + if (json != null && json.size()>0) { + MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); + District property = districtService.findByNameAndAlias(dto.getCity(), dto.getDistrict(), dto.getName(), cat); + if(property == null){ + throw new Exception("未找到该小区"); + } + queryBean.setProperty(property); + }else{ + throw new Exception("未找到该小区"); + } + } + String estateType = queryBean.getProperty().getEstateType2(); + queryBean.setPropertyTypeCode("01"); + if(StringUtils.isNotBlank(estateType)){ + if(estateType.equals("普通住宅")){ + queryBean.setPropertyTypeCode("01"); + }else if(estateType.equals("别墅")){ + queryBean.setPropertyTypeCode("02"); + }else if(estateType.equals("商住")){ + queryBean.setPropertyTypeCode("03"); + } + } + + Integer decrCondCode = queryBean.getDecrCondCode(); + if(decrCondCode == null){ + decrCondCode = 2; + } + if(decrCondCode > 5 || decrCondCode < 1){ + throw new Exception("decrCondCode取值非法"); + } + Integer towardDirectCode = queryBean.getTowardDirectCode(); + if(towardDirectCode == null){ + towardDirectCode = 3; + } + if(towardDirectCode > 10 || towardDirectCode < 1){ + throw new Exception("towardDirectCode取值非法"); + } + queryBeans.add(queryBean); + } + return queryBeans; + } + + +// private List convertSampileQueryToBean(SampleQuery... queries) throws Exception{ +// +// List queryBeans = new ArrayList(queries.length); +// for(SampleQuery q : queries){ +// +// CollateralSampleQueryBean queryBean = new CollateralSampleQueryBean(); +// BeanUtils.copyProperties(q, queryBean); +// +// +// String propertyTypeCode = queryBean.getPropertyTypeCode(); +// if(!Arrays.asList("01", "02", "03").contains(propertyTypeCode)){ +// throw new Exception("propertyTypeCode取值非法"); +// } +// String cat = "district"; +// District property = districtService.findByNameAndAlias(queryBean.getCity(), queryBean.getDistrict(), queryBean.getBuildingName(), cat); +// if(property == null){ +// throw new Exception("未找到该小区"); +// } +// queryBean.setProperty(property); +// Integer decrCondCode = queryBean.getDecrCondCode(); +// if(decrCondCode == null){ +// decrCondCode = 2; +// } +// if(decrCondCode > 5 || decrCondCode < 1){ +// throw new Exception("decrCondCode取值非法"); +// } +// Integer towardDirectCode = queryBean.getTowardDirectCode(); +// if(towardDirectCode == null){ +// towardDirectCode = 3; +// } +// if(towardDirectCode > 10 || towardDirectCode < 1){ +// throw new Exception("towardDirectCode取值非法"); +// } +// queryBeans.add(queryBean); +// } +// return queryBeans; +// } + public Object detailAction(HousePublishModel model){ RestfulModelAndView mav = new RestfulModelAndView(); mav.setViewType("rest"); @@ -774,6 +889,54 @@ public class HouseController { return mav; } + + public Object caseAction(@Valid SampleQuery sampleQuery){ + + RestfulModelAndView mav = new RestfulModelAndView(); + List querys = null; + try{ + querys = convertSampileQueryToBean(sampleQuery); + }catch (Exception e){ + mav.setModel(BasicModel.buildBadRequestModel(e.getMessage())); + return mav; + } + if(null == sampleQuery.getMax()){ + sampleQuery.setMax(10); + } + long start = System.currentTimeMillis(); + List collaterals = czbankSampleService.findSample2(querys, sampleQuery.getMax()); + long end = System.currentTimeMillis(); + System.out.println("用时:"+(end-start)); + Collateral collateral = collaterals.get(0); + List samples = collateral.getSample(); + UniversalDto dto = UniversalDto.newDto(); + if(null != collateral.getMaxPrice()){ + dto.append("maxUnitPrice", collateral.getMaxPrice()); + } + if(null != collateral.getMinPrice()){ + dto.append("minUnitPrice", collateral.getMinPrice()); + } + + dto.append("datas", samples); +// if(samples!= null && samples.size()>=2){ +// Sample minSample = samples.get(samples.size()-2); +// Sample maxSample = samples.get(samples.size()-1); +// dto.append("minUnitPrice", minSample.getUnitPrice()); +// dto.append("maxUnitPrice", maxSample.getUnitPrice()); +// } +// if(samples.size()>2){ +// dto.append("datas", samples.subList(0, samples.size()-2)); +// }else{ +// dto.append("datas", samples); +// } + + mav.setModel(BasicModel.buildOKModel().setResult(dto)); + return mav; + } + + + + private List fillDistrictInfoForHouse(FacetQueryResult houseList, Date endDate, District district, boolean showDetail, boolean matchModel) { FacetQueryResult list = new FacetQueryResult(); diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/PoiController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/PoiController.java index c79b4369b..1cc608e7e 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/PoiController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/PoiController.java @@ -1,6 +1,7 @@ package com.fangjia.open.controllers; import com.fangjia.core.RegionData; +import com.fangjia.core.util.HttpRequest; import com.fangjia.dal.mongo.model.AmapPoi; import com.fangjia.dal.mongo.model.CbmRegion; import com.fangjia.dal.mongo.model.elastic.CbmAmapPoi; @@ -8,10 +9,7 @@ import com.fangjia.dal.seaweed.model.District; import com.fangjia.open.dto.UniversalDto; import com.fangjia.open.interceptors.Authority; import com.fangjia.open.interceptors.Role; -import com.fangjia.open.model.AntiFraudQuestionModel; -import com.fangjia.open.model.BasicModel; -import com.fangjia.open.model.PoiSuggestModel; -import com.fangjia.open.model.RestfulModelAndView; +import com.fangjia.open.model.*; import com.fangjia.service.address.AddressParserService; import com.fangjia.service.address.AddressParserUtil; import com.fangjia.service.address.mode.Address; @@ -19,6 +17,7 @@ import com.fangjia.service.api.AmapPoiService; import com.fangjia.service.bo.Point; import com.fangjia.service.datastore.DistrictService; import com.fangjia.service.mongo.fangjia.CbmRegionService; +import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import javax.validation.Valid; @@ -33,14 +32,14 @@ public class PoiController { private DistrictService districtService; private static final String[] PROPERTY_SEARCH_API_FIELDS = {"address", "city", "region", "name", "addrAlias"}; - public Object getAntiFraudQuestionAction(@Valid AntiFraudQuestionModel model){ + public Object getAntiFraudQuestionAction(@Valid AntiFraudQuestionModel model) { RestfulModelAndView mav = new RestfulModelAndView(); Point point = amapPoiService.geocode(model.getCity(), model.getAddress()); - if(point != null){ + if (point != null) { List poiList = amapPoiService.findAntiFraudPoisAction(point, model.getActualPoiSelectRadius(), model.getFraudPoiSelectMinRadius(), model.getActualCount(), model.getFraudCount()); List pois = new ArrayList(); - for(AmapPoi poi : poiList){ + for (AmapPoi poi : poiList) { UniversalDto dto = UniversalDto.newDto(); dto.append("id", poi.getId()); dto.append("city", poi.getCityname()); @@ -54,22 +53,22 @@ public class PoiController { pois.add(dto); } mav.setModel(BasicModel.buildOKModel().setResult(pois)); - }else{ + } else { mav.setModel(BasicModel.buildOKModel().setResult(Collections.emptyList())); } return mav; } - public Object cmbTipsAction(@Valid PoiSuggestModel poiSuggestModel){ + public Object cmbTipsAction(@Valid PoiSuggestModel poiSuggestModel) { RestfulModelAndView mav = new RestfulModelAndView(); String city = RegionData.formatCity(poiSuggestModel.getCity()); - if(city != null){ + if (city != null) { String region = RegionData.formatRegion(city, poiSuggestModel.getRegion()); - if(!RegionData.isRegion(city, region) && RegionData.getRegionByCity(city) != null){ - for(String r : RegionData.getRegionByCity(city)){ - if(region.startsWith(r)){ + if (!RegionData.isRegion(city, region) && RegionData.getRegionByCity(city) != null) { + for (String r : RegionData.getRegionByCity(city)) { + if (region.startsWith(r)) { region = r; break; } @@ -78,71 +77,71 @@ public class PoiController { poiSuggestModel.setCity(city); poiSuggestModel.setRegion(region); } - if(!RegionData.isRegion(poiSuggestModel.getCity(), poiSuggestModel.getRegion()) || !RegionData.isCity(poiSuggestModel.getCity())){ + if (!RegionData.isRegion(poiSuggestModel.getCity(), poiSuggestModel.getRegion()) || !RegionData.isCity(poiSuggestModel.getCity())) { CbmRegion cbmRegion = cbmRegionService.findCbmRegion(poiSuggestModel.getCity(), poiSuggestModel.getRegion()); - if(cbmRegion != null){ + if (cbmRegion != null) { poiSuggestModel.setCity(cbmRegion.getCity()); poiSuggestModel.setRegion(cbmRegion.getRegion()); } } - if(city == null){ + if (city == null) { mav.setModel(BasicModel.buildBadRequestModel("city非法")); return mav; } Address address = addressParserService.standardizeForSearch(poiSuggestModel.getCity(), poiSuggestModel.getKeywords()); String keywords = poiSuggestModel.getKeywords(); - if(StringUtils.isNotBlank(address.getEffectiveAddress())){ + if (StringUtils.isNotBlank(address.getEffectiveAddress())) { poiSuggestModel.setKeywords(address.getEffectiveAddress()); poiSuggestModel.setCity(address.getCity()); - if(StringUtils.isNotBlank(address.getDistrict())){ + if (StringUtils.isNotBlank(address.getDistrict())) { poiSuggestModel.setRegion(address.getDistrict()); } } List districts = districtService.cmbSearch(poiSuggestModel.getCity(), poiSuggestModel.getRegion(), poiSuggestModel.getKeywords(), PROPERTY_SEARCH_API_FIELDS, poiSuggestModel.getLimit()); List dtos = new ArrayList(); Set keys = new HashSet(); - for(District district : districts){ + for (District district : districts) { UniversalDto dto = new UniversalDto(); dto.append("city", district.getCity()); dto.append("region", district.getRegion()); - if(district.getName().contains(poiSuggestModel.getKeywords()) || district.getAlias() == null){ + if (district.getName().contains(poiSuggestModel.getKeywords()) || district.getAlias() == null) { dto.append("name", district.getName()); keys.add(district.getName()); dto.append("address", district.getAddress()); - }else{ + } else { dto.append("name", getLookLikeString(poiSuggestModel.getKeywords(), district.getAlias(), district.getName())); - keys.add((String)dto.get("name")); - if(district.getAddress() == null || district.getAddress().contains(poiSuggestModel.getKeywords()) || district.getAddrAlias() == null){ + keys.add((String) dto.get("name")); + if (district.getAddress() == null || district.getAddress().contains(poiSuggestModel.getKeywords()) || district.getAddrAlias() == null) { dto.append("address", district.getAddress()); - }else{ + } else { dto.append("address", getLookLikeString(poiSuggestModel.getKeywords(), district.getAddrAlias(), district.getAddress())); } } dtos.add(dto); } - if(dtos.size() == poiSuggestModel.getLimit()){ + if (dtos.size() == poiSuggestModel.getLimit()) { mav.setModel(BasicModel.buildOKModel().setResult(dtos)); return mav; } List amapPois = amapPoiService.inputtips(poiSuggestModel.getCity(), poiSuggestModel.getRegion(), keywords, poiSuggestModel.getLimit(), false); - for(AmapPoi amapPoi : amapPois){ - if(!keys.contains(amapPoi.getName())){ + for (AmapPoi amapPoi : amapPois) { + if (!keys.contains(amapPoi.getName())) { UniversalDto dto = new UniversalDto(); - if(amapPoi.getCity() == null){ + if (amapPoi.getCity() == null) { dto.append("city", poiSuggestModel.getCity()); - }else{ + } else { dto.append("city", amapPoi.getCity()); } - if(amapPoi.getRegion() == null){ + if (amapPoi.getRegion() == null) { dto.append("region", poiSuggestModel.getRegion()); - }else{ + } else { dto.append("region", amapPoi.getRegion()); } dto.append("name", amapPoi.getName()); dto.append("address", amapPoi.getAddress()); dtos.add(dto); } - if(dtos.size() >= poiSuggestModel.getLimit()){ + if (dtos.size() >= poiSuggestModel.getLimit()) { break; } } @@ -150,16 +149,16 @@ public class PoiController { return mav; } - String getLookLikeString(String orgStr, List list, String extend){ - if(list == null){ + String getLookLikeString(String orgStr, List list, String extend) { + if (list == null) { list = new ArrayList(); } list.add(extend); String targetStr = extend; double similar = 0; - for(String item : list){ + for (String item : list) { double s = AddressParserUtil.getSimilarityRatio(orgStr, item); - if(s > similar){ + if (s > similar) { targetStr = item; similar = s; } @@ -167,14 +166,14 @@ public class PoiController { return targetStr; } - public Object cmbTips2Action(@Valid PoiSuggestModel poiSuggestModel){ + public Object cmbTips2Action(@Valid PoiSuggestModel poiSuggestModel) { RestfulModelAndView mav = new RestfulModelAndView(); String city = RegionData.formatCity(poiSuggestModel.getCity()); - if(city != null){ + if (city != null) { String region = RegionData.formatRegion(city, poiSuggestModel.getRegion()); - if(!RegionData.isRegion(city, region) && RegionData.getRegionByCity(city) != null){ - for(String r : RegionData.getRegionByCity(city)){ - if(region.startsWith(r)){ + if (!RegionData.isRegion(city, region) && RegionData.getRegionByCity(city) != null) { + for (String r : RegionData.getRegionByCity(city)) { + if (region.startsWith(r)) { region = r; break; } @@ -183,28 +182,28 @@ public class PoiController { poiSuggestModel.setCity(city); poiSuggestModel.setRegion(region); } - if(!RegionData.isRegion(poiSuggestModel.getCity(), poiSuggestModel.getRegion()) || !RegionData.isCity(poiSuggestModel.getCity())){ + if (!RegionData.isRegion(poiSuggestModel.getCity(), poiSuggestModel.getRegion()) || !RegionData.isCity(poiSuggestModel.getCity())) { CbmRegion cbmRegion = cbmRegionService.findCbmRegion(poiSuggestModel.getCity(), poiSuggestModel.getRegion()); poiSuggestModel.setCity(cbmRegion.getCity()); poiSuggestModel.setRegion(cbmRegion.getRegion()); } Address address = addressParserService.standardizeForSearch(poiSuggestModel.getCity(), poiSuggestModel.getKeywords()); - if(StringUtils.isNotBlank(address.getEffectiveAddress())){ + if (StringUtils.isNotBlank(address.getEffectiveAddress())) { poiSuggestModel.setKeywords(address.getEffectiveAddress()); poiSuggestModel.setCity(address.getCity()); poiSuggestModel.setRegion(address.getDistrict()); } List amapPois = amapPoiService.cmbTips(poiSuggestModel.getCity(), poiSuggestModel.getRegion(), poiSuggestModel.getKeywords()); List dtos = new ArrayList(); - for(CbmAmapPoi poi : amapPois){ + for (CbmAmapPoi poi : amapPois) { UniversalDto dto = UniversalDto.newDto(); dto.append("city", poi.getCityname()); dto.append("region", poi.getAdname()); dto.append("name", poi.getName()); dto.append("address", poi.getAddress()); - if(!poi.getName().startsWith(poiSuggestModel.getKeywords()) && poi.getAlias() != null && poi.getAlias().contains(poi.getText())){ + if (!poi.getName().startsWith(poiSuggestModel.getKeywords()) && poi.getAlias() != null && poi.getAlias().contains(poi.getText())) { dto.append("name", poi.getText()); - }else if((poi.getAddress() != null && !poi.getAddress().startsWith(poiSuggestModel.getKeywords())) && poi.getAddrAlias() != null && poi.getAddrAlias().contains(poi.getText())){ + } else if ((poi.getAddress() != null && !poi.getAddress().startsWith(poiSuggestModel.getKeywords())) && poi.getAddrAlias() != null && poi.getAddrAlias().contains(poi.getText())) { dto.append("address", poi.getText()); } dtos.add(dto); @@ -213,6 +212,62 @@ public class PoiController { return mav; } + /** + * POI搜索服务 + * + * @param model + * @return + */ + public Object searchAction(AddressModel model) { + + RestfulModelAndView mav = new RestfulModelAndView(); + if (StringUtils.isBlank(model.getLocation()) || StringUtils.isBlank(model.getCity())) { + mav.setModel(BasicModel.buildBadRequestModel("城市和经纬度为必填项")); + return mav; + } + + HttpRequest request = new HttpRequest(); + JSONObject json = null; + Map params = new HashMap(); + params.put("city", model.getCity()); + params.put("location", model.getLocation()); + params.put("types", StringUtils.isNotBlank(model.getTypes()) ? model.getTypes() : null); + Integer radius = model.getRadius(); + if (radius != null && radius > 0) { + params.put("radius", radius.toString()); + } + Integer offset = model.getOffset(); + if (offset != null && offset > 0) { + params.put("offset", offset.toString()); + } + Integer page = model.getPage(); + if (page != null && page > 0) { + params.put("page", page.toString()); + } + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/poi/search", params, "UTF-8"); + } catch (Exception e) { + try { + json = request.getJsonContent("http://192.168.0.100:32080/FangJiaAddressService/poi/search", params, "UTF-8"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (json != null) { + int code = json.getInt("msgCode"); + String msg = json.getString("msg"); + BasicModel basicModel = new BasicModel(code, msg); + if (json.containsKey("result")) { + basicModel.setResult(json.get("result")); + } + mav.setModel(basicModel); + } else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + return mav; + } + public void setAmapPoiService(AmapPoiService amapPoiService) { this.amapPoiService = amapPoiService; } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/PropertyController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/PropertyController.java index e44529895..b5efca725 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/PropertyController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/PropertyController.java @@ -10,17 +10,7 @@ import java.net.URLEncoder; import java.nio.charset.Charset; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -30,6 +20,7 @@ import javax.validation.Valid; import com.fangjia.core.util.*; import com.fangjia.dal.*; +import com.fangjia.dal.mongo.dao.AliasFangDao; import com.fangjia.dal.mongo.model.*; import com.fangjia.dal.mongo.open.model.CommunityBasePrice; import com.fangjia.dal.mongo.open.model.CommunityPoi; @@ -37,6 +28,9 @@ import com.fangjia.dal.mongo.open.model.EvaluateRatio; import com.fangjia.dal.seawater.dao.SeawaterDao; import com.fangjia.dal.seawater.model.Seawater; import com.fangjia.open.dto.*; +import com.fangjia.open.dto.addressGovernance.StructureDto; +import com.fangjia.open.util.CommonDtoUtils; +import com.fangjia.service.address.AddressParserUtil; import com.fangjia.service.district.*; import com.fangjia.service.mongo.fangjia.*; import com.fangjia.service.open.*; @@ -136,7 +130,6 @@ import com.mongodb.DBObject; @Authority(role = Role.USER) public class PropertyController { - private static final Logger LOGGER = LoggerFactory.getLogger(PropertyController.class); private DistrictService districtService; private AddressParser addressParser; @@ -184,7 +177,7 @@ public class PropertyController { private FileDao fileDao = FileDao.getInstance(); private static final int DEFAULT_PAGE_SIZE = 20; - private static final String[] PROPERTY_SEARCH_API_FIELDS = { "address", "city", "region", "name", "lat2", "lng2","lat", "lng", "block", "estateType2", "addrAlias" }; + private static final String[] PROPERTY_SEARCH_API_FIELDS = { "address", "city", "region", "name", "lat2", "lng2","lat", "lng", "block", "estateType2", "addrAlias", "alias" }; static final int BAI_DU_GEO = 1;// 百度系坐标 static final int GAO_DE_GEO = 2;// 高德系坐标 @@ -194,6 +187,7 @@ public class PropertyController { private DistrictRoomSqmetreRentService districtRoomSqmetreRentService; private RentDealPriceService rentDealPriceService; private EvaluateRatioService evaluateRatioService; + private AliasFangService aliasFangService; private static final int EVALUATE_SHOW_DETAIL = 1; private static final Map PROPERTY_TYPES = new HashMap() { @@ -607,6 +601,25 @@ public class PropertyController { dto.setBlock(district.getBlock()); } dto.setPropertyType(district.getEstateType2()); + if (CollectionUtils.isNotEmpty(district.getAlias())) { + // 将最相近的别名输出给用户 + String alias = null; + double similarity = 0; + if (StringUtils.isNotBlank(model.getKeyword())) { + for (String mappingAlias : district.getAlias()) { + double curr = AddressParserUtil.getSimilarityRatio(mappingAlias, model.getKeyword()); + if (curr > similarity ) { + similarity = curr; + alias = mappingAlias; + } + } + } + if (StringUtils.isNotBlank(alias)) { + dto.setAlias(alias); + } else { + dto.setAlias(district.getAlias().get(0)); + } + } list.add(dto); } @@ -878,8 +891,13 @@ public class PropertyController { districtInfoDto.setAddressAlias(district.getAddrAlias()); if (district.getLat2() != null && district.getLat2() != 0 && district.getLng2() != null && district.getLng2() != 0) { - districtInfoDto.setLat(district.getLat2() / 10000000000D); - districtInfoDto.setLng(district.getLng2() / 10000000000D); + districtInfoDto.setLat2(district.getLat2() / 10000000000D); + districtInfoDto.setLng2(district.getLng2() / 10000000000D); + } + if (district.getLat() != null && district.getLat() != 0 && district.getLng() != null + && district.getLng() != 0) { + districtInfoDto.setLat(district.getLat() / 10000000000D); + districtInfoDto.setLng(district.getLng() / 10000000000D); } districtInfoDto.setPropertyType(district.getEstateType2()); if (HouseValidator.validateBuildingType(district.getBuildType())) { @@ -1085,6 +1103,21 @@ public class PropertyController { return mav; } + if(model.getFloor() == null){ + JSONObject structureOb = addressMatchProxyService.addressStructure(district.getCity(), model.getAddress()); + if(structureOb != null){ + if(structureOb.containsKey("buildingNumber")){ + model.setBuildingNumber(structureOb.getString("buildingNumber")); + } + + if(structureOb.containsKey("roomNumber")){ + String roomNumber = structureOb.getString("roomNumber"); + model.setFloor(getFloor(roomNumber)); + } + + } + } + if(model.getMaxFloor() == null && model.getFloor() != null &&StringUtils.isNotBlank(model.getBuildingNumber())){ Loudong loudong = loudongService.findForEvaluate(district.getId(), model.getBuildingNumber(), model.getUnitNumber()); if(loudong != null && loudong.getFloors() >= model.getFloor()){ @@ -1108,6 +1141,8 @@ public class PropertyController { } else { model.setCalDate(DateUtil.getFirstDayOfWeek(new Date())); } + + Evaluation evaluation = evaluationService.evaluate(district, buildEvaluation(model, request), model.getCalDate()); Double cityPriceCredit = null; @@ -1549,6 +1584,9 @@ public class PropertyController { model.setDistrict(fangjiaOfficialAreaMap.getFangjiaDistrict()); } } + + boolean villaFlag = DataUtil.isVilla(model.getSize(), model.getName(), model.getHeight(), model.getRoom()); + District district = null; Map params = new HashMap(); params.put("city", model.getCity()); @@ -1566,7 +1604,14 @@ public class PropertyController { if(json.getInt("code")==200){ Map map = (Map) json.get("result"); if((Integer)map.get("precise")>=0){ - district = districtService.findByNameAndAlias((String) map.get("city"), (String) map.get("district"), (String) map.get("name"), "district"); + String propertyType = (String) map.get("propertyType"); + if(villaFlag && StringUtils.isNotBlank(propertyType) && !propertyType.equals("别墅")){ + district = districtService.findByNameAndAlias((String) map.get("city"), (String) map.get("district"), (String) map.get("name")+"别墅", "district"); + } + if(null == district){ + district = districtService.findByNameAndAlias((String) map.get("city"), (String) map.get("district"), (String) map.get("name"), "district"); + } + } } } @@ -2482,7 +2527,7 @@ public class PropertyController { model.setMax(100); } - List districtNames = new ArrayList(); + Set districtNames = new HashSet(); if (null == district) { districtNames.add(model.getName()); } else { @@ -2490,14 +2535,56 @@ public class PropertyController { if (district.getAlias() != null) { districtNames.addAll(district.getAlias()); } - } - List dealPrices = null; - for (String name : districtNames) { - dealPrices = findDealPricesByName(model.getCity(), model.getDistrict(), name, model.getMax() * 5, model); - if (!dealPrices.isEmpty()) { - break; + final String masterDistrictName = district.getMasterDistrictName(); + if (StringUtils.isNotBlank(masterDistrictName)) { + List districts; + if ("master".equals(masterDistrictName)) { + // 所有的分期数据 + districts = districtService.findSlaves(model.getCity(), model.getDistrict(), model.getName()); + } else { + // 根据主小区名查询所有名称 + districts = districtService.findSlaves(model.getCity(), model.getDistrict(), masterDistrictName); + } + if (CollectionUtils.isNotEmpty(districts)) { + for (District districtTemp : districts) { + districtNames.add(districtTemp.getName()); + } + } + + // districtNames 不包含 主小区名,加进去 + if (!districtNames.contains(masterDistrictName)){ + districtNames.add(masterDistrictName); + } + } } + // 将搜房中的别名与名称加入查询集合 + try { + List aliasFangs = aliasFangService.findFangByNameAndAlias(model.getCity(), model.getDistrict(), districtNames); + Set aliasSet = new HashSet(); + for (AliasFang aliasFang : aliasFangs) { + if (StringUtils.isNotBlank(aliasFang.getName())) { + aliasSet.add(aliasFang.getName()); + } + if (StringUtils.isNotBlank(aliasFang.getAlias())) { + aliasSet.add(aliasFang.getAlias()); + } + } + districtNames.addAll(aliasSet); + } catch (Exception ex) { + ex.printStackTrace(); + } + + +// List dealPrices = new ArrayList(); + // 将主名与映射别名查得成交加入 存在不能查出最新成交问题 +// for (String name : districtNames) { +// List dealPricesTempList = findDealPricesByName(model.getCity(), model.getDistrict(), name, model.getMax() * 5, model); +// if (CollectionUtils.isNotEmpty(dealPricesTempList)) { +// dealPrices.addAll(dealPricesTempList); +// } +// } + List dealPrices = findDealPricesByNames(model.getCity(), model.getDistrict(), new ArrayList(districtNames), model.getMax() * 5, model); if (model.getSize() != null) { Collections.sort(dealPrices, new Comparator() { @Override @@ -2546,15 +2633,9 @@ public class PropertyController { } deal = new LinkedHashMap(); dealPrice.setId(null); - if (district != null) { - deal.put("city", district.getCity()); - deal.put("district", district.getRegion()); - deal.put("name", district.getName()); - } else { - deal.put("city", dealPrice.getCity()); - deal.put("district", dealPrice.getRegion()); - deal.put("name", dealPrice.getDistrictName()); - } + deal.put("city", dealPrice.getCity()); + deal.put("district", dealPrice.getRegion()); + deal.put("name", dealPrice.getDistrictName()); if (dealPrice.getArea() == null) { deal.put("size", ""); } else { @@ -2773,7 +2854,7 @@ public class PropertyController { evaluation.setOtherFactor(model.getOtherFactor()); } evaluation.setRegion(model.getDistrict()); - if (0 != model.getRoom()) { + if (null != model.getRoom()) { evaluation.setRoom(model.getRoom()); } if (StringUtils.isNotBlank(model.getRoomNumber())) { @@ -3467,6 +3548,33 @@ public class PropertyController { return null; } + private List findDealPricesByNames(String city, String region, List names, int max, + DealPriceModel model) { + List params = new ArrayList(); + params.add(new QueryParam("city", city)); + params.add(new QueryParam("region", region)); + params.add(new QueryParam("districtName", QueryParam.IN_OPERATOR, names)); + if (model.getRoom() != null) { + params.add(new QueryParam("room", model.getRoom())); + } + if (model.getHall() != null) { + params.add(new QueryParam("hall", model.getHall())); + } + // 18年之后抓住的数据没有score字段 +// params.add(new QueryParam("score", QueryParam.GREATER_THAN_OPERATOR, 200000000000l)); + List dealPrices = dealPriceService.findDealPrices(params, max); + List distinctDealPrices = new ArrayList(); + for (DealPrice dealPrice : dealPrices) { + if (dealPrice.getAvgPrice() == null) { + dealPrice.setAvgPrice((int) (dealPrice.getTotalPrice() / dealPrice.getArea())); + } + if (!checkExists(distinctDealPrices, dealPrice)) { + distinctDealPrices.add(dealPrice); + } + } + return distinctDealPrices; + } + private List findDealPricesByName(String city, String region, String name, int max, DealPriceModel model) { List params = new ArrayList(); @@ -3479,7 +3587,8 @@ public class PropertyController { if (model.getHall() != null) { params.add(new QueryParam("hall", model.getHall())); } - params.add(new QueryParam("score", QueryParam.GREATER_THAN_OPERATOR, 200000000000l)); + // 18年之后抓住的数据没有score字段 +// params.add(new QueryParam("score", QueryParam.GREATER_THAN_OPERATOR, 200000000000l)); List dealPrices = dealPriceService.findDealPrices(params, max); List distinctDealPrices = new ArrayList(); for (DealPrice dealPrice : dealPrices) { @@ -4057,6 +4166,19 @@ public class PropertyController { return "fangjia.com"; } + private Integer getFloor(String roomNumber){ + if(StringUtils.isNotBlank(roomNumber) && DataUtil.isNumber(roomNumber)){ + if(roomNumber.length() == 3){ + return Integer.valueOf(roomNumber.substring(0,1)); + }else if(roomNumber.length() == 4){ + return Integer.valueOf(roomNumber.substring(0,2)); + }else{ + return null; + } + } + return null; + } + private boolean checkExists(FacetQueryResult houseBoList, NewHousePojo house) { for (NewHousePojo bo : houseBoList) { boolean sameName = bo.getName().equals(house.getName()); @@ -5517,7 +5639,7 @@ public class PropertyController { //周边相似小区租金 Integer room = null; - if(model.getRoom()!=0){ + if(model.getRoom()!=null && model.getRoom()>0){ room = model.getRoom(); }else{ room = houseService.getDistrictRoomType((float)model.getSize()); @@ -5911,4 +6033,8 @@ public class PropertyController { public void setCommunityBasePriceService(CommunityBasePriceService communityBasePriceService) { this.communityBasePriceService = communityBasePriceService; } + + public void setAliasFangService(AliasFangService aliasFangService) { + this.aliasFangService = aliasFangService; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/Test.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/Test.java new file mode 100644 index 000000000..e03484f3e --- /dev/null +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/Test.java @@ -0,0 +1,190 @@ +//package com.fangjia.open.controllers; +// +//import com.google.gson.Gson; +//import com.google.gson.JsonArray; +//import com.google.gson.JsonObject; +//import org.apache.http.HttpEntity; +//import org.apache.http.client.methods.CloseableHttpResponse; +//import org.apache.http.client.methods.HttpPost; +//import org.apache.http.entity.ContentType; +//import org.apache.http.entity.StringEntity; +//import org.apache.http.impl.client.CloseableHttpClient; +//import org.apache.http.impl.client.HttpClients; +//import org.apache.http.util.EntityUtils; +//import sun.misc.BASE64Encoder; +// +//import java.io.IOException; +//import java.net.Authenticator; +//import java.net.InetSocketAddress; +//import java.net.PasswordAuthentication; +//import java.net.Proxy; +//import java.nio.charset.Charset; +//import java.nio.charset.StandardCharsets; +//import java.util.Base64; +//import java.util.HashMap; +//import java.util.Map; +// +////public class Test { +//// public static void main(String[] args) throws IOException { +//// // 目标URL +//// String targetURL = "http://146.56.217.44:9010/uams/farmer/all/v3/sign"; +//// +//// // 设置代理 +//// String proxyHost = "tunnel2.qg.net"; +//// int proxyPort = 14186; +//// +//// // 设置代理用户名和密码 +//// final String proxyUsername = "113BBC06"; +//// final String proxyPassword = "3B2FBD05B0AF"; +//// +//// // 设置请求的JSON数据 +//// String address = "江苏省扬州市宝应县安宜镇宝应大道88号"; +//// String type = "1"; +//// String jsonData = "{\"address\":\"" + address + "\",\"type\":\"" + type + "\"}"; +//// +//// // 设置HTTP基本认证 +//// String authKey = proxyUsername; +//// String password = proxyPassword; +//// String auth = authKey + ":" + password; +//// String authHeader = "Basic " + new BASE64Encoder().encode(auth.getBytes(Charset.forName("UTF-8"))); +//// +//// // 创建HTTP客户端 +//// CloseableHttpClient httpClient = HttpClients.createDefault(); +//// HttpPost httpPost = new HttpPost(targetURL); +//// +//// // 设置代理 +//// Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); +//// +//// // 设置代理认证 +//// Authenticator.setDefault(new Authenticator() { +//// protected PasswordAuthentication getPasswordAuthentication() { +//// return new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray()); +//// } +//// }); +//// +//// // 设置请求头 +//// httpPost.setHeader("Content-Type", "application/json"); +//// httpPost.setHeader("Accept", "*/*"); +//// httpPost.setHeader("Host", "146.56.217.44:9010"); +//// httpPost.setHeader("Proxy-Authorization", authHeader); +//// +//// // 设置请求体 +//// StringEntity stringEntity = new StringEntity(jsonData, ContentType.APPLICATION_JSON); +//// httpPost.setEntity(stringEntity); +//// +//// // 发送POST请求 +//// CloseableHttpResponse httpResponse = httpClient.execute(httpPost); +//// +//// // 获取响应 +//// HttpEntity responseEntity = httpResponse.getEntity(); +//// String responseString = EntityUtils.toString(responseEntity); +//// System.out.println(responseString); +//// +//// // 关闭连接 +//// httpResponse.close(); +//// httpClient.close(); +//// } +////} +// +//public class Test { +// public static void main(String[] args) throws IOException { +// Map map = senRequest("江苏省泰州市靖江市通江路37号", "1"); +// System.out.println(map); +// +// } +// +// private static Map senRequest(String address, String type) throws IOException { +// String targetURL = "http://146.56.217.44:9010/uams/farmer/all/v3/sign"; +// String proxyHost = "tunnel2.qg.net"; +// int proxyPort = 14186; +// final String proxyUsername = "113BBC06"; +// final String proxyPassword = "3B2FBD05B0AF"; +// String jsonData = "{\"address\":\"" + address + "\",\"type\":\"" + type + "\"}"; +// String authKey = proxyUsername; +// String password = proxyPassword; +// String auth = authKey + ":" + password; +// String authHeader = "Basic " + new BASE64Encoder().encode(auth.getBytes(Charset.forName("UTF-8"))); +// +// CloseableHttpClient httpClient = HttpClients.createDefault(); +// HttpPost httpPost = new HttpPost(targetURL); +// Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); +// Authenticator.setDefault(new Authenticator() { +// protected PasswordAuthentication getPasswordAuthentication() { +// return new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray()); +// } +// }); +// httpPost.setHeader("Content-Type", "application/json"); +// httpPost.setHeader("Accept", "*/*"); +// httpPost.setHeader("Host", "146.56.217.44:9010"); +// httpPost.setHeader("Proxy-Authorization", authHeader); +// StringEntity stringEntity = new StringEntity(jsonData, ContentType.APPLICATION_JSON); +// httpPost.setEntity(stringEntity); +// +// CloseableHttpResponse httpResponse = null; +// int retryCount = 2; // 设置重试次数 +// int retryDelay = 10; // 设置重试延迟时间(毫秒) +// boolean success = false; +// for (int i = 0; i < retryCount; i++) { +// try { +// httpResponse = httpClient.execute(httpPost); +// success = true; +// break; +// } catch (IOException e) { +// System.err.println("代理请求失败,进行重试..."); +// try { +// Thread.sleep(retryDelay); +// } catch (InterruptedException ex) { +// Thread.currentThread().interrupt(); +// } +// } +// } +// +// if (success) { +// HttpEntity responseEntity = httpResponse.getEntity(); +// String responseString = EntityUtils.toString(responseEntity); +// +// // 使用 Gson 解析 JSON 字符串 +// Gson gson = new Gson(); +// JsonObject jsonObject = gson.fromJson(responseString, JsonObject.class); +// +// +// // 创建 Map 存储各个值 +// Map dataMap = new HashMap(); +// +// // 获取各个值并放入 Map +// dataMap.put("code", jsonObject.get("code").getAsString()); +// dataMap.put("msg", jsonObject.get("msg").getAsString()); +// JsonObject data = jsonObject.getAsJsonObject("data"); +// dataMap.put("version", data.get("version").getAsString()); +// dataMap.put("province", data.get("province").getAsString()); +// dataMap.put("city", data.get("city").getAsString()); +// dataMap.put("district", data.get("district").getAsString()); +// dataMap.put("town", data.get("town").getAsString()); +// dataMap.put("village", data.get("village").getAsString()); +// dataMap.put("provinceCode", data.get("provinceCode").getAsString()); +// dataMap.put("cityCode", data.get("cityCode").getAsString()); +// dataMap.put("districtCode", data.get("districtCode").getAsString()); +// dataMap.put("townCode", data.get("townCode").getAsString()); +// dataMap.put("villageCode", data.get("villageCode").getAsString()); +// dataMap.put("areaCode", data.get("areaCode").getAsString()); +// dataMap.put("farmer", data.get("farmer").getAsString()); +// dataMap.put("isGovt", data.get("isGovt").getAsString()); +// dataMap.put("govtAddr", data.get("govtAddr").isJsonNull() ? null : data.get("govtAddr").getAsString()); // 对于可能为 null 的值,需要判断是否为空 +// JsonArray indusParkList = data.get("indusParkList").isJsonNull() ? null : data.get("indusParkList").getAsJsonArray(); +// if (indusParkList != null) { +// JsonObject jsonObject1 = gson.fromJson(indusParkList.get(0), JsonObject.class); +// dataMap.put("devName",jsonObject1.get("indusParkName").getAsString()); +// dataMap.put("devLevel",jsonObject1.get("indusParkLevel").getAsString()); +// } +// +// httpResponse.close(); +// return dataMap; +// } else { +// System.err.println("重试次数已用完,请求失败。"); +// } +// +// httpClient.close(); +// return null; +// } +//} +// diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/TestController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/TestController.java new file mode 100644 index 000000000..07fbed914 --- /dev/null +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/TestController.java @@ -0,0 +1,1608 @@ +/* +package com.fangjia.open.controllers; + +import com.fangjia.core.util.*; +import com.fangjia.dal.common.DistrictKey; +import com.fangjia.dal.mongo.fangjia.model.ServerArea; +import com.fangjia.dal.mongo.model.ApiUserCfg; +import com.fangjia.dal.mongo.model.DistrictFacilitys; +import com.fangjia.dal.mongo.model.Evaluation; +import com.fangjia.dal.mongo.model.FangjiaOfficialAreaMap; +import com.fangjia.dal.mongo.model.bkoff.Loudong; +import com.fangjia.dal.mongo.open.model.ApiUserAuthority; +import com.fangjia.dal.mongo.open.model.EvaluateRatio; +import com.fangjia.dal.seaweed.model.District; +import com.fangjia.open.HttpCode; +import com.fangjia.open.OpenHttpCodeEnum; +import com.fangjia.open.dto.HouseValueInformationDto; +import com.fangjia.open.dto.UniversalDto; +import com.fangjia.open.dto.addressGovernance.MatchedBuildingDto; +import com.fangjia.open.interceptors.AuthenticationBean; +import com.fangjia.open.model.*; +import com.fangjia.open.util.CommonDtoUtils; +import com.fangjia.open.util.CommonUtils; +import com.fangjia.open.ws.query.SampleQuery; +import com.fangjia.service.api.AddressMatchProxyService; +import com.fangjia.service.api.ApiUserCfgService; +import com.fangjia.service.bo.Collateral; +import com.fangjia.service.bo.DistrictStatBo; +import com.fangjia.service.bo.Sample; +import com.fangjia.service.datastore.*; +import com.fangjia.service.datastore.bean.CollateralSampleQueryBean; +import com.fangjia.service.district.*; +import com.fangjia.service.mongo.bkoff.HouseLoudongService; +import com.fangjia.service.mongo.bkoff.LoudongService; +import com.fangjia.service.mongo.fangjia.*; +import com.fangjia.service.open.*; +import com.fangjia.service.tool.OpenLogService; +import com.fangjia.service.web.AddressService; +import net.sf.json.JSONObject; +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.time.DateUtils; +import org.slf4j.Logger; +import org.sothis.web.mvc.ActionContext; +import org.sothis.web.mvc.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import java.text.ParseException; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static com.poseidon.util.TypeConverter.convertToString; + +*/ +/** + * @author 13607 + * @since 2023/12/12 10:29 + *//* + + + +public class TestController { + private DistrictService districtService; + + private DistrictStatService districtStatService; + + private FangjiaOfficialAreaService fangjiaOfficialAreaService; + private AddressMatchProxyService addressMatchProxyService; + + private static final Logger LOGGER = LoggerFactory.getLogger(PropertyController.class); + private HouseLoudongService houseLoudongService; + private LoudongService loudongService; + private EvaluationService evaluationService; + private BatchEvaluateService batchEvaluateService; + private ApiUserAuthorityService apiUserAuthorityService; + private AverageStatisticsService averageStatisticsService; + private ServerAreaService serverAreaService; + private ApiUserCfgService apiUserCfgService; + private OpenApiLogService openApiLogService; + private EvaluateFactorService evaluateFactorService; + + private CzbankSampleService czbankSampleService; + + private DistrictFacilitysService districtFacilitysService; + + private static final int DEFAULT_PAGE_SIZE = 20; + private static final String[] PROPERTY_SEARCH_API_FIELDS = {"address", "city", "region", "name", "lat2", "lng2", "lat", "lng", "block", "estateType2", "addrAlias"}; + static final int BAI_DU_GEO = 1;// 百度系坐标 + static final int GAO_DE_GEO = 2;// 高德系坐标 + + + private EvaluateRatioService evaluateRatioService; + + private static final int EVALUATE_SHOW_DETAIL = 1; + private static final Map PROPERTY_TYPES = new HashMap() { + { + put(null, "普通住宅"); + put("0", "普通住宅"); + put("1", "别墅"); + put("2", "商住"); + } + }; + + private static final Map DIRECTION = new HashMap() { + { + put(null, "南"); + put("1", "西南"); + put("2", "东南"); + put("3", "南"); + put("4", "西北"); + put("5", "东北"); + put("6", "东"); + put("7", "西"); + put("8", "北"); + put("9", "东西"); + put("10", "南北"); + } + }; + + private static final Map FITMENT = new HashMap() { + { + put(null, "简装"); + put("1", "毛坯"); + put("2", "简装"); + put("3", "精装"); + put("4", "豪装"); + } + }; + + private static final Map EVALUATION_MODEL_FITMENT = new HashMap() { + { + put(null, "简单装修"); + put("简装", "简单装修"); + put("毛坯", "毛坯"); + put("精装", "精装修"); + put("豪装", "豪华装修"); + } + }; + + private static final Map SIGHT = new HashMap() { + { + put(null, "一般"); + put("1", "景观房"); + put("2", "侧景观房"); + put("3", "一般"); + put("4", "差"); + } + }; + + private static final Map NOISE = new HashMap() { + { + put(null, "无噪音"); + put("0", "无噪音"); + put("1", "噪音较小"); + put("2", "噪音大"); + } + }; + private static final Map FACILITIES = new HashMap() { + { + put("0", "健身房"); + put("1", "游泳池"); + put("2", "会所"); + put("3", "网球场"); + put("4", "球场"); + put("5", "棋牌室"); + put("6", "停车场"); + put("7", "图书馆"); + put("8", "活动中心"); + } + }; + + private static final Map NEGATIVE_FACTOR = new HashMap() { + { + put(null, "无"); + put("1", "很近"); + put("2", "较近"); + put("3", "无"); + } + }; + + + Map listKeyMap = new HashMap() { + { + put("school", "schools"); + put("hospital", "hospitals"); + put("bank", "banks"); + put("supermarket", "supermarkets"); + put("market", "markets"); + put("beautySalon", "beautySalons"); + put("gym", "gyms"); + put("park", "parks"); + put("bus", "buses"); + put("metro", "metros"); + put("dock", "docks"); + put("airport", "airports"); + put("trainStation", "trainStations"); + put("restaurant", "restaurants"); + put("hotel", "hotels"); + } + }; + + private static final Map CITYLEVEL_MAP = new HashMap() { + { + put("1000", "one");// 一线 + put("1500", "newOne");// 新一线 + put("2000", "two");// 二线 + put("3000", "three");// 三线 + put("4000", "four");// 四线 + put("5000", "five");// 五线 + } + }; + + + //全局json + private JSONObject globalJson = null; + + + public Object houseValueInformationAction(HouseInfomationModel model, HttpServletRequest httpServletRequest) throws IllegalAccessException, HttpRequestException { + + HouseValueInformationDto houseValueInformation = new HouseValueInformationDto(); + RestfulModelAndView mav = new RestfulModelAndView(); + + if (StringUtils.isBlank(model.getAddress()) || StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(String.valueOf(model.getSize()))) { + mav.setModel(BasicModel.buildBadRequestModel("城市(city),地址(address),面积(size)为必填字段")); + return mav; + } + + HttpRequest httpRequest = new HttpRequest(); + + Map communityAvgPriceParams = new HashMap(); + communityAvgPriceParams.put("city", model.getCity()); + communityAvgPriceParams.put("address", model.getAddress()); + communityAvgPriceParams.put("category", model.getCategory()); + communityAvgPriceParams.put("useMap", String.valueOf(model.isUseMap())); + globalJson = httpRequest.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", communityAvgPriceParams, "UTF-8"); + + // 创建线程池 + ExecutorService executorService = Executors.newFixedThreadPool(5); + + Future avgPriceFuture = executorService.submit(new UpdateCommunityAvgPriceCallable(globalJson, mav)); + Future> future2 = executorService.submit(new UpdateAddressValueCallable( globalJson, model, mav, httpServletRequest)); + Future future3 = executorService.submit(new UpdateHouseCaseCallable(houseValueInformation, globalJson, model, mav)); + Future future4 = executorService.submit(new UpdateSurroundingPoiCallable(houseValueInformation, globalJson, model, mav)); + + try { + // 获取线程任务的返回结果 + MatchedBuildingDto avgPrice = avgPriceFuture.get(); + if (avgPrice!=null){ + houseValueInformation.setCommunityAvgPrice(avgPrice); + }else { + mav.setModel(BasicModel.buildServerErrorModel().setMsg("服务升级中...")); + } + Map result2 = future2.get(); + UniversalDto result3 = future3.get(); + DistrictFacilitys result4 = future4.get(); + + // 根据需要处理返回结果 + // ... + } catch (Exception e) { + // 处理异常 + e.printStackTrace(); + } + + + // 关闭线程池 + executorService.shutdown(); + return mav; + + + } + + private class UpdateCommunityAvgPriceCallable implements Callable { + private JSONObject globalJson; + private ModelAndView mav; + + public UpdateCommunityAvgPriceCallable( JSONObject globalJson, ModelAndView mav) { + this.globalJson = globalJson; + this.mav = mav; + } + + @Override + public MatchedBuildingDto call() throws Exception { + synchronized (globalJson) { + + try { + //新匹配接口 + JSONObject json = globalJson; + BasicModel basicModel = new BasicModel(200, "ok"); + if (json != null && json.size() > 0) { + MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); + + District district = districtService.findByNameAndAlias(dto.getCity(), dto.getDistrict(), dto.getName(), "district"); + if (null != district) { + DistrictStatBo statBo = districtStatService.findCurrentDistrictStat(new DistrictKey(dto.getCity(), dto.getDistrict(), dto.getName())); + if (null != statBo) { + if (statBo.getDistrictStat() != null) { + dto.setAvgPrice(statBo.getDistrictStat().getAvgPrice()); + } else if (statBo.getVillaDistrictStat() != null) { + dto.setAvgPrice(statBo.getVillaDistrictStat().getAvgPrice()); + } + + } + } +// basicModel.setResult(dto); + // 保存小区均价的返回结果 + return dto; + } + } catch (Exception e) { + e.printStackTrace(); + return null; + } + return null; + } + } + } + + private class UpdateAddressValueCallable implements Callable { + private JSONObject globalJson; + + private HouseInfomationModel model; + + private RestfulModelAndView mav; + private HttpServletRequest httpServletRequest; + + public UpdateAddressValueCallable(JSONObject globalJson, HouseInfomationModel model, RestfulModelAndView mav, HttpServletRequest httpServletRequest) { + this.globalJson = globalJson; + this.model = model; + this.mav = mav; + this.httpServletRequest = httpServletRequest; + } + + @Override + public MatchedBuildingDto call() throws Exception { + //根据model给PropertyEvaluationModel赋值 + PropertyEvaluationModel propertyEvaluationModel = createPropertyEvaluationModelFromHouseInfomationModel(model); + +// RestfulModelAndView propertyEvaluationMav = new RestfulModelAndView(); +// mav.setViewType("rest"); +// if (StringUtils.isBlank(propertyEvaluationModel.getCity()) || StringUtils.isBlank(propertyEvaluationModel.getAddress()) || propertyEvaluationModel.getSize() <= 0) { +// mav.setModel(BasicModel.buildBadRequestModel("参数非法:城市,地址,面积(size)为必填项")); +// return mav; +// } + if (propertyEvaluationModel.getDistrict() != null) { + //区域编码转房价网区域 + FangjiaOfficialAreaMap fangjiaOfficialAreaMap = fangjiaOfficialAreaService.convertOfficialCodeToFangjia(propertyEvaluationModel.getDistrict()); + if (fangjiaOfficialAreaMap != null) { + propertyEvaluationModel.setDistrict(fangjiaOfficialAreaMap.getFangjiaDistrict()); + } + } + + boolean villaFlag = DataUtil.isVilla(propertyEvaluationModel.getSize(), propertyEvaluationModel.getName(), propertyEvaluationModel.getHeight(), propertyEvaluationModel.getRoom()); + + District district = null; + Map params = new HashMap(); + params.put("city", propertyEvaluationModel.getCity()); + if (StringUtils.isNotBlank(propertyEvaluationModel.getDistrict())) { + params.put("suggestDistrict", propertyEvaluationModel.getDistrict()); + } + params.put("address", propertyEvaluationModel.getAddress()); + if (StringUtils.isNotBlank(propertyEvaluationModel.getName())) { + params.put("suggestName", propertyEvaluationModel.getName()); + } + params.put("category", "district"); + String result = addressMatchProxyService.parser(params); + if (result != null) { + JSONObject json = globalJson; + json = JSONObject.fromObject(result); + if (json.getInt("code") == 200) { + Map map = (Map) json.get("result"); + if ((Integer) map.get("precise") >= 0) { + String propertyType = (String) map.get("propertyType"); + if (villaFlag && StringUtils.isNotBlank(propertyType) && !propertyType.equals("别墅")) { + district = districtService.findByNameAndAlias((String) map.get("city"), (String) map.get("district"), (String) map.get("name") + "别墅", "district"); + } + if (null == district) { + district = districtService.findByNameAndAlias((String) map.get("city"), (String) map.get("district"), (String) map.get("name"), "district"); + } + + } + } + } + + if (district == null) { + mav.setModel(BasicModel.buildBadRequestModel("该地址不支持估价!")); +// return mav; + } + propertyEvaluationModel.setDistrict(district.getRegion()); + propertyEvaluationModel.setName(district.getName()); + try { + evaluateAction(propertyEvaluationModel, httpServletRequest, mav); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + } + + private class UpdateAddressValueRunnable implements Runnable { + private HouseValueInformationDto houseValueInformation; + + private JSONObject globalJson; + + private HouseInfomationModel model; + + private RestfulModelAndView mav; + private HttpServletRequest httpServletRequest; + + public UpdateAddressValueRunnable(HouseValueInformationDto houseValueInformation, JSONObject globalJson, HouseInfomationModel model, RestfulModelAndView mav, HttpServletRequest httpServletRequest) { + this.houseValueInformation = houseValueInformation; + this.globalJson = globalJson; + this.model = model; + this.mav = mav; + this.httpServletRequest = httpServletRequest; + } + + @Override + public void run() { + //根据model给PropertyEvaluationModel赋值 + PropertyEvaluationModel propertyEvaluationModel = createPropertyEvaluationModelFromHouseInfomationModel(model); + +// RestfulModelAndView propertyEvaluationMav = new RestfulModelAndView(); +// mav.setViewType("rest"); +// if (StringUtils.isBlank(propertyEvaluationModel.getCity()) || StringUtils.isBlank(propertyEvaluationModel.getAddress()) || propertyEvaluationModel.getSize() <= 0) { +// mav.setModel(BasicModel.buildBadRequestModel("参数非法:城市,地址,面积(size)为必填项")); +// return mav; +// } + if (propertyEvaluationModel.getDistrict() != null) { + //区域编码转房价网区域 + FangjiaOfficialAreaMap fangjiaOfficialAreaMap = fangjiaOfficialAreaService.convertOfficialCodeToFangjia(propertyEvaluationModel.getDistrict()); + if (fangjiaOfficialAreaMap != null) { + propertyEvaluationModel.setDistrict(fangjiaOfficialAreaMap.getFangjiaDistrict()); + } + } + + boolean villaFlag = DataUtil.isVilla(propertyEvaluationModel.getSize(), propertyEvaluationModel.getName(), propertyEvaluationModel.getHeight(), propertyEvaluationModel.getRoom()); + + District district = null; + Map params = new HashMap(); + params.put("city", propertyEvaluationModel.getCity()); + if (StringUtils.isNotBlank(propertyEvaluationModel.getDistrict())) { + params.put("suggestDistrict", propertyEvaluationModel.getDistrict()); + } + params.put("address", propertyEvaluationModel.getAddress()); + if (StringUtils.isNotBlank(propertyEvaluationModel.getName())) { + params.put("suggestName", propertyEvaluationModel.getName()); + } + params.put("category", "district"); + String result = addressMatchProxyService.parser(params); + if (result != null) { + JSONObject json = globalJson; + json = JSONObject.fromObject(result); + if (json.getInt("code") == 200) { + Map map = (Map) json.get("result"); + if ((Integer) map.get("precise") >= 0) { + String propertyType = (String) map.get("propertyType"); + if (villaFlag && StringUtils.isNotBlank(propertyType) && !propertyType.equals("别墅")) { + district = districtService.findByNameAndAlias((String) map.get("city"), (String) map.get("district"), (String) map.get("name") + "别墅", "district"); + } + if (null == district) { + district = districtService.findByNameAndAlias((String) map.get("city"), (String) map.get("district"), (String) map.get("name"), "district"); + } + + } + } + } + + if (district == null) { + mav.setModel(BasicModel.buildBadRequestModel("该地址不支持估价!")); +// return mav; + } + propertyEvaluationModel.setDistrict(district.getRegion()); + propertyEvaluationModel.setName(district.getName()); + try { + evaluateAction(propertyEvaluationModel, httpServletRequest, houseValueInformation, mav); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + } + + private class UpdateHouseCaseRunnable implements Runnable { + private HouseValueInformationDto houseValueInformation; + + private JSONObject globalJson; + + private HouseInfomationModel model; + private RestfulModelAndView mav; + + public UpdateHouseCaseRunnable(HouseValueInformationDto houseValueInformation, JSONObject globalJson, HouseInfomationModel model, RestfulModelAndView mav) { + this.houseValueInformation = houseValueInformation; + this.globalJson = globalJson; + this.model = model; + this.mav = mav; + } + + @Override + public void run() { + //房源样本 + + //构造sampleQuery对象 + SampleQuery sampleQuery = new SampleQuery(); + sampleQuery.setCity(model.getCity()); + sampleQuery.setStrctureArea(model.getSize()); + sampleQuery.setAddress(model.getAddress()); + +// RestfulModelAndView houseCaseMav = new RestfulModelAndView(); + List querys = null; + try { + querys = convertSampileQueryToBean(sampleQuery); + } catch (Exception e) { + mav.setModel(BasicModel.buildBadRequestModel(e.getMessage())); + } + if (null == sampleQuery.getMax()) { + sampleQuery.setMax(10); + } + // 此处慢 + long start = System.currentTimeMillis(); + List collaterals = czbankSampleService.findSample2(querys, sampleQuery.getMax()); + long end = System.currentTimeMillis(); + System.out.println("用时:" + (end - start)); + Collateral collateral = collaterals.get(0); + List samples = collateral.getSample(); + UniversalDto dto = UniversalDto.newDto(); + if (null != collateral.getMaxPrice()) { + dto.append("maxUnitPrice", collateral.getMaxPrice()); + } + if (null != collateral.getMinPrice()) { + dto.append("minUnitPrice", collateral.getMinPrice()); + } + dto.append("datas", samples); + houseValueInformation.setHouseCase(dto); + + } + } + + private class UpdateSurroundingPoiRunnable implements Runnable { + private HouseValueInformationDto houseValueInformation; + + private JSONObject globalJson; + + private HouseInfomationModel model; + private RestfulModelAndView mav; + + public UpdateSurroundingPoiRunnable(HouseValueInformationDto houseValueInformation, JSONObject globalJson, HouseInfomationModel model, RestfulModelAndView mav) { + this.houseValueInformation = houseValueInformation; + this.globalJson = globalJson; + this.model = model; + this.mav = mav; + } + + @Override + public void run() { + //周边POI + +// RestfulModelAndView mav = new RestfulModelAndView(); +// mav.setViewType("rest"); + if (StringUtils.isBlank(model.getAddress())) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.ARGUMENT_LOSE, "地址必须输入")); +// return mav; + } else { + String cat = "district"; + + HttpRequest request = new HttpRequest(); +// json = null; +// Map poiParams = new HashMap(); +// poiParams.put("city", model.getCity()); +// poiParams.put("address", model.getAddress()); +// poiParams.put("category", "property"); + //新匹配接口 +// json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", poiParams, "UTF-8"); + JSONObject json = globalJson; + District property = null; + if (json != null && json.size() > 0) { + MatchedBuildingDto matchedBuildingDto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); + property = districtService.findByNameAndAlias(matchedBuildingDto.getCity(), matchedBuildingDto.getDistrict(), matchedBuildingDto.getName(), cat); + if (null == property) { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "小区数据不存在")); +// return mav; + } + DistrictFacilitys facilitys = districtFacilitysService.findByDistrict(property); +// mav.setModel(BasicModel.buildOKModel().setResult(facilitys)); + // 将周边POI数据放到结果集 + houseValueInformation.setSurroundingPoi(facilitys); + } else { + mav.setModel(new HttpCode(OpenHttpCodeEnum.TARGET_DATA_NOT_EXIST, "小区数据不存在")); + } + } +// return mav; +// houseValueInformation.setSurroundingPoi(mav); + + mav.setModel(BasicModel.buildOKModel().setResult(houseValueInformation)); +// return mav; + } + } + + private PropertyEvaluationModel createPropertyEvaluationModelFromHouseInfomationModel(HouseInfomationModel model) { + PropertyEvaluationModel propertyModel = new PropertyEvaluationModel(); + propertyModel.setCity(model.getCity()); + propertyModel.setAddress(model.getAddress()); + propertyModel.setSize(model.getSize()); + + if (StringUtils.isNotBlank(model.getDistrict())) { + propertyModel.setDistrict(model.getDistrict()); + } + if (StringUtils.isNotBlank(model.getName())) { + propertyModel.setName(model.getName()); + } + if (StringUtils.isNotBlank(model.getBuildingNumber())) { + propertyModel.setBuildingNumber(model.getBuildingNumber()); + } + if (StringUtils.isNotBlank(model.getUnitNumber())) { + propertyModel.setUnitNumber(model.getUnitNumber()); + } + if (model.getFloor() != null && model.getFloor() != 0) { + propertyModel.setFloor(model.getFloor()); + } + if (model.getMaxFloor() != null && model.getMaxFloor() != 0) { + propertyModel.setMaxFloor(model.getMaxFloor()); + } + if (model.getRoom() != null && model.getRoom() != 0) { + propertyModel.setRoom(model.getRoom()); + } + if (model.getHall() != 0) { + propertyModel.setHall(model.getHall()); + } + if (model.getToilet() != 0) { + propertyModel.setToilet(model.getToilet()); + } + if (model.getCalDate() != null) { + propertyModel.setCalDate(model.getCalDate()); + } + if (model.getPropertyType() != null) { + propertyModel.setPropertyType(model.getPropertyType()); + } + if (StringUtils.isNotBlank(model.getDirection())) { + propertyModel.setDirection(model.getDirection()); + } + if (StringUtils.isNotBlank(model.getDecoration())) { + propertyModel.setDecoration(model.getDecoration()); + } + + if (model.getDecorationCost() != null && model.getDecorationCost() != 0) { + propertyModel.setDecorationCost(model.getDecorationCost()); + } + + if (model.getDecorationAge() != 0) { + propertyModel.setDecorationAge(model.getDecorationAge()); + } + if (StringUtils.isNotBlank(model.getView())) { + propertyModel.setView(model.getView()); + } + if (StringUtils.isNotBlank(model.getNoise())) { + propertyModel.setNoise(model.getNoise()); + } + if (model.getGardenSize() != null && model.getGardenSize() != 0) { + propertyModel.setGardenSize(model.getGardenSize()); + } + if (model.getBasementSize() != null && model.getBasementSize() != 0) { + propertyModel.setBasementSize(model.getBasementSize()); + } + if (model.getOuterSize() != null && model.getOuterSize() != 0) { + propertyModel.setOuterSize(model.getOuterSize()); + } + if (model.getAtticSize() != null && model.getAtticSize() != 0) { + propertyModel.setAtticSize(model.getAtticSize()); + } + if (StringUtils.isNotBlank(model.getNegativeFactor())) { + propertyModel.setNegativeFactor(model.getNegativeFactor()); + } + if (model.getAge() != 0) { + propertyModel.setAge(model.getAge()); + } + if (model.getCarportPrice() != null && model.getCarportPrice() != 0) { + propertyModel.setCarportPrice(model.getCarportPrice()); + } + + if (StringUtils.isNotBlank(model.getFacilities())) { + propertyModel.setFacilities(model.getFacilities()); + } + if (StringUtils.isNotBlank(model.getInsidePosition())) { + propertyModel.setInsidePosition(model.getInsidePosition()); + } + return propertyModel; + } + + private List convertSampileQueryToBean(SampleQuery... queries) throws Exception { + + List queryBeans = new ArrayList(queries.length); + for (SampleQuery q : queries) { + + CollateralSampleQueryBean queryBean = new CollateralSampleQueryBean(); + BeanUtils.copyProperties(q, queryBean); +// String propertyTypeCode = queryBean.getPropertyTypeCode(); +// if(!Arrays.asList("01", "02", "03").contains(propertyTypeCode)){ +// throw new Exception("propertyTypeCode取值非法"); +// } + String cat = "district"; + + if (StringUtils.isNotBlank(queryBean.getCity()) && StringUtils.isNotBlank(queryBean.getDistrict()) && StringUtils.isNotBlank(queryBean.getBuildingName())) { + District property = districtService.findByNameAndAlias(queryBean.getCity(), queryBean.getDistrict(), queryBean.getBuildingName(), cat); + if (property == null) { + throw new Exception("未找到该小区"); + } + queryBean.setProperty(property); + } else if (StringUtils.isNotBlank(queryBean.getAddress())) { + HttpRequest request = new HttpRequest(); + JSONObject json = null; + String address = queryBean.getAddress().replace(" ", "").replace("%", ""); +// Map params = new HashMap(); +// params.put("city", queryBean.getCity()); +// params.put("address", address); +// params.put("category", "property"); + //新匹配接口 +// json = request.getJsonContent("http://192.168.0.100:32080/FangJiaNlpService/match", params, "UTF-8"); + json = globalJson; + if (json != null && json.size() > 0) { + MatchedBuildingDto dto = CommonDtoUtils.transformV(MatchedBuildingDto.class, json); + District property = districtService.findByNameAndAlias(dto.getCity(), dto.getDistrict(), dto.getName(), cat); + if (property == null) { + throw new Exception("未找到该小区"); + } + queryBean.setProperty(property); + } else { + throw new Exception("未找到该小区"); + } + } + String estateType = queryBean.getProperty().getEstateType2(); + queryBean.setPropertyTypeCode("01"); + if (StringUtils.isNotBlank(estateType)) { + if (estateType.equals("普通住宅")) { + queryBean.setPropertyTypeCode("01"); + } else if (estateType.equals("别墅")) { + queryBean.setPropertyTypeCode("02"); + } else if (estateType.equals("商住")) { + queryBean.setPropertyTypeCode("03"); + } + } + + Integer decrCondCode = queryBean.getDecrCondCode(); + if (decrCondCode == null) { + decrCondCode = 2; + } + if (decrCondCode > 5 || decrCondCode < 1) { + throw new Exception("decrCondCode取值非法"); + } + Integer towardDirectCode = queryBean.getTowardDirectCode(); + if (towardDirectCode == null) { + towardDirectCode = 3; + } + if (towardDirectCode > 10 || towardDirectCode < 1) { + throw new Exception("towardDirectCode取值非法"); + } + queryBeans.add(queryBean); + } + return queryBeans; + } + + private void adjustPriceByRatio(District district, Evaluation evaluation) { + + try { + ApiUserCfg apiUserCfg_pt = apiUserCfgService.findByUserId(Long.valueOf(evaluation.getFromUserId()), ApiUserCfg.ApiUserCfgKey.PRICE_TYPE); + if (apiUserCfg_pt != null && apiUserCfg_pt.getCfgValue() != null) { + String priceType = apiUserCfg_pt.getCfgValue().toString(); + // 评估价则系数调整 + if (StringUtils.isNotBlank(priceType) && "evaluate".equals(priceType)) { + EvaluateRatio evaluateRatio = null; + if (StringUtils.isNotBlank(district.getRegion())) { + evaluateRatio = evaluateRatioService.findByCityAndRegion(district.getCity(), district.getRegion()); + } + if (evaluateRatio == null) { + evaluateRatio = evaluateRatioService.findByCity(district.getCity()); + } + if (evaluateRatio != null) { + // 系数添加 + long totalPrice = evaluation.getBigTotalPrice(); + totalPrice = (long) (totalPrice * (1 + evaluateRatio.getRatio())); + evaluation.setBigTotalPrice(totalPrice); + evaluation.setAvgPrice((int) (totalPrice / evaluation.getArea())); + } + } + } + } catch (Exception ex) { + LOGGER.error("系数下调异常{}", ex.getMessage()); + } + } + + public Object evaluateAction(PropertyEvaluationModel model, HttpServletRequest request, HouseValueInformationDto houseValueInformation, RestfulModelAndView mav) + throws NumberFormatException, IllegalAccessException { +// RestfulModelAndView mav = new RestfulModelAndView(); +// mav.setViewType("rest"); + if (StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(model.getName()) + || StringUtils.isBlank(model.getDistrict()) || model.getSize() <= 0) { + mav.setModel(BasicModel.buildBadRequestModel("参数非法:城市,区域,小区名,面积(size)为必填项")); + return mav; + } + if (model.getCity().endsWith("市")) { + model.setCity(model.getCity().replaceAll("市$", "")); + } + if (StringUtils.isNotBlank(request.getParameter("calDate"))) { + Date calDate = null; + try { + calDate = DateUtils.parseDate(request.getParameter("calDate"), new String[]{"yyyy-MM-dd"}); + } catch (ParseException e) { + + } + if (calDate == null) { + mav.setModel(BasicModel.buildBadRequestModel("calDate:数据类型不合法")); + return mav; + } else { + model.setCalDate(calDate); + } + } +// 先到CPDB库中查找小区 + + District district = districtService.findByNameAndAlias(model.getCity(), model.getDistrict(), model.getName(), + "district"); + if (district == null) { + if (model.getDistrict().contains("市辖区") || model.getDistrict().contains(model.getCity())) { + district = districtService.findByNameAndAlias(model.getCity(), null, model.getName(), "district"); + } + if (district == null) { + mav.setModel(BasicModel.buildBadRequestModel("该小区不存在")); + return mav; + } + } + model.setName(district.getName()); + + if (model.getCarportPrice() != null && (model.getCarportPrice() < 0 || model.getCarportPrice() > 1000000)) { + mav.setModel(BasicModel.buildBadRequestModel("carportPrice(车位)取值不合法")); + return mav; + } + if (model.getMaxFloor() != null && (model.getMaxFloor() <= 0 || model.getMaxFloor() > 59)) { + mav.setModel(BasicModel.buildBadRequestModel("maxFloor取值非法,正确范围[1,60)")); + return mav; + } + + if (model.getFloor() != null && (model.getFloor() <= 0 || model.getFloor() > 59)) { + mav.setModel(BasicModel.buildBadRequestModel("floor取值非法,正确范围[1,60)")); + return mav; + } + if (model.getMaxFloor() != null && model.getFloor() != null && model.getFloor() > model.getMaxFloor()) { + mav.setModel(BasicModel.buildBadRequestModel("所在楼层不能大于总楼层")); + return mav; + } + + if (model.getFloor() == null) { + JSONObject structureOb = addressMatchProxyService.addressStructure(district.getCity(), model.getAddress()); + if (structureOb != null) { + if (structureOb.containsKey("buildingNumber")) { + model.setBuildingNumber(structureOb.getString("buildingNumber")); + } + + if (structureOb.containsKey("roomNumber")) { + String roomNumber = structureOb.getString("roomNumber"); + model.setFloor(getFloor(roomNumber)); + } + + } + } + + if (model.getMaxFloor() == null && model.getFloor() != null && StringUtils.isNotBlank(model.getBuildingNumber())) { + Loudong loudong = loudongService.findForEvaluate(district.getId(), model.getBuildingNumber(), model.getUnitNumber()); + if (loudong != null && loudong.getFloors() >= model.getFloor()) { + model.setMaxFloor(loudong.getFloors()); + } + } + model.setRegion(district.getRegion()); + model.setDistrictName(district.getName()); + if (StringUtils.isBlank(model.getPropertyType())) { + if (district.getEstateType2() != null && district.getEstateType2().contains("别墅")) { + model.setPropertyType("1"); + } + } + + if (model.getCalDate() != null) { + if (new Date().before(model.getCalDate())) { + model.setCalDate(DateUtil.getFirstDayOfWeek(new Date())); + } else { + model.setCalDate(DateUtil.getFirstDayOfWeek(model.getCalDate())); + } + } else { + model.setCalDate(DateUtil.getFirstDayOfWeek(new Date())); + } + + + Evaluation evaluation = evaluationService.evaluate(district, buildEvaluation(model, request), + model.getCalDate()); + Double cityPriceCredit = null; + if (StringUtils.isNotBlank(evaluation.getFromUserId())) { + try { + ApiUserAuthority apiUserAuthority = apiUserAuthorityService + .findByUserId(Long.valueOf(evaluation.getFromUserId())); + if (apiUserAuthority.getCityCreditMap() != null + && apiUserAuthority.getCityCreditMap().containsKey(evaluation.getCity())) { + cityPriceCredit = apiUserAuthority.getCityCreditMap().get(evaluation.getCity()); + if (cityPriceCredit > 1 || cityPriceCredit < 0) { + cityPriceCredit = null; + } + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + + this.adjustPriceByRatio(district, evaluation); + } + + // 调整面积不同面积价格 + try { + DistrictStatBo districtStatBo = districtStatService.findDistrictStat(new DistrictKey(district)); + int orgAvgPrice = 0; + if (districtStatBo != null) { + if (StringUtils.isNotBlank(district.getEstateType2()) && district.getEstateType2().contains("别墅") && districtStatBo.getVillaDistrictStat() != null) { + orgAvgPrice = districtStatBo.getVillaDistrictStat().getAvgPrice(); + } else if (districtStatBo.getDistrictStat() != null) { + orgAvgPrice = districtStatBo.getDistrictStat().getAvgPrice(); + } + } + if (evaluation != null && evaluation.getAvgPrice() != null && evaluation.getAvgPrice() > 0) { + int factorPrice = evaluation.getAvgPrice(); + int avgPrice = evaluateFactorService.recompose(district.getCity(), district.getRegion(), evaluation.getArea(), factorPrice, orgAvgPrice); + Integer minPrice = (int) (evaluation.getAvgPrice() * 0.95); + Integer maxPrice = (int) (evaluation.getAvgPrice() * 1.05); + // 偏离度超过5%不进行调整 + if (minPrice <= avgPrice && avgPrice <= maxPrice) { + evaluation.setAvgPrice(avgPrice); + evaluation.setBigTotalPrice((long) (avgPrice * evaluation.getArea())); + } + } + } catch (Exception ex) { + LOGGER.error("调整面积不同面积价格异常{}", ex.getMessage()); + } + + if (evaluation.getTotalPrice() != null && evaluation.getTotalPrice() != 0 + && (cityPriceCredit == null || evaluation.getCredit() >= cityPriceCredit)) { + Map districtPriceMap = new HashMap(); + districtPriceMap.put("city", district.getCity()); + districtPriceMap.put("district", district.getRegion()); + districtPriceMap.put("name", district.getName()); + districtPriceMap.put("totalPrice", evaluation.getBigTotalPrice()); + districtPriceMap.put("avgPrice", evaluation.getAvgPrice()); + + // 根据城市等 级设置D级可信度 + ApiUserAuthority apiUserAuthority = apiUserAuthorityService + .findByUserId(Long.valueOf(evaluation.getFromUserId())); + if (apiUserAuthority != null && null != apiUserAuthority.getCreditLevelStatus() + && apiUserAuthority.getCreditLevelStatus() == 1) { + double dCredit = 0.61; + if (null != apiUserAuthority.getPriceRatingMap()) { + ServerArea serverArea = serverAreaService.findByDisplay(evaluation.getCity()); + Map rateMap = apiUserAuthority.getPriceRatingMap(); + if (null != rateMap) { + dCredit = rateMap.get(CITYLEVEL_MAP.get(serverArea.getNewCityGrade().toString())); + } + } + Map rMap = getLastEvaluationPrice(district, evaluation, dCredit); + + if (model.getScope() == EVALUATE_SHOW_DETAIL) { + if (null != rMap) { + if (rMap.containsKey("level")) { + districtPriceMap.put("level", rMap.get("level")); + } + if (rMap.containsKey("other_price")) { + districtPriceMap.put("other_price", rMap.get("other_price")); + } + } + } + + Long lastPrice = (Long) rMap.get("lastPrice"); + + if (null != lastPrice) { + districtPriceMap.put("totalPrice", lastPrice); + if (lastPrice > 0 && lastPrice != evaluation.getBigTotalPrice()) { + districtPriceMap.put("avgPrice", (int) (lastPrice / evaluation.getArea())); + } + } else { + mav.setModel(BasicModel.buildOKModel().setMsg("暂时不支持该小区的估价").markNoData()); + return mav; + } + + } else { + districtPriceMap.put("totalPrice", evaluation.getBigTotalPrice()); + } + + if (model.getScope() == EVALUATE_SHOW_DETAIL) { + districtPriceMap.put("evaluateWay", evaluation.getEvaluateWay()); + districtPriceMap.put("credit", evaluation.getCredit()); + districtPriceMap.put("id", evaluation.getId()); + } + // 将评估价放到结果集 + houseValueInformation.setAddressValue(districtPriceMap); +// mav.setModel(BasicModel.buildOKModel().setResult(districtPriceMap)); + try { + if (StringUtils.isNotBlank(evaluation.getFromUserId()) && !evaluation.getFromUserId().equals("1007497")) { + openApiLogService.saveLog(CommonUtils.convertToMap(model), districtPriceMap, evaluation, "/property/evaluate"); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + return mav; + } else { + evaluationService.remove(evaluation.getId()); + mav.setModel(BasicModel.buildOKModel().setMsg("暂时不支持该小区的估价").markNoData()); + return mav; + } + } + + private Integer getFloor(String roomNumber) { + if (StringUtils.isNotBlank(roomNumber) && DataUtil.isNumber(roomNumber)) { + if (roomNumber.length() == 3) { + return Integer.valueOf(roomNumber.substring(0, 1)); + } else if (roomNumber.length() == 4) { + return Integer.valueOf(roomNumber.substring(0, 2)); + } else { + return null; + } + } + return null; + } + + private Evaluation buildEvaluation(PropertyEvaluationModel model, HttpServletRequest request) { + Evaluation evaluation = new Evaluation(); + evaluation.setCity(model.getCity()); + evaluation.setRegion(model.getRegion()); + evaluation.setDistrictName(model.getName()); + evaluation.setDirection(DIRECTION.get(model.getDirection())); + evaluation.setFitment(EVALUATION_MODEL_FITMENT.get(FITMENT.get(StringUtils.isNotBlank(model.getDecoration()) ? + model.getDecoration() : model.getFitment()))); + evaluation.setNoise(NOISE.get(model.getNoise())); + evaluation.setEstateType(PROPERTY_TYPES.get(model.getPropertyType())); + evaluation.setSight(SIGHT.get(model.getView())); + evaluation.setAtticArea(model.getAtticSize()); + evaluation.setTerraceArea(model.getOuterSize()); + evaluation.setBasementArea(model.getBasementSize()); + evaluation.setGardenArea(model.getGardenSize()); + String worryFacility = model.getNegativeFactor(); + evaluation.setWorryFacility(NEGATIVE_FACTOR.get(worryFacility)); + evaluation.setCreationDate(new Date()); + evaluation.setModificationDate(new Date()); + evaluation.setClientNo(model.getClientNo()); + if (0 != model.getAge()) { + evaluation.setAge(model.getAge()); + } + evaluation.setArea(model.getSize()); + if (ArrayUtils.isNotEmpty(model.getBuildQuality())) { + evaluation.setBuildQuality(convertToString(model.getBuildQuality())); + } + if (StringUtils.isNotBlank(model.getBuildType())) { + evaluation.setBuildType(model.getBuildType()); + } + if (StringUtils.isNotBlank(model.getCarport())) { + evaluation.setCarport(model.getCarport()); + } + if (model.getDecorationAge() >= 1 && model.getDecorationAge() <= 5) { + evaluation.setFitmentAge(model.getDecorationAge()); + } + evaluation.setCarportPrice(model.getCarportPrice()); + evaluation.setCity(model.getCity()); + evaluation.setDistrictName(model.getName()); + if (model.getDecorationCost() != null && model.getDecorationCost() > 0) { + evaluation.setFitmentCharge(model.getDecorationCost()); + } + if (0 != model.getHall()) { + evaluation.setHall(model.getHall()); + } + if (null != model.getFloor()) { + evaluation.setFloor(model.getFloor()); + } + if (model.getMaxFloor() != null && 0 != model.getMaxFloor()) { + evaluation.setHeight(model.getMaxFloor()); + } + if (StringUtils.isNotBlank(model.getBuildingNumber())) { + evaluation.setHouseNum(model.getBuildingNumber()); + } + if (StringUtils.isNotBlank(model.getHouseProperty())) { + evaluation.setHouseProperty(model.getHouseProperty()); + } + if (StringUtils.isNotBlank(model.getInsidepos())) { + evaluation.setInsidepos(model.getInsidepos()); + } + if (StringUtils.isNotBlank(model.getLightingVentilation())) { + evaluation.setLightingVentilation(model.getLightingVentilation()); + } + + if (StringUtils.isNotBlank(model.getOtherFactor())) { + evaluation.setOtherFactor(model.getOtherFactor()); + } + evaluation.setRegion(model.getDistrict()); + if (null != model.getRoom()) { + evaluation.setRoom(model.getRoom()); + } + if (StringUtils.isNotBlank(model.getRoomNumber())) { + evaluation.setRoomNum(model.getRoomNumber()); + } + if (StringUtils.isNotBlank(model.getSideset())) { + evaluation.setSideset(model.getSideset()); + } + if (0 != model.getToilet()) { + evaluation.setToilet(model.getToilet()); + } + if (model.getFacilities() != null) { + String facilities = model.getFacilities(); + String[] fs = facilities.split(","); + for (int i = 0; i < fs.length; i++) { + fs[i] = FACILITIES.get(fs[i]); + } + evaluation.setFacilities(convertToString(fs)); + } + + if (StringUtils.isNotBlank(model.getFacade())) { + evaluation.setFacade(model.getFacade()); + } + if (StringUtils.isNotBlank(model.getTraffice())) { + evaluation.setTraffice(model.getTraffice()); + } + if (StringUtils.isNotBlank(model.getShape())) { + evaluation.setShape(model.getShape()); + } + if (StringUtils.isNotBlank(model.getObstacle())) { + evaluation.setObstacle(model.getObstacle()); + } + if (StringUtils.isNotBlank(model.getIndustry())) { + evaluation.setIndustry(model.getIndustry()); + } + if (StringUtils.isNotBlank(model.getSupportDevice())) { + evaluation.setSupportDevice(model.getSupportDevice()); + } + if (StringUtils.isNotBlank(model.getLeftPosition())) { + evaluation.setLeftPosition(model.getLeftPosition()); + } + if (StringUtils.isNotBlank(model.getShopType())) { + evaluation.setShopType(model.getShopType()); + } + if (StringUtils.isNotBlank(model.getShopUnique())) { + evaluation.setShopUnique(model.getShopUnique()); + } + if (StringUtils.isNotBlank(model.getLocation())) { + evaluation.setLocation(model.getLocation()); + } + if (model.isNewDistrict()) { + evaluation.setNewDistrict(model.isNewDistrict()); + } + String ip = AnalyticsUtil.getIpAddress(ActionContext.getContext().getRequest()); + evaluation.setIp(ip); + AuthenticationBean authenticationBean = (AuthenticationBean) request + .getAttribute(AuthenticationBean.ATTR_AUTHENTICATION_BEAN); + if (authenticationBean != null && authenticationBean.apiUser != null) { + evaluation.setFromUserId(String.valueOf(authenticationBean.apiUser.getId())); + } + evaluation.setSource("api_property_evaluation"); + return evaluation; + } + + private Map getLastEvaluationPrice(District district, Evaluation evaluation, double dCredit) + throws NumberFormatException, IllegalAccessException { + Date startDate = DateUtil.parseDate(DateUtil.addMonth(new Date(), -6), "yyyy-MM-dd"); + // 第三方价格 + Map otherPriceRets = averageStatisticsService.findFirstAverageStatictics(district.getCity(), + district.getRegion(), district.getName(), district.getCategory(), startDate); + if (null == otherPriceRets) { + otherPriceRets = new HashMap(); + } + + otherPriceRets.put("fjw_price", evaluation.getAvgPrice()); + Map levelMap = getPriceLevel(otherPriceRets, evaluation.getCredit()); + Long lastPrice = getLastPrice(levelMap, otherPriceRets, evaluation, dCredit); + + Map rMap = new HashMap(); + rMap.put("lastPrice", lastPrice); + if (null != levelMap && levelMap.containsKey("level")) { + String priceLevel = (String) levelMap.get("level"); + rMap.put("level", priceLevel); + } + rMap.put("other_price", otherPriceRets); + return rMap; + } + + private Map getPriceLevel(Map otherPriceRets, double credit) { + + Integer avgPrice = (Integer) otherPriceRets.get("fjw_price"); + + int keyCount = 0; + int commonCount = 0; + int isExistCount = 0; + + List prices = new ArrayList(); + List smallPrices = new ArrayList(); + + if (null != otherPriceRets.get("fanggugu_price")) { + Integer fangguguPrice = (Integer) otherPriceRets.get("fanggugu_price"); + int mod = avgPrice - fangguguPrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + keyCount++; + } else { + prices.add(fangguguPrice); + } + isExistCount++; + } + if (null != otherPriceRets.get("yungujia_price")) { + Integer yungujiaPrice = (Integer) otherPriceRets.get("yungujia_price"); + int mod = avgPrice - yungujiaPrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + keyCount++; + } else { + prices.add(yungujiaPrice); + } + + isExistCount++; + } + + if (null != otherPriceRets.get("zhugezhaofang_price")) { + Integer zhugezhaofangPrice = (Integer) otherPriceRets.get("zhugezhaofang_price"); + int mod = avgPrice - zhugezhaofangPrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + keyCount++; + } else { + prices.add(zhugezhaofangPrice); + } + + isExistCount++; + } + + if (null != otherPriceRets.get("lianjia_price")) { + Integer lianjiaPrice = (Integer) otherPriceRets.get("lianjia_price"); + int mod = avgPrice - lianjiaPrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + keyCount++; + } else { + prices.add(lianjiaPrice); + } + isExistCount++; + } + if (null != otherPriceRets.get("anjuke_price")) { + Integer anjukePrice = (Integer) otherPriceRets.get("anjuke_price"); + int mod = avgPrice - anjukePrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + commonCount++; + smallPrices.add(anjukePrice); + } else { + prices.add(anjukePrice); + } + + isExistCount++; + } + if (null != otherPriceRets.get("ganji_price")) { + Integer ganjiPrice = (Integer) otherPriceRets.get("ganji_price"); + int mod = avgPrice - ganjiPrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + commonCount++; + smallPrices.add(ganjiPrice); + } else { + prices.add(ganjiPrice); + } + + isExistCount++; + } + if (null != otherPriceRets.get("soufan_price")) { + Integer soufan_price = (Integer) otherPriceRets.get("soufan_price"); + int mod = avgPrice - soufan_price; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + commonCount++; + smallPrices.add(soufan_price); + } else { + prices.add(soufan_price); + } + + isExistCount++; + } + if (null != otherPriceRets.get("tobushi_price")) { + Integer tobushi = (Integer) otherPriceRets.get("tobushi_price"); + int mod = avgPrice - tobushi; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + commonCount++; + smallPrices.add(tobushi); + } else { + prices.add(tobushi); + } + + isExistCount++; + } + + if (null != otherPriceRets.get("zhongyuan_price")) { + Integer zhongyuanPrice = (Integer) otherPriceRets.get("zhongyuan_price"); + int mod = avgPrice - zhongyuanPrice; + double temp = DataUtil.getDoubleRound(2, mod * 100 / avgPrice); + temp = Math.abs(temp); + if (temp <= 15) { + commonCount++; + smallPrices.add(zhongyuanPrice); + } else { + prices.add(zhongyuanPrice); + } + + isExistCount++; + } + + Map retMap = new HashMap(); + String level = null; + if (keyCount >= 2) { + level = "A"; + } else if (keyCount >= 1 && commonCount >= 1) { + level = "A"; + } else if (keyCount >= 1 || commonCount >= 2) { + level = "B"; + } else if (commonCount >= 1) { + level = "C"; + } else if (isExistCount == 0) { + level = "D"; + } else if (isExistCount >= 1) { + if (isExistCount == 1) { + level = "D"; + } else { + level = "E"; + } + } + + if (credit == 0) { + level = "E"; + } + + if (StringUtils.isNotBlank(level)) { + retMap.put("level", level); + retMap.put("prices", prices); + retMap.put("small_prices", smallPrices); + } + return retMap; + } + + private Long getLastPrice(Map retMap, Map otherPriceRets, Evaluation evaluation, double dCredit) { + Long lastPrice = null; + if (null != retMap) { + String priceLevel = (String) retMap.get("level"); + + if (priceLevel.equals("D")) { + + lastPrice = inputResultByWebsite(otherPriceRets, evaluation, dCredit); + + } else if (priceLevel.equals("E")) { + if (evaluation.getCredit() >= 0.65) { + lastPrice = evaluation.getBigTotalPrice(); + } else { + List prices = (List) retMap.get("prices"); + int avgPrice = 0; + if (prices != null) { + avgPrice = findNewPrice(prices, evaluation.getAvgPrice()); + } + // 在 dCredit与0.65之间 + if (evaluation.getCredit() >= dCredit && dCredit < 0.65) { + if (avgPrice > 0) { + Double newTotalPrice = avgPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else { + if (null != otherPriceRets.get("lianjia_price")) { + Integer lianjiaPrice = (Integer) otherPriceRets.get("lianjia_price"); + Double newTotalPrice = lianjiaPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("zhugezhaofang_price")) { + Integer zhugezhaofangPrice = (Integer) otherPriceRets.get("zhugezhaofang_price"); + Double newTotalPrice = zhugezhaofangPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("yungujia_price")) { + Integer yungujiaPrice = (Integer) otherPriceRets.get("yungujia_price"); + Double newTotalPrice = yungujiaPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("fanggugu_price")) { + Integer fangguguPrice = (Integer) otherPriceRets.get("fanggugu_price"); + Double newTotalPrice = fangguguPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else { + lastPrice = evaluation.getBigTotalPrice(); + } + } + } else if (evaluation.getCredit() < dCredit) {// 在dCredit以下 + if (avgPrice > 0) { + Double newTotalPrice = avgPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else { + if (null != otherPriceRets.get("lianjia_price")) { + Integer lianjiaPrice = (Integer) otherPriceRets.get("lianjia_price"); + Double newTotalPrice = lianjiaPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("zhugezhaofang_price")) { + Integer zhugezhaofangPrice = (Integer) otherPriceRets.get("zhugezhaofang_price"); + Double newTotalPrice = zhugezhaofangPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("yungujia_price")) { + Integer yungujiaPrice = (Integer) otherPriceRets.get("yungujia_price"); + Double newTotalPrice = yungujiaPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("fanggugu_price")) { + Integer fangguguPrice = (Integer) otherPriceRets.get("fanggugu_price"); + Double newTotalPrice = fangguguPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } + } + } + } + + } else if (priceLevel.equals("C")) { + List smallPrices = (List) retMap.get("small_prices"); + if (smallPrices != null) { + smallPrices.add(evaluation.getAvgPrice()); + int avgPrice = sum(smallPrices) / smallPrices.size(); + Double newTotalPrice = avgPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } + } else { + lastPrice = evaluation.getBigTotalPrice(); + } + } + return lastPrice; + } + + private Integer sum(List smallPrices) { + int sum = 0; + for (int price : smallPrices) { + sum += price; + } + return sum; + } + + private Long inputResultByWebsite(Map otherPriceRets, Evaluation evaluation, double dCredit) { + Long lastPrice = null; + if (evaluation.getCredit() >= dCredit) { + lastPrice = evaluation.getBigTotalPrice(); + } else { + if (evaluation.getCredit() < dCredit) { + if (null != otherPriceRets.get("lianjia_price")) { + Integer lianjiaPrice = (Integer) otherPriceRets.get("lianjia_price"); + Double newTotalPrice = lianjiaPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("zhugezhaofang_price")) { + Integer zhugezhaofangPrice = (Integer) otherPriceRets.get("zhugezhaofang_price"); + Double newTotalPrice = zhugezhaofangPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("yungujia_price")) { + Integer yungujiaPrice = (Integer) otherPriceRets.get("yungujia_price"); + Double newTotalPrice = yungujiaPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else if (null != otherPriceRets.get("fanggugu_price")) { + Integer fangguguPrice = (Integer) otherPriceRets.get("fanggugu_price"); + Double newTotalPrice = fangguguPrice * evaluation.getArea(); + lastPrice = newTotalPrice.longValue(); + } else { + lastPrice = evaluation.getBigTotalPrice(); + } + } else { + lastPrice = evaluation.getBigTotalPrice(); + } + } + return lastPrice; + } + + private Integer findNewPrice(List prices, int avgPrice) { + int minValue1 = Integer.MAX_VALUE; + List> values = new ArrayList>(); + int fjw_price = avgPrice; + + // 找出最小差 + for (int i = 0; i < prices.size() - 1; i++) { + int a = prices.get(i); + for (int j = i + 1; j < prices.size(); j++) { + int b = prices.get(j); + int mod = Math.abs(a - b); + if (mod < minValue1) { + minValue1 = mod; + } + } + } + + // 根据最小差找出结果 + for (int i = 0; i < prices.size() - 1; i++) { + int a = prices.get(i); + for (int j = i + 1; j < prices.size(); j++) { + int b = prices.get(j); + int mod = Math.abs(a - b); + if (mod == minValue1) { + values.add(Arrays.asList(a, b)); + } + } + } + + int minValue2 = Integer.MAX_VALUE; + int lastValue = 0; + if (values.size() >= 1) { + for (List value : values) { + int newPrice = (value.get(0) + value.get(1)) / 2; + int mod = Math.abs(fjw_price - newPrice); + if (mod < minValue2) { + minValue2 = mod; + lastValue = newPrice; + } + } + } + + if (lastValue > 0) { + double temp = DataUtil.getDoubleRound(2, minValue1 * 100 / lastValue); + temp = Math.abs(temp); + if (temp > 15) { + lastValue = 0; + } + } + return lastValue; + } + + + public void setEvaluationService(EvaluationService evaluationService) { + this.evaluationService = evaluationService; + } + + public void setDistrictService(DistrictService districtService) { + this.districtService = districtService; + } + + public void setAddressService(AddressService addressService) { + } + + public void setDistrictStatService(DistrictStatService districtStatService) { + this.districtStatService = districtStatService; + } + + protected AddressMatchLogService addressMatchLogService; + + public void setAddressMatchLogService(AddressMatchLogService addressMatchLogService) { + this.addressMatchLogService = addressMatchLogService; + } + + + public BatchEvaluateService getBatchEvaluateService() { + return batchEvaluateService; + } + + public void setBatchEvaluateService(BatchEvaluateService batchEvaluateService) { + this.batchEvaluateService = batchEvaluateService; + } + + public void setAddressMatchProxyService(AddressMatchProxyService addressMatchProxyService) { + this.addressMatchProxyService = addressMatchProxyService; + } + + public void setLoudongService(LoudongService loudongService) { + this.loudongService = loudongService; + } + + public void setApiUserAuthorityService(ApiUserAuthorityService apiUserAuthorityService) { + this.apiUserAuthorityService = apiUserAuthorityService; + } + + public void setAverageStatisticsService(AverageStatisticsService averageStatisticsService) { + this.averageStatisticsService = averageStatisticsService; + } + + public void setServerAreaService(ServerAreaService serverAreaService) { + this.serverAreaService = serverAreaService; + } + + public void setApiUserCfgService(ApiUserCfgService apiUserCfgService) { + this.apiUserCfgService = apiUserCfgService; + } + + public void setOpenApiLogService(OpenApiLogService openApiLogService) { + this.openApiLogService = openApiLogService; + } + + public void setFangjiaOfficialAreaService(FangjiaOfficialAreaService fangjiaOfficialAreaService) { + this.fangjiaOfficialAreaService = fangjiaOfficialAreaService; + } + + + public void setEvaluateRatioService(EvaluateRatioService evaluateRatioService) { + this.evaluateRatioService = evaluateRatioService; + } + + + public void setEvaluateFactorService(EvaluateFactorService evaluateFactorService) { + this.evaluateFactorService = evaluateFactorService; + } + + public void setCzbankSampleService(CzbankSampleService czbankSampleService) { + this.czbankSampleService = czbankSampleService; + } + + public void setDistrictFacilitysService(DistrictFacilitysService districtFacilitysService) { + this.districtFacilitysService = districtFacilitysService; + } + +} + +*/ diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/UserController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/UserController.java index e97bc10ae..73e27d8a6 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/UserController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/UserController.java @@ -542,7 +542,7 @@ public class UserController { String code = usersInfoService.randomCode(); System.out.println(code); try { - smsService.send(model.getMobile(), "【房价网】你的验证码是" + code + ",请立即验证。"); + smsService.send(model.getMobile(), "【百盛评估】你的验证码是" + code + ",请立即验证。"); resultModel.setResult(Message.RESULT_SUCCESS); CookieUtils.setCookie(mobile + "_" + type, code, "/", 60 * 60 * 24 *7, resp); CacheUtils.putValue(CachePolicyEnum.TINY, FjtUsers.class, mobile, new Date().getTime()); diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/WeiXinEvaluationController.java b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/WeiXinEvaluationController.java index 800a2360d..716c2156f 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/WeiXinEvaluationController.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/controllers/weixin/WeiXinEvaluationController.java @@ -1282,15 +1282,20 @@ public class WeiXinEvaluationController { Point point = new Point(Double.valueOf(ll[0]), Double.valueOf(ll[1])); points.add(point); } - Point point = new Point(district.getLng2()/10000000000.0, district.getLat2()/10000000000.0); - //boolean flag = InsidePolygon.aboutZone(point, points); - //boolean flag = InsidePolygon.isPtInPoly(point.getLon(), point.getLat(), points); - boolean flag = InsidePolygon2.checkIsInPolygon(point, points); - if(flag){ - pbObj = pb; - System.out.println(district.getRegion()+" "+district.getName()+" "+pb.getName()); - break; + Point point = null; + if(district.getLng2()!=null){ + point = new Point(district.getLng2()/10000000000.0, district.getLat2()/10000000000.0); + + //boolean flag = InsidePolygon.aboutZone(point, points); + //boolean flag = InsidePolygon.isPtInPoly(point.getLon(), point.getLat(), points); + boolean flag = InsidePolygon2.checkIsInPolygon(point, points); + if(flag){ + pbObj = pb; + System.out.println(district.getRegion()+" "+district.getName()+" "+pb.getName()); + break; + } } + } Integer yearAge = getBuildYear(district.getFinishBuildingDate()); if(pbObj!=null){ diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/dto/CityNewPriceDto.java b/projects/fangjia-open/src/main/java/com/fangjia/open/dto/CityNewPriceDto.java index 438808ffc..4b09649d3 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/dto/CityNewPriceDto.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/dto/CityNewPriceDto.java @@ -7,7 +7,8 @@ import com.fangjia.dal.mongo.model.CityNewPrice; import com.fangjia.dal.mongo.model.RegionSellStat; @SuppressWarnings("serial") -public class CityNewPriceDto implements Serializable{ +public class +CityNewPriceDto implements Serializable{ /** * diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/dto/DistrictInfoDto.java b/projects/fangjia-open/src/main/java/com/fangjia/open/dto/DistrictInfoDto.java index 6fbca5e08..8d24c760f 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/dto/DistrictInfoDto.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/dto/DistrictInfoDto.java @@ -26,8 +26,14 @@ public class DistrictInfoDto { private List alias; private List addressAlias; private String videoUrl; + //高德坐标 + //维度 private Double lat; + //经度 private Double lng; + // 百度坐标 + private Double lat2; + private Double lng2; private String developer; private String buildType; private String estateCompany; @@ -102,7 +108,22 @@ public class DistrictInfoDto { private String township; private String landProperty; - + public Double getLat2() { + return lat2; + } + + public void setLat2(Double lat2) { + this.lat2 = lat2; + } + + public Double getLng2() { + return lng2; + } + + public void setLng2(Double lng2) { + this.lng2 = lng2; + } + public String getDistrict() { return district; } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/dto/HouseValueInformationDto.java b/projects/fangjia-open/src/main/java/com/fangjia/open/dto/HouseValueInformationDto.java new file mode 100644 index 000000000..7c699ae17 --- /dev/null +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/dto/HouseValueInformationDto.java @@ -0,0 +1,57 @@ +package com.fangjia.open.dto; + +import com.fangjia.dal.mongo.model.DistrictFacilitys; +import com.fangjia.open.dto.addressGovernance.MatchedBuildingDto; +import com.fangjia.open.model.RestfulModelAndView; + +import java.util.Map; + +/** + * @author 13607 + * @since 2023/12/12 10:47 + */ +public class HouseValueInformationDto { + // 原小区均价返回值 + private MatchedBuildingDto communityAvgPrice; + // 原房屋价值评估返回值 + private Map addressValue; + + //原房源样本返回值 + private UniversalDto houseCase; + + //原周边POI返回值 + private DistrictFacilitys surroundingPoi; + + public MatchedBuildingDto getCommunityAvgPrice() { + return communityAvgPrice; + } + + public void setCommunityAvgPrice(MatchedBuildingDto communityAvgPrice) { + this.communityAvgPrice = communityAvgPrice; + } + + public Map getAddressValue() { + return addressValue; + } + + public void setAddressValue(Map addressValue) { + this.addressValue = addressValue; + } + + public UniversalDto getHouseCase() { + return houseCase; + } + + public void setHouseCase(UniversalDto houseCase) { + this.houseCase = houseCase; + } + + public DistrictFacilitys getSurroundingPoi() { + return surroundingPoi; + } + + public void setSurroundingPoi(DistrictFacilitys surroundingPoi) { + this.surroundingPoi = surroundingPoi; + } +} + diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/dto/PropertyDto.java b/projects/fangjia-open/src/main/java/com/fangjia/open/dto/PropertyDto.java index 8e9097e2a..aac0f83b2 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/dto/PropertyDto.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/dto/PropertyDto.java @@ -15,6 +15,10 @@ public class PropertyDto { private String propertyType; private String block; private String distance; + /** + * 新增小区别名 + */ + private String alias; public String getId() { return id; } @@ -88,4 +92,12 @@ public class PropertyDto { public void setDistance(String distance) { this.distance = distance; } + + public String getAlias() { + return alias; + } + + public void setAlias(String alias) { + this.alias = alias; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/dto/addressGovernance/MatchedBuildingDto.java b/projects/fangjia-open/src/main/java/com/fangjia/open/dto/addressGovernance/MatchedBuildingDto.java index e666a9100..ce0ad64cc 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/dto/addressGovernance/MatchedBuildingDto.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/dto/addressGovernance/MatchedBuildingDto.java @@ -46,6 +46,11 @@ public class MatchedBuildingDto { */ private String propertyType; + /** + * 均价 + */ + private Integer avgPrice; + public String getId() { return id; } @@ -125,4 +130,12 @@ public class MatchedBuildingDto { public void setPropertyType(String propertyType) { this.propertyType = propertyType; } + + public Integer getAvgPrice() { + return avgPrice; + } + + public void setAvgPrice(Integer avgPrice) { + this.avgPrice = avgPrice; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/AddesssMatchModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/AddesssMatchModel.java index ea10ab2f4..1a8907341 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/model/AddesssMatchModel.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/AddesssMatchModel.java @@ -9,6 +9,7 @@ import org.hibernate.validator.constraints.NotBlank; public class AddesssMatchModel extends FangjiaApiModel { private String city; + private String refCity; @NotBlank private String address; private String suggestDistrict; @@ -24,6 +25,14 @@ public class AddesssMatchModel extends FangjiaApiModel { private String showCode; + public String getRefCity() { + return refCity; + } + + public void setRefCity(String refCity) { + this.refCity = refCity; + } + public String getAddress_1() { return address_1; } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/AddressModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/AddressModel.java index 529d42d07..94af02362 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/model/AddressModel.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/AddressModel.java @@ -33,13 +33,27 @@ public class AddressModel extends FangjiaApiModel { private Integer radius; // 查询数量 private Integer number; + private Integer offset; // 查询页码 private Integer pageNo; + private Integer page; // 是否用于检查 private String dataLevel; - private String keyword; + private String keywords; + //是否使用地图poi数据 + private boolean useMap; + //涉农到区之后,是否显式后面的字段值 + private String showFullValue; + //是否显示涉农测试用字段值 + private String showTestValue; + + private String lat; + private String lng; + + private String location; + private String types; public boolean isContainsLocation() { return containsLocation; } @@ -233,12 +247,12 @@ public class AddressModel extends FangjiaApiModel { this.dataLevel = dataLevel; } - public String getKeyword() { - return keyword; + public String getKeywords() { + return keywords; } - public void setKeyword(String keyword) { - this.keyword = keyword; + public void setKeywords(String keywords) { + this.keywords = keywords; } public String getRegion() { @@ -248,4 +262,76 @@ public class AddressModel extends FangjiaApiModel { public void setRegion(String region) { this.region = region; } + + public boolean isUseMap() { + return useMap; + } + + public void setUseMap(boolean useMap) { + this.useMap = useMap; + } + + public String getShowFullValue() { + return showFullValue; + } + + public void setShowFullValue(String showFullValue) { + this.showFullValue = showFullValue; + } + + public String getShowTestValue() { + return showTestValue; + } + + public void setShowTestValue(String showTestValue) { + this.showTestValue = showTestValue; + } + + public String getLat() { + return lat; + } + + public void setLat(String lat) { + this.lat = lat; + } + + public String getLng() { + return lng; + } + + public void setLng(String lng) { + this.lng = lng; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getTypes() { + return types; + } + + public void setTypes(String types) { + this.types = types; + } + + public Integer getOffset() { + return offset; + } + + public void setOffset(Integer offset) { + this.offset = offset; + } + + public Integer getPage() { + return page; + } + + public void setPage(Integer page) { + this.page = page; + } } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/HouseInfomationModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/HouseInfomationModel.java new file mode 100644 index 000000000..52cbca930 --- /dev/null +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/HouseInfomationModel.java @@ -0,0 +1,941 @@ +package com.fangjia.open.model; + +import java.util.Date; + +/** + * @author 13607 + * @since 2023/12/12 14:27 + */ +public class HouseInfomationModel extends FangjiaApiModel { + private String city; + private String address; + private String category; + private boolean useMap; + + /** + * 判断是不是有房估价 + */ + private boolean isYouFang; + + /** + * 判断是不是友达 + */ + private boolean isYouDa; + + /** + * 区域 + */ + private String region; + + /** + * 区域(新版本估价) + **/ + private String district; + + /** + * 小区名 + */ + private String districtName; + /** + * 小区名(新版本) + */ + private String name; + /** + * 楼号 + */ + private String unitNumber; + /** + * 新楼号 + */ + private String houseNumber; + + private String id; + /** + * 室号 + */ + private String roomNumber; + + /** + * 面积 + */ + private double size; + + /** + * 所在楼层 + */ + private Integer floor; + + /** + * 总楼层 + */ + private Integer height; + + /** + * 室数 + */ + private Integer room; + + /** + * 厅数 + */ + private int hall; + + /** + * 卫数 + */ + private int toilet; + + /** + * 估价时间 + */ + private Date calDate; + + private String propertyType; + + + /** + * 建筑类型 + */ + private String buildType; + + /** + * 朝向 + */ + private String direction; + + /** + * 装修情况 + */ + private String fitment; + + /** + * 装修价格 + */ + private int fitmentCharge; + + /** + * 景观情况 + */ + private String view; + + /** + * 噪音情况 + */ + private String noise; + + /** + * 花园面积 + */ + private Double gardenArea; + + /** + * 地下室面积 + */ + private Double basementArea; + + /** + * 厌恶因素 + */ + private String[] worryFactor; + + /** + * 房龄 + */ + private int age; + + /** + * 自有车位 + */ + private String carport; + + /** + * 小区配套 + */ + private String facilities; + + /** + * 小区位置 + */ + private String insidepos; + + /** + * 装修年限 + */ + private int fitmentAge; + + /** + * 采光通风 + */ + private String lightingVentilation; + + /** + * 边套装置 + */ + private String sideset; + + /** + * 建筑质量 + */ + private String[] buildQuality; + + /** + * 厌恶设施 + */ + private String worryFacility; + + /** + * 产权属性 + */ + private String houseProperty; + + /** + * 其他因素 + */ + private String otherFactor; + + /** + * 门面开间 + */ + private String facade; + + /** + * 公共交通 + */ + private String traffice; + + /** + * 形状 + */ + private String shape; + + /** + * 障碍物 + */ + private String obstacle; + + /** + * 经营性质 + */ + private String industry; + + /** + * 配套设备 + */ + private String supportDevice; + + /** + * 距离扶梯位置 + */ + private String leftPosition; + + /** + * 商铺类型 + */ + private String shopType; + + /** + * 商铺唯一性 + */ + private String shopUnique; + + /** + * 商铺位置 + */ + private String location; + + private String kind; + + private boolean isNewDistrict; + + private Integer carportPrice; + + private String keyword; + + private String buildingNumber; + + private Integer maxFloor; + + private String decoration; + + private Integer decorationCost; + + private Double gardenSize; + private Double basementSize; + private Double outerSize; + private Double atticSize; + private String negativeFactor; + private String insidePosition; + private int decorationAge; + + private boolean convert; + + private String estateType; + private String periodType; + private Integer periodCount; + + + private Integer houseType; + private String clientNo; + private int scope; + + private Integer maxPrice; + private Integer minPrice; + + private Integer radius; + private Integer limit; + private String app; + + private String user; + + private Integer avgPrice; + + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public boolean isUseMap() { + return useMap; + } + + public void setUseMap(boolean useMap) { + this.useMap = useMap; + } + + public boolean isYouFang() { + return isYouFang; + } + + public void setYouFang(boolean youFang) { + isYouFang = youFang; + } + + public boolean isYouDa() { + return isYouDa; + } + + public void setYouDa(boolean youDa) { + isYouDa = youDa; + } + + public String getRegion() { + return region; + } + + public void setRegion(String region) { + this.region = region; + } + + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } + + public String getDistrictName() { + return districtName; + } + + public void setDistrictName(String districtName) { + this.districtName = districtName; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUnitNumber() { + return unitNumber; + } + + public void setUnitNumber(String unitNumber) { + this.unitNumber = unitNumber; + } + + public String getHouseNumber() { + return houseNumber; + } + + public void setHouseNumber(String houseNumber) { + this.houseNumber = houseNumber; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getRoomNumber() { + return roomNumber; + } + + public void setRoomNumber(String roomNumber) { + this.roomNumber = roomNumber; + } + + public double getSize() { + return size; + } + + public void setSize(double size) { + this.size = size; + } + + public Integer getFloor() { + return floor; + } + + public void setFloor(Integer floor) { + this.floor = floor; + } + + public Integer getHeight() { + return height; + } + + public void setHeight(Integer height) { + this.height = height; + } + + public Integer getRoom() { + return room; + } + + public void setRoom(Integer room) { + this.room = room; + } + + public int getHall() { + return hall; + } + + public void setHall(int hall) { + this.hall = hall; + } + + public int getToilet() { + return toilet; + } + + public void setToilet(int toilet) { + this.toilet = toilet; + } + + public Date getCalDate() { + return calDate; + } + + public void setCalDate(Date calDate) { + this.calDate = calDate; + } + + public String getPropertyType() { + return propertyType; + } + + public void setPropertyType(String propertyType) { + this.propertyType = propertyType; + } + + public String getBuildType() { + return buildType; + } + + public void setBuildType(String buildType) { + this.buildType = buildType; + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } + + public String getFitment() { + return fitment; + } + + public void setFitment(String fitment) { + this.fitment = fitment; + } + + public int getFitmentCharge() { + return fitmentCharge; + } + + public void setFitmentCharge(int fitmentCharge) { + this.fitmentCharge = fitmentCharge; + } + + public String getView() { + return view; + } + + public void setView(String view) { + this.view = view; + } + + public String getNoise() { + return noise; + } + + public void setNoise(String noise) { + this.noise = noise; + } + + public Double getGardenArea() { + return gardenArea; + } + + public void setGardenArea(Double gardenArea) { + this.gardenArea = gardenArea; + } + + public Double getBasementArea() { + return basementArea; + } + + public void setBasementArea(Double basementArea) { + this.basementArea = basementArea; + } + + public String[] getWorryFactor() { + return worryFactor; + } + + public void setWorryFactor(String[] worryFactor) { + this.worryFactor = worryFactor; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getCarport() { + return carport; + } + + public void setCarport(String carport) { + this.carport = carport; + } + + public String getFacilities() { + return facilities; + } + + public void setFacilities(String facilities) { + this.facilities = facilities; + } + + public String getInsidepos() { + return insidepos; + } + + public void setInsidepos(String insidepos) { + this.insidepos = insidepos; + } + + public int getFitmentAge() { + return fitmentAge; + } + + public void setFitmentAge(int fitmentAge) { + this.fitmentAge = fitmentAge; + } + + public String getLightingVentilation() { + return lightingVentilation; + } + + public void setLightingVentilation(String lightingVentilation) { + this.lightingVentilation = lightingVentilation; + } + + public String getSideset() { + return sideset; + } + + public void setSideset(String sideset) { + this.sideset = sideset; + } + + public String[] getBuildQuality() { + return buildQuality; + } + + public void setBuildQuality(String[] buildQuality) { + this.buildQuality = buildQuality; + } + + public String getWorryFacility() { + return worryFacility; + } + + public void setWorryFacility(String worryFacility) { + this.worryFacility = worryFacility; + } + + public String getHouseProperty() { + return houseProperty; + } + + public void setHouseProperty(String houseProperty) { + this.houseProperty = houseProperty; + } + + public String getOtherFactor() { + return otherFactor; + } + + public void setOtherFactor(String otherFactor) { + this.otherFactor = otherFactor; + } + + public String getFacade() { + return facade; + } + + public void setFacade(String facade) { + this.facade = facade; + } + + public String getTraffice() { + return traffice; + } + + public void setTraffice(String traffice) { + this.traffice = traffice; + } + + public String getShape() { + return shape; + } + + public void setShape(String shape) { + this.shape = shape; + } + + public String getObstacle() { + return obstacle; + } + + public void setObstacle(String obstacle) { + this.obstacle = obstacle; + } + + public String getIndustry() { + return industry; + } + + public void setIndustry(String industry) { + this.industry = industry; + } + + public String getSupportDevice() { + return supportDevice; + } + + public void setSupportDevice(String supportDevice) { + this.supportDevice = supportDevice; + } + + public String getLeftPosition() { + return leftPosition; + } + + public void setLeftPosition(String leftPosition) { + this.leftPosition = leftPosition; + } + + public String getShopType() { + return shopType; + } + + public void setShopType(String shopType) { + this.shopType = shopType; + } + + public String getShopUnique() { + return shopUnique; + } + + public void setShopUnique(String shopUnique) { + this.shopUnique = shopUnique; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getKind() { + return kind; + } + + public void setKind(String kind) { + this.kind = kind; + } + + public boolean isNewDistrict() { + return isNewDistrict; + } + + public void setNewDistrict(boolean newDistrict) { + isNewDistrict = newDistrict; + } + + public Integer getCarportPrice() { + return carportPrice; + } + + public void setCarportPrice(Integer carportPrice) { + this.carportPrice = carportPrice; + } + + public String getKeyword() { + return keyword; + } + + public void setKeyword(String keyword) { + this.keyword = keyword; + } + + public String getBuildingNumber() { + return buildingNumber; + } + + public void setBuildingNumber(String buildingNumber) { + this.buildingNumber = buildingNumber; + } + + public Integer getMaxFloor() { + return maxFloor; + } + + public void setMaxFloor(Integer maxFloor) { + this.maxFloor = maxFloor; + } + + public String getDecoration() { + return decoration; + } + + public void setDecoration(String decoration) { + this.decoration = decoration; + } + + public Integer getDecorationCost() { + return decorationCost; + } + + public void setDecorationCost(Integer decorationCost) { + this.decorationCost = decorationCost; + } + + public Double getGardenSize() { + return gardenSize; + } + + public void setGardenSize(Double gardenSize) { + this.gardenSize = gardenSize; + } + + public Double getBasementSize() { + return basementSize; + } + + public void setBasementSize(Double basementSize) { + this.basementSize = basementSize; + } + + public Double getOuterSize() { + return outerSize; + } + + public void setOuterSize(Double outerSize) { + this.outerSize = outerSize; + } + + public Double getAtticSize() { + return atticSize; + } + + public void setAtticSize(Double atticSize) { + this.atticSize = atticSize; + } + + public String getNegativeFactor() { + return negativeFactor; + } + + public void setNegativeFactor(String negativeFactor) { + this.negativeFactor = negativeFactor; + } + + public String getInsidePosition() { + return insidePosition; + } + + public void setInsidePosition(String insidePosition) { + this.insidePosition = insidePosition; + } + + public int getDecorationAge() { + return decorationAge; + } + + public void setDecorationAge(int decorationAge) { + this.decorationAge = decorationAge; + } + + public boolean isConvert() { + return convert; + } + + public void setConvert(boolean convert) { + this.convert = convert; + } + + public String getEstateType() { + return estateType; + } + + public void setEstateType(String estateType) { + this.estateType = estateType; + } + + public String getPeriodType() { + return periodType; + } + + public void setPeriodType(String periodType) { + this.periodType = periodType; + } + + public Integer getPeriodCount() { + return periodCount; + } + + public void setPeriodCount(Integer periodCount) { + this.periodCount = periodCount; + } + + public Integer getHouseType() { + return houseType; + } + + public void setHouseType(Integer houseType) { + this.houseType = houseType; + } + + public String getClientNo() { + return clientNo; + } + + public void setClientNo(String clientNo) { + this.clientNo = clientNo; + } + + public int getScope() { + return scope; + } + + public void setScope(int scope) { + this.scope = scope; + } + + public Integer getMaxPrice() { + return maxPrice; + } + + public void setMaxPrice(Integer maxPrice) { + this.maxPrice = maxPrice; + } + + public Integer getMinPrice() { + return minPrice; + } + + public void setMinPrice(Integer minPrice) { + this.minPrice = minPrice; + } + + public Integer getRadius() { + return radius; + } + + public void setRadius(Integer radius) { + this.radius = radius; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + public String getApp() { + return app; + } + + public void setApp(String app) { + this.app = app; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public Integer getAvgPrice() { + return avgPrice; + } + + public void setAvgPrice(Integer avgPrice) { + this.avgPrice = avgPrice; + } +} + diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/model/PropertyEvaluationModel.java b/projects/fangjia-open/src/main/java/com/fangjia/open/model/PropertyEvaluationModel.java index 859658742..2abc1acf1 100644 --- a/projects/fangjia-open/src/main/java/com/fangjia/open/model/PropertyEvaluationModel.java +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/model/PropertyEvaluationModel.java @@ -70,12 +70,12 @@ public class PropertyEvaluationModel extends FangjiaApiModel { /** * 总楼层 */ - private int height; + private Integer height; /** * 室数 */ - private int room; + private Integer room; /** * 厅数 @@ -345,19 +345,19 @@ public class PropertyEvaluationModel extends FangjiaApiModel { this.floor = floor; } - public int getHeight() { + public Integer getHeight() { return height; } - public void setHeight(int height) { + public void setHeight(Integer height) { this.height = height; } - public int getRoom() { + public Integer getRoom() { return room; } - public void setRoom(int room) { + public void setRoom(Integer room) { this.room = room; } diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/test.java b/projects/fangjia-open/src/main/java/com/fangjia/open/test.java new file mode 100644 index 000000000..3adf910da --- /dev/null +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/test.java @@ -0,0 +1,10 @@ +package com.fangjia.open; + +public class test { + public static void main(String[] args) { + String a = "123545"; + String b ="i980"; + System.out.println(a.matches("\\d+")); + System.out.println(b.matches("\\d+")); + } +} diff --git a/projects/fangjia-open/src/main/java/com/fangjia/open/ws/query/SampleQuery.java b/projects/fangjia-open/src/main/java/com/fangjia/open/ws/query/SampleQuery.java new file mode 100644 index 000000000..2be04d480 --- /dev/null +++ b/projects/fangjia-open/src/main/java/com/fangjia/open/ws/query/SampleQuery.java @@ -0,0 +1,181 @@ +package com.fangjia.open.ws.query; + +import org.hibernate.validator.constraints.NotBlank; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import java.util.Date; + +public class SampleQuery { + + + /**城市*/ +// @NotBlank + private String city; + + /**区域*/ +// @NotBlank + private String district; + +// @NotBlank + /**小区名*/ + private String buildingName; + /**楼栋名称*/ + private String buildingNoName; + /**物业类型编码*/ + private String propertyTypeCode; + /**是否有电梯 0:无 1:有*/ + private Integer isElevator; + /**总楼层*/ + private Integer aboveFloorAmount; + /**所在楼层*/ + private Integer floorNumber; + /** + * 装修情况编码 + * 1:毛坯 + * 2:简装(默认) + * 3:精装 + * 4:豪装 + * */ + private Integer decrCondCode; + /**面积**/ + private Double strctureArea; + /** + * 朝向情况编码 + * 1:西南 + * 2:东南 + * 3:南(默认) + * 4:西北 + * 5:东北 + * 6:东 + * 7:西 + * 8:北 + * 9:东西 + * 10:南北 + * */ + private Integer towardDirectCode; + + private Date updateDate; + + @NotBlank + private String address; + + @Min(1) + @Max(10) + private Integer max; + + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getDistrict() { + return district; + } + + public void setDistrict(String district) { + this.district = district; + } + + public String getBuildingName() { + return buildingName; + } + + public void setBuildingName(String buildingName) { + this.buildingName = buildingName; + } + + public String getBuildingNoName() { + return buildingNoName; + } + + public void setBuildingNoName(String buildingNoName) { + this.buildingNoName = buildingNoName; + } + + public String getPropertyTypeCode() { + return propertyTypeCode; + } + + public void setPropertyTypeCode(String propertyTypeCode) { + this.propertyTypeCode = propertyTypeCode; + } + + public Integer getIsElevator() { + return isElevator; + } + + public void setIsElevator(Integer isElevator) { + this.isElevator = isElevator; + } + + public Integer getAboveFloorAmount() { + return aboveFloorAmount; + } + + public void setAboveFloorAmount(Integer aboveFloorAmount) { + this.aboveFloorAmount = aboveFloorAmount; + } + + public Integer getFloorNumber() { + return floorNumber; + } + + public void setFloorNumber(Integer floorNumber) { + this.floorNumber = floorNumber; + } + + public Double getStrctureArea() { + return strctureArea; + } + + public void setStrctureArea(Double strctureArea) { + this.strctureArea = strctureArea; + } + + public Integer getDecrCondCode() { + return decrCondCode; + } + + public void setDecrCondCode(Integer decrCondCode) { + this.decrCondCode = decrCondCode; + } + + public Integer getTowardDirectCode() { + return towardDirectCode; + } + + public void setTowardDirectCode(Integer towardDirectCode) { + this.towardDirectCode = towardDirectCode; + } + + public Date getUpdateDate() { + return updateDate; + } + + public void setUpdateDate(Date updateDate) { + this.updateDate = updateDate; + } + + + public Integer getMax() { + return max; + } + + public void setMax(Integer max) { + this.max = max; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} diff --git a/projects/fangjia-open/src/main/java/com/fangjia/test.java b/projects/fangjia-open/src/main/java/com/fangjia/test.java new file mode 100644 index 000000000..055094273 --- /dev/null +++ b/projects/fangjia-open/src/main/java/com/fangjia/test.java @@ -0,0 +1,18 @@ +package com.fangjia; + +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.codec.binary.Hex; +import java.util.Scanner; + +public class test { + public static void main(String[] args) { + while (true){ + Scanner scanner = new Scanner(System.in); + String password = scanner.nextLine(); + String p =DigestUtils.md5Hex(password); + System.out.println(p); + + } + + } +} diff --git a/projects/fangjia-open/src/main/webapp/district/districtDetail.ftl b/projects/fangjia-open/src/main/webapp/district/districtDetail.ftl index df44569db..761d749d7 100644 --- a/projects/fangjia-open/src/main/webapp/district/districtDetail.ftl +++ b/projects/fangjia-open/src/main/webapp/district/districtDetail.ftl @@ -109,9 +109,11 @@

- +
diff --git a/projects/fangjia-open/src/main/webapp/static/images/baisheng_logo.jpg b/projects/fangjia-open/src/main/webapp/static/images/baisheng_logo.jpg new file mode 100644 index 000000000..5836db407 Binary files /dev/null and b/projects/fangjia-open/src/main/webapp/static/images/baisheng_logo.jpg differ diff --git a/projects/fangjia-open/src/main/webapp/static/images/baisheng_logo2.jpg b/projects/fangjia-open/src/main/webapp/static/images/baisheng_logo2.jpg new file mode 100644 index 000000000..af13b474b Binary files /dev/null and b/projects/fangjia-open/src/main/webapp/static/images/baisheng_logo2.jpg differ diff --git a/projects/fangjia-open/src/main/webapp/static/images/bs_bananer.jpg b/projects/fangjia-open/src/main/webapp/static/images/bs_bananer.jpg new file mode 100644 index 000000000..79ac3c5fd Binary files /dev/null and b/projects/fangjia-open/src/main/webapp/static/images/bs_bananer.jpg differ diff --git a/projects/fangjia-open/src/main/webapp/user/bhydLoginPage.ftl b/projects/fangjia-open/src/main/webapp/user/bhydLoginPage.ftl index 11b6bd390..18bf22242 100644 --- a/projects/fangjia-open/src/main/webapp/user/bhydLoginPage.ftl +++ b/projects/fangjia-open/src/main/webapp/user/bhydLoginPage.ftl @@ -21,12 +21,12 @@ - +