Browse Source

修改心跳检测

humuyu 3 years ago
parent
commit
3d3208cd82

+ 259 - 230
eladmin-system/src/main/java/me/zhengjie/application/admin/controller/UserController.java

@@ -34,6 +34,8 @@ import me.zhengjie.base.ResultCode;
 import me.zhengjie.base.util.ApplicationContextUtil;
 import me.zhengjie.base.util.BeanCopyUtils;
 import me.zhengjie.base.util.FileUploadUtil;
+import me.zhengjie.base.websocket.AppSocketClientCache;
+import me.zhengjie.base.websocket.PcSocketClientCache;
 import me.zhengjie.config.RsaProperties;
 import me.zhengjie.dao.mybatis.entity.Dept;
 import me.zhengjie.dao.mybatis.entity.FileInfoEntity;
@@ -43,8 +45,11 @@ import me.zhengjie.dao.mybatis.mapper.BankMapper;
 import me.zhengjie.dao.mybatis.mapper.FileInfoMapper;
 import me.zhengjie.dao.mybatis.mapper.NotaryOfficeMapper;
 import me.zhengjie.exception.BadRequestException;
+import me.zhengjie.security.service.dto.OnlineUserDto;
 import me.zhengjie.utils.RsaUtils;
 import me.zhengjie.utils.enums.CodeEnum;
+
+import org.apache.commons.collections4.MapUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
@@ -59,12 +64,16 @@ import org.springframework.validation.annotation.Validated;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 
+import com.corundumstudio.socketio.SocketIOClient;
+
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.UUID;
 import java.util.stream.Collectors;
 
 /**
@@ -77,250 +86,270 @@ import java.util.stream.Collectors;
 @RequiredArgsConstructor
 public class UserController {
 
-    private final PasswordEncoder passwordEncoder;
-    private final UserService userService;
-    private final DataService dataService;
-    private final DeptService deptService;
-    private final RoleService roleService;
-    private final VerifyService verificationCodeService;
-    private final FileInfoMapper fileInfoMapper;
-    private final ApplicationContextUtil contextUtil;
-    private final BankMapper bankMapper;
-    private final NotaryOfficeMapper notaryOfficeMapper;
+	private final PasswordEncoder passwordEncoder;
+	private final UserService userService;
+	private final DataService dataService;
+	private final DeptService deptService;
+	private final RoleService roleService;
+	private final VerifyService verificationCodeService;
+	private final FileInfoMapper fileInfoMapper;
+	private final ApplicationContextUtil contextUtil;
+	private final BankMapper bankMapper;
+	private final NotaryOfficeMapper notaryOfficeMapper;
+
+	@ApiOperation("获取用户信息")
+	@GetMapping(value = "/info")
+	public ResponseEntity<Object> getUserInfo() {
+		// 这里需要处理图片显示问题
+		JwtUserDto jwtUserDto = contextUtil.getCurrentUser();
+		// 处理图片的显示,重新查询一下当前的用户的值
+		UserDto nocacheUser = userService.findUserNoCacheId(jwtUserDto.getUser().getId());
+		// 重新设置user
+		if (nocacheUser != null) {
+			// 处理客户经理和公证处才执行这里
+			if (StringUtils.isNotBlank(nocacheUser.getOrgId())) {
+				String[] split = nocacheUser.getOrgId().split("_");
+				if ("bank".equals(split[0])) {
+					nocacheUser.setOrgName(bankMapper.selectById(split[1]).getBankName());
+				} else if ("notary".equals(split[0])) {
+					NotaryOfficeEntity notaryOfficeEntity = notaryOfficeMapper.selectById(split[1]);
+					nocacheUser.setOrgName(notaryOfficeEntity.getName());
+					nocacheUser.setAutoGenerate(notaryOfficeEntity.getAutoGenerate());
+				}
+			}
+
+			FileInfoEntity fileInfo = fileInfoMapper.selectById(nocacheUser.getSignImgId());
+			if (fileInfo != null) {
+				nocacheUser.setSignImgUrl(FileUploadUtil.getFileUrl(fileInfo.getPath()));
+			} else {
+				nocacheUser.setSignImgUrl("");
+			}
+			jwtUserDto.setUser(nocacheUser);
+		}
+		return ResponseEntity.ok(jwtUserDto);
+	}
+
+	@ApiOperation("导出用户数据")
+	@GetMapping(value = "/download")
+	@PreAuthorize("@el.check('user:list')")
+	public void exportUser(HttpServletResponse response, UserQueryCriteria criteria) throws IOException {
+		userService.download(userService.queryAll(criteria), response);
+	}
 
-    @ApiOperation("获取用户信息")
-    @GetMapping(value = "/info")
-    public ResponseEntity<Object> getUserInfo() {
-        // 这里需要处理图片显示问题
-        JwtUserDto jwtUserDto = contextUtil.getCurrentUser();
-        // 处理图片的显示,重新查询一下当前的用户的值
-        UserDto nocacheUser = userService.findUserNoCacheId(jwtUserDto.getUser().getId());
-        // 重新设置user
-        if (nocacheUser != null) {
-        	//处理客户经理和公证处才执行这里
-        	if(StringUtils.isNotBlank(nocacheUser.getOrgId())) {
-        		   String[] split = nocacheUser.getOrgId().split("_");
-                   if ("bank".equals(split[0])) {
-                       nocacheUser.setOrgName(bankMapper.selectById(split[1]).getBankName());
-                   }else if ("notary".equals(split[0]))  {
-                       NotaryOfficeEntity notaryOfficeEntity = notaryOfficeMapper.selectById(split[1]);
-                       nocacheUser.setOrgName(notaryOfficeEntity.getName());
-                       nocacheUser.setAutoGenerate(notaryOfficeEntity.getAutoGenerate());
-                   }
-        	}
-         
-            FileInfoEntity fileInfo = fileInfoMapper.selectById(nocacheUser.getSignImgId());
-            if (fileInfo != null) {
-                nocacheUser.setSignImgUrl(FileUploadUtil.getFileUrl(fileInfo.getPath()));
-            } else {
-                nocacheUser.setSignImgUrl("");
-            }
-            jwtUserDto.setUser(nocacheUser);
-        }
-        return ResponseEntity.ok(jwtUserDto);
-    }
+	@ApiOperation("查询用户")
+	@GetMapping
+	@PreAuthorize("@el.check('user:list')")
+	public ResponseEntity<Object> queryUser(UserReq userReq) {
+		if (!ObjectUtils.isEmpty(userReq.getDeptId())) {
+			userReq.getDeptIds().add(userReq.getDeptId());
+			// 先查找是否存在子节点
+			List<Dept> data = deptService.findByPid(userReq.getDeptId());
+			// 然后把子节点的ID都加入到集合中
+			userReq.getDeptIds().addAll(deptService.getDeptChildren(data));
+		}
+		// 数据权限
+		List<Long> dataScopes = dataService.getDeptIds(userService.findByName(contextUtil.getCurrentUsername()));
+		// getDeptIds() 不为空并且数据权限不为空则取交集
+		Map<String, Object> userList = null;
+		if (!CollectionUtils.isEmpty(userReq.getDeptIds()) && !CollectionUtils.isEmpty(dataScopes)) {
+			// 取交集
+			userReq.getDeptIds().retainAll(dataScopes);
+			if (!CollectionUtil.isEmpty(userReq.getDeptIds())) {
+				userList = userService.queryAll(userReq);
+			}
+		} else {
+			// 否则取并集
+			userReq.getDeptIds().addAll(dataScopes);
+			userList = userService.queryAll(userReq);
+		}
+		return new ResponseEntity<>(userList, HttpStatus.OK);
+	}
 
-    @ApiOperation("导出用户数据")
-    @GetMapping(value = "/download")
-    @PreAuthorize("@el.check('user:list')")
-    public void exportUser(HttpServletResponse response, UserQueryCriteria criteria) throws IOException {
-        userService.download(userService.queryAll(criteria), response);
-    }
+	@Log("重置密码")
+	@ApiOperation("重置密码")
+	@PostMapping("/reset-password")
+	@PreAuthorize("@el.check('user:reset')")
+	public AppBaseResponse resetPassword(@RequestBody User user) {
+		checkLevel(user);
+		// 默认密码 123456
+		userService.updatePass(user.getUsername(), passwordEncoder.encode("123456"));
+		return AppBaseResponse.success();
+	}
 
-    @ApiOperation("查询用户")
-    @GetMapping
-    @PreAuthorize("@el.check('user:list')")
-    public ResponseEntity<Object> queryUser(UserReq userReq){
-        if (!ObjectUtils.isEmpty(userReq.getDeptId())) {
-            userReq.getDeptIds().add(userReq.getDeptId());
-            // 先查找是否存在子节点
-            List<Dept> data = deptService.findByPid(userReq.getDeptId());
-            // 然后把子节点的ID都加入到集合中
-            userReq.getDeptIds().addAll(deptService.getDeptChildren(data));
-        }
-        // 数据权限
-        List<Long> dataScopes = dataService.getDeptIds(userService.findByName(contextUtil.getCurrentUsername()));
-        // getDeptIds() 不为空并且数据权限不为空则取交集
-        Map<String,Object> userList = null;
-        if (!CollectionUtils.isEmpty(userReq.getDeptIds()) && !CollectionUtils.isEmpty(dataScopes)){
-            // 取交集
-            userReq.getDeptIds().retainAll(dataScopes);
-            if(!CollectionUtil.isEmpty(userReq.getDeptIds())){
-                userList = userService.queryAll(userReq);
-            }
-        } else {
-            // 否则取并集
-            userReq.getDeptIds().addAll(dataScopes);
-            userList = userService.queryAll(userReq);
-        }
-        return new ResponseEntity<>(userList,HttpStatus.OK);
-    }
+	@Log("新增用户")
+	@ApiOperation("新增用户")
+	@PostMapping
+	@PreAuthorize("@el.check('user:add')")
+	public AppBaseResponse createUser(@Validated @RequestBody UserEditReqVO userEditReqVO) {
+		User userEntity = BeanCopyUtils.convertObj(userEditReqVO, User.class);
+		checkLevel(userEntity);
+		// 默认密码 123456
+		userEntity.setPassword(passwordEncoder.encode("123456"));
+		return userService.create(userEntity);
+	}
 
-    @Log("重置密码")
-    @ApiOperation("重置密码")
-    @PostMapping("/reset-password")
-    @PreAuthorize("@el.check('user:reset')")
-    public AppBaseResponse resetPassword(@RequestBody User user) {
-        checkLevel(user);
-        // 默认密码 123456
-        userService.updatePass(user.getUsername(), passwordEncoder.encode("123456"));
-        return AppBaseResponse.success();
-    }
+	@Log("修改用户")
+	@ApiOperation("修改用户")
+	@PutMapping
+	@PreAuthorize("@el.check('user:edit')")
+	public ResponseEntity<Object> updateUser(@Validated(User.Update.class) @RequestBody UserEditReqVO userEditReqVO)
+			throws Exception {
+		User userEntity = BeanCopyUtils.convertObj(userEditReqVO, User.class);
+		checkLevel(userEntity);
+		userService.update(userEntity);
+		return new ResponseEntity<>(HttpStatus.NO_CONTENT);
+	}
 
-    @Log("新增用户")
-    @ApiOperation("新增用户")
-    @PostMapping
-    @PreAuthorize("@el.check('user:add')")
-    public AppBaseResponse createUser(@Validated @RequestBody UserEditReqVO userEditReqVO) {
-        User userEntity = BeanCopyUtils.convertObj(userEditReqVO, User.class);
-        checkLevel(userEntity);
-        // 默认密码 123456
-        userEntity.setPassword(passwordEncoder.encode("123456"));
-        return userService.create(userEntity);
-    }
+	@Log("修改用户:个人中心")
+	@ApiOperation("修改用户:个人中心")
+	@PutMapping(value = "center")
+	public ResponseEntity<Object> centerUser(@Validated(User.Update.class) @RequestBody User resources) {
+		if (!resources.getId().equals(contextUtil.getCurrentUserId())) {
+			throw new BadRequestException("不能修改他人资料");
+		}
+		userService.updateCenter(resources);
+		return new ResponseEntity<>(HttpStatus.NO_CONTENT);
+	}
 
-    @Log("修改用户")
-    @ApiOperation("修改用户")
-    @PutMapping
-    @PreAuthorize("@el.check('user:edit')")
-    public ResponseEntity<Object> updateUser(@Validated(User.Update.class) @RequestBody UserEditReqVO userEditReqVO) throws Exception {
-        User userEntity = BeanCopyUtils.convertObj(userEditReqVO, User.class);
-        checkLevel(userEntity);
-        userService.update(userEntity);
-        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
-    }
+	@Log("删除用户")
+	@ApiOperation("删除用户")
+	@DeleteMapping
+	@PreAuthorize("@el.check('user:del')")
+	public ResponseEntity<Object> deleteUser(@RequestBody Set<Long> ids) {
+		for (Long id : ids) {
+			Integer currentLevel = Collections.min(roleService.findByUsersId(contextUtil.getCurrentUserId()).stream()
+					.map(RoleSmallDto::getLevel).collect(Collectors.toList()));
+			Integer optLevel = Collections.min(
+					roleService.findByUsersId(id).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
+			if (currentLevel > optLevel) {
+				throw new BadRequestException("角色权限不足,不能删除:" + userService.findById(id).getUsername());
+			}
+		}
+		userService.delete(ids);
+		return new ResponseEntity<>(HttpStatus.OK);
+	}
 
-    @Log("修改用户:个人中心")
-    @ApiOperation("修改用户:个人中心")
-    @PutMapping(value = "center")
-    public ResponseEntity<Object> centerUser(@Validated(User.Update.class) @RequestBody User resources){
-        if(!resources.getId().equals(contextUtil.getCurrentUserId())){
-            throw new BadRequestException("不能修改他人资料");
-        }
-        userService.updateCenter(resources);
-        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
-    }
+	@ApiOperation("修改密码")
+	@PostMapping(value = "/updatePass")
+	public AppBaseResponse<?> updateUserPass(@RequestBody UserPassVo passVo) throws Exception {
+		String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passVo.getOldPass());
+		String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passVo.getNewPass());
+		UserDto user = userService.findByName(contextUtil.getCurrentUsername());
+		if (!passwordEncoder.matches(oldPass, user.getPassword())) {
+			throw new BadRequestException("修改失败,旧密码错误");
+		}
+		if (passwordEncoder.matches(newPass, user.getPassword())) {
+			throw new BadRequestException("新密码不能与旧密码相同");
+		}
+		userService.updatePass(user.getUsername(), passwordEncoder.encode(newPass));
+		return AppBaseResponse.success();
+	}
 
-    @Log("删除用户")
-    @ApiOperation("删除用户")
-    @DeleteMapping
-    @PreAuthorize("@el.check('user:del')")
-    public ResponseEntity<Object> deleteUser(@RequestBody Set<Long> ids){
-        for (Long id : ids) {
-            Integer currentLevel =  Collections.min(roleService.findByUsersId(contextUtil.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
-            Integer optLevel =  Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
-            if (currentLevel > optLevel) {
-                throw new BadRequestException("角色权限不足,不能删除:" + userService.findById(id).getUsername());
-            }
-        }
-        userService.delete(ids);
-        return new ResponseEntity<>(HttpStatus.OK);
-    }
+	@ApiOperation("修改头像")
+	@PostMapping(value = "/updateAvatar")
+	public ResponseEntity<Object> updateUserAvatar(@RequestParam MultipartFile avatar) {
+		return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK);
+	}
 
-    @ApiOperation("修改密码")
-    @PostMapping(value = "/updatePass")
-    public AppBaseResponse<?> updateUserPass(@RequestBody UserPassVo passVo) throws Exception {
-        String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPass());
-        String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPass());
-        UserDto user = userService.findByName(contextUtil.getCurrentUsername());
-        if(!passwordEncoder.matches(oldPass, user.getPassword())){
-            throw new BadRequestException("修改失败,旧密码错误");
-        }
-        if(passwordEncoder.matches(newPass, user.getPassword())){
-            throw new BadRequestException("新密码不能与旧密码相同");
-        }
-        userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass));
-        return AppBaseResponse.success();
-    }
+	@Log("修改邮箱")
+	@ApiOperation("修改邮箱")
+	@PostMapping(value = "/updateEmail/{code}")
+	public ResponseEntity<Object> updateUserEmail(@PathVariable String code, @RequestBody User user) throws Exception {
+		String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, user.getPassword());
+		UserDto userDto = userService.findByName(contextUtil.getCurrentUsername());
+		if (!passwordEncoder.matches(password, userDto.getPassword())) {
+			throw new BadRequestException("密码错误");
+		}
+		verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code);
+		userService.updateEmail(userDto.getUsername(), user.getEmail());
+		return new ResponseEntity<>(HttpStatus.OK);
+	}
 
-    @ApiOperation("修改头像")
-    @PostMapping(value = "/updateAvatar")
-    public ResponseEntity<Object> updateUserAvatar(@RequestParam MultipartFile avatar) {
-        return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK);
-    }
+	/**
+	 *
+	 * 发送授权验证信息
+	 * 
+	 * @param userId
+	 * @return
+	 */
+	@Log("发送授权验证信息")
+	@ApiOperation("发送授权验证信息")
+	@GetMapping(value = "/sendAuthMessage")
+	public ResponseEntity<Object> sendAuthMessage(@RequestParam String userId) {
+		userService.sendAuthMessage(userId);
+		return new ResponseEntity<>(HttpStatus.OK);
+	}
 
-    @Log("修改邮箱")
-    @ApiOperation("修改邮箱")
-    @PostMapping(value = "/updateEmail/{code}")
-    public ResponseEntity<Object> updateUserEmail(@PathVariable String code,@RequestBody User user) throws Exception {
-        String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,user.getPassword());
-        UserDto userDto = userService.findByName(contextUtil.getCurrentUsername());
-        if(!passwordEncoder.matches(password, userDto.getPassword())){
-            throw new BadRequestException("密码错误");
-        }
-        verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code);
-        userService.updateEmail(userDto.getUsername(),user.getEmail());
-        return new ResponseEntity<>(HttpStatus.OK);
-    }
+	/**
+	 * 验证授权验证信息
+	 * 
+	 * @param user
+	 * @return
+	 */
+	@Log("验证授权验证信息")
+	@ApiOperation("验证授权验证信息")
+	@PostMapping(value = "/verifyAuthMessage")
+	public AppBaseResponse verifyAuthMessage(@RequestBody User user) {
+		userService.verifyAuthMessage(user);
+		return AppBaseResponse.success();
+	}
 
-    /**
-     *
-     * 发送授权验证信息
-     * @param userId
-     * @return
-     */
-    @Log("发送授权验证信息")
-    @ApiOperation("发送授权验证信息")
-    @GetMapping(value = "/sendAuthMessage")
-    public ResponseEntity<Object> sendAuthMessage(@RequestParam String userId) {
-        userService.sendAuthMessage(userId);
-        return new ResponseEntity<>(HttpStatus.OK);
-    }
+	/**
+	 * 如果当前用户的角色级别低于创建用户的角色级别,则抛出权限不足的错误
+	 * 
+	 * @param resources /
+	 */
+	private void checkLevel(User resources) {
+		Integer currentLevel = Collections.min(roleService.findByUsersId(contextUtil.getCurrentUserId()).stream()
+				.map(RoleSmallDto::getLevel).collect(Collectors.toList()));
+		Integer optLevel = roleService.findByRoles(resources.getRoles());
+		if (currentLevel > optLevel) {
+			throw new BadRequestException("角色权限不足");
+		}
+	}
 
-    /**
-     * 验证授权验证信息
-     * @param user
-     * @return
-     */
-    @Log("验证授权验证信息")
-    @ApiOperation("验证授权验证信息")
-    @PostMapping(value = "/verifyAuthMessage")
-    public AppBaseResponse verifyAuthMessage(@RequestBody User user){
-        userService.verifyAuthMessage(user);
-        return AppBaseResponse.success();
-    }
+	/**
+	 * 上传签名
+	 * 
+	 * @param user
+	 * @return
+	 */
+	@PostMapping(value = "/uploadSeal")
+	public AppBaseResponse uploadSeal(@RequestBody User user) {
+		return userService.uploadSeal(user);
+	}
 
-    /**
-     * 如果当前用户的角色级别低于创建用户的角色级别,则抛出权限不足的错误
-     * @param resources /
-     */
-    private void checkLevel(User resources) {
-        Integer currentLevel =  Collections.min(roleService.findByUsersId(contextUtil.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
-        Integer optLevel = roleService.findByRoles(resources.getRoles());
-        if (currentLevel > optLevel) {
-            throw new BadRequestException("角色权限不足");
-        }
-    }
+	/**
+	 * 获取签名状态
+	 * 
+	 * @return
+	 */
+	@AnonymousPostMapping("/getAuthStatus")
+	public AppBaseResponse getAuthStatus() {
+		return userService.getAuthStatus();
+	}
 
-    /**
-     * 上传签名
-     * @param user
-     * @return
-     */
-    @PostMapping(value = "/uploadSeal")
-    public AppBaseResponse uploadSeal(@RequestBody User user){
-        return userService.uploadSeal(user);
-    }
+	/**
+	 * 
+	 * 校验登录状态
+	 * 
+	 * @return
+	 */
+	
+	@AnonymousPostMapping("/checkAuth")
+	public AppBaseResponse<?> checkAuth() {
+		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+		if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
+			return AppBaseResponse.error(ResultCode.PERMISSION_TOKEN_INVALID);
+		}
+		// 还有一个判断,判断当前是否有websocket
+		Object securityContextUser = authentication.getPrincipal();
+		OnlineUserDto userDto = (OnlineUserDto) securityContextUser;
+		HashMap<UUID, SocketIOClient> map = PcSocketClientCache.socketIOClient(userDto.getUsername());
+		if (MapUtils.isEmpty(map)) {
+			return AppBaseResponse.error(ResultCode.PERMISSION_TOKEN_INVALID);
+		}
+		return AppBaseResponse.success();
+	}
 
-    /**
-     * 获取签名状态
-     * @return
-     */
-    @AnonymousPostMapping("/getAuthStatus")
-    public AppBaseResponse getAuthStatus(){
-        return userService.getAuthStatus();
-    }
-    /**
-     * 校验登录状态
-     * @return
-     */
-    @AnonymousPostMapping("/checkAuth")
-    public AppBaseResponse<?> checkAuth(){
-         Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
-        if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
-         return	AppBaseResponse.error(ResultCode.PERMISSION_TOKEN_INVALID);
-        }
-        return AppBaseResponse.success();
-    }
-    
 }

+ 24 - 17
eladmin-system/src/main/java/me/zhengjie/base/websocket/SocketEventListenner.java

@@ -8,6 +8,7 @@ import java.util.Map;
 import java.util.Set;
 import java.util.UUID;
 
+import org.apache.commons.collections4.MapUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
@@ -21,6 +22,7 @@ import com.corundumstudio.socketio.annotation.OnEvent;
 
 import lombok.extern.slf4j.Slf4j;
 import me.zhengjie.security.service.OnlineUserService;
+
 /**
  * @author litong
  * @date 2019/11/6 15:59
@@ -49,22 +51,13 @@ public class SocketEventListenner {
 		String pcSname = handshakeData.getSingleUrlParam("pcSname");
 		if (StringUtils.isNotBlank(pcSname)) {
 			client.sendEvent("connectSucc", "success");
-			System.out.println("pc建立连接");
+			log.info("pc建立连接");
 		}
 		String appSname = handshakeData.getSingleUrlParam("appSname");
 		if (StringUtils.isNotBlank(appSname)) {
 			client.sendEvent("connectSucc", "success");
-			System.out.println("app建立连接");
+			log.info("app建立连接");
 		}
-//		String pcSname = handshakeData.getSingleUrlParam("pcSname");
-//		if(StringUtils.isNotBlank(pcSname)) {
-//			client.sendEvent("connectSucc", "success");
-//			System.out.println("pc建立连接");
-//		}
-//		sname = client.getHandshakeData().getSingleUrlParam("sname");
-//		String sname = handshakeData.getSingleUrlParam("pcSname");
-//		UUID sessionId = client.getSessionId();
-//		webSocketClientCache.saveClient(sname, sessionId, client);
 
 	}
 
@@ -90,12 +83,11 @@ public class SocketEventListenner {
 			// 解绑公证处和订单关系
 			appPcBindSocket.delBusinessNo(appSname);
 			log.info("关闭连接 appSname: {}", appSname);
-			// TODO 处理绑定关系
+
 		}
 	}
 
 	// 消息接收入口,当接收到消息后,查找发送目标客户端,并且向该客户端发送消息,且给自己发送消息
-
 	@OnEvent("pcRegisterEvent")
 	public void pcRegisterEvent(SocketIOClient client, AckRequest request, Map<String, String> map) throws Exception {
 		// 在新增之前,先判断当前人是否
@@ -104,7 +96,7 @@ public class SocketEventListenner {
 		String pcSname = map.get("pcSname");
 		// 判断当前公证员是否包含
 		Set<String> usernames = onlineUserService.getAllLoginUserName();
-		// 判断这个人必须登录,才能注入
+		// TODO 判断这个人必须登录,才能注入,这里必须是公证员
 		if (StringUtils.isNotBlank(pcSname) && usernames.contains(pcSname)) {
 			// 如果存在先移除,再新增
 			List<String> list = new ArrayList<String>();
@@ -113,7 +105,7 @@ public class SocketEventListenner {
 			UUID sessionId = client.getSessionId();
 			// 移除用户
 			HashMap<UUID, SocketIOClient> socketIOClient = pcSocketClientCache.getUserClient(pcSname);
-			if (socketIOClient != null) {
+			if (MapUtils.isNotEmpty(socketIOClient)) {
 				Collection<SocketIOClient> collection = socketIOClient.values();
 //				for (SocketIOClient ioClient : collection) {
 //					log.info("发送退出登录:" + pcSname);
@@ -126,7 +118,7 @@ public class SocketEventListenner {
 			}
 
 			pcSocketClientCache.saveClient(pcSname, sessionId, client);
-			log.info("将sname注册到websocket里面:" + pcSname);
+			log.info("将pcSname注册到websocket里面:" + pcSname);
 		} else {
 			// 保存,先判断这里是否存在,如果存在发生close
 			HashMap<UUID, SocketIOClient> socketIOClient = pcSocketClientCache.getUserClient(pcSname);
@@ -144,6 +136,21 @@ public class SocketEventListenner {
 	}
 
 	// 消息接收入口,当接收到消息后,查找发送目标客户端,并且向该客户端发送消息,且给自己发送消息
+	@OnEvent("pcPingEvent")
+	public void pingEvent(SocketIOClient client, AckRequest request, Map<String, String> map) throws Exception {
+		String pcSname = map.get("pcSname");
+		if (StringUtils.isNotBlank(pcSname)) {
+			HashMap<UUID, SocketIOClient> socketIOClient = pcSocketClientCache.getUserClient(pcSname);
+			if (MapUtils.isEmpty(socketIOClient)) {
+				client.sendEvent("logoutEvent", "close");
+			}
+		} else {
+			log.info("当前公证员的心跳检测:" + pcSname);
+		}
+
+	}
+
+	// 消息接收入口,当接收到消息后,查找发送目标客户端,并且向该客户端发送消息,且给自己发送消息
 	@OnEvent("appRegisterEvent")
 	public void appRegisterEvent(SocketIOClient client, AckRequest request, Map<String, String> map) throws Exception {
 		HandshakeData shakeData = client.getHandshakeData();
@@ -167,7 +174,7 @@ public class SocketEventListenner {
 			appSocketClientCache.deleteSname(appSname);
 			appSocketClientCache.saveClient(appSname, sessionId, client);
 			// 发送
-			log.info("将sname注册到websocket里面:" + appSname);
+			log.info("将appSname注册到websocket里面:" + appSname);
 		}
 
 	}