cn.hutool.core.lang.Dict Java Examples

The following examples show how to use cn.hutool.core.lang.Dict. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UploadController.java    From spring-boot-demo with MIT License 8 votes vote down vote up
@PostMapping(value = "/local", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Dict local(@RequestParam("file") MultipartFile file) {
	if (file.isEmpty()) {
		return Dict.create().set("code", 400).set("message", "文件内容为空");
	}
	String fileName = file.getOriginalFilename();
	String rawFileName = StrUtil.subBefore(fileName, ".", true);
	String fileType = StrUtil.subAfter(fileName, ".", true);
	String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
	try {
		file.transferTo(new File(localFilePath));
	} catch (IOException e) {
		log.error("【文件上传至本地】失败,绝对路径:{}", localFilePath);
		return Dict.create().set("code", 500).set("message", "文件上传失败");
	}

	log.info("【文件上传至本地】绝对路径:{}", localFilePath);
	return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", fileName).set("filePath", localFilePath));
}
 
Example #2
Source File: VerificationCodeServiceImpl.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(VerificationCode code) {
    EmailVo emailVo;
    String content;
    VerificationCode verificationCode = this.getOne(new QueryWrapper<VerificationCode>()
            .eq("scenes",code.getScenes()).eq("type",code.getType()).eq("value",code.getValue()));
    // 如果不存在有效的验证码,就创建一个新的
    TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
    Template template = engine.getTemplate("email/email.ftl");
    if(verificationCode == null){
        code.setCode(RandomUtil.randomNumbers (6));
        content = template.render(Dict.create().set("code",code.getCode()));
        emailVo = new EmailVo(Collections.singletonList(code.getValue()),"yshop后台管理系统",content);
        this.save(code);
        timedDestruction(code);
    // 存在就再次发送原来的验证码
    } else {
        content = template.render(Dict.create().set("code",verificationCode.getCode()));
        emailVo = new EmailVo(Collections.singletonList(verificationCode.getValue()),"yshop后台管理系统",content);
    }
    return emailVo;
}
 
Example #3
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用根据主键更新,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param pk         主键
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer updateById(T t, P pk, Boolean ignoreNull) {
	String tableName = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> StrUtil.appendIfMissing(s, " = ?")).collect(Collectors.toList());
	String params = StrUtil.join(Const.SEPARATOR_COMMA, columns);

	// 构造值
	List<Object> valueList = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).collect(Collectors.toList());
	valueList.add(pk);

	Object[] values = ArrayUtil.toArray(valueList, Object.class);

	String sql = StrUtil.format("UPDATE {table} SET {params} where id = ?", Dict.create().set("table", tableName).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #4
Source File: UploadController.java    From spring-boot-demo with MIT License 6 votes vote down vote up
@PostMapping(value = "/local", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Dict local(@RequestParam("file") MultipartFile file) {
	if (file.isEmpty()) {
		return Dict.create().set("code", 400).set("message", "文件内容为空");
	}
	String fileName = file.getOriginalFilename();
	String rawFileName = StrUtil.subBefore(fileName, ".", true);
	String fileType = StrUtil.subAfter(fileName, ".", true);
	String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
	try {
		file.transferTo(new File(localFilePath));
	} catch (IOException e) {
		log.error("【文件上传至本地】失败,绝对路径:{}", localFilePath);
		return Dict.create().set("code", 500).set("message", "文件上传失败");
	}

	log.info("【文件上传至本地】绝对路径:{}", localFilePath);
	return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", fileName).set("filePath", localFilePath));
}
 
Example #5
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用插入,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer insert(T t, Boolean ignoreNull) {
	String table = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	String columns = StrUtil.join(Const.SEPARATOR_COMMA, columnList);

	// 构造占位符
	String params = StrUtil.repeatAndJoin("?", columnList.size(), Const.SEPARATOR_COMMA);

	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("INSERT INTO {table} ({columns}) VALUES ({params})", Dict.create().set("table", table).set("columns", columns).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #6
Source File: VerificationCodeServiceImpl.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(VerificationCode code) {
    EmailVo emailVo;
    String content;
    VerificationCode verificationCode = verificationCodeDao.findByScenesAndTypeAndValueAndStatusIsTrue(code.getScenes(), code.getType(), code.getValue());
    // 如果不存在有效的验证码,就创建一个新的
    TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
    Template template = engine.getTemplate("email/email.ftl");
    if (verificationCode == null) {
        code.setCode(RandomUtil.randomNumbers(6));
        content = template.render(Dict.create().set("code", code.getCode()));
        emailVo = new EmailVo(Collections.singletonList(code.getValue()), "eladmin后台管理系统", content);
        timedDestruction(verificationCodeDao.save(code));
        // 存在就再次发送原来的验证码
    } else {
        content = template.render(Dict.create().set("code", verificationCode.getCode()));
        emailVo = new EmailVo(Collections.singletonList(verificationCode.getValue()), "eladmin后台管理系统", content);
    }
    return emailVo;
}
 
Example #7
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 根据对象查询
 *
 * @param t 查询条件
 * @return 对象列表
 */
public List<T> findByExample(T t) {
	String tableName = getTableName(t);
	List<Field> filterField = getField(t, true);
	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> " and " + s + " = ? ").collect(Collectors.toList());

	String where = StrUtil.join(" ", columns);
	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("SELECT * FROM {table} where 1=1 {where}", Dict.create().set("table", tableName).set("where", StrUtil.isBlank(where) ? "" : where));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, values);
	List<T> ret = CollUtil.newArrayList();
	maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, ReflectUtil.newInstance(clazz), true, false)));
	return ret;
}
 
Example #8
Source File: VerifyServiceImpl.java    From eladmin with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(String email, String key) {
    EmailVo emailVo;
    String content;
    String redisKey = key + email;
    // 如果不存在有效的验证码,就创建一个新的
    TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
    Template template = engine.getTemplate("email/email.ftl");
    Object oldCode =  redisUtils.get(redisKey);
    if(oldCode == null){
        String code = RandomUtil.randomNumbers (6);
        // 存入缓存
        if(!redisUtils.set(redisKey, code, expiration)){
            throw new BadRequestException("服务异常,请联系网站负责人");
        }
        content = template.render(Dict.create().set("code",code));
        emailVo = new EmailVo(Collections.singletonList(email),"EL-ADMIN后台管理系统",content);
    // 存在就再次发送原来的验证码
    } else {
        content = template.render(Dict.create().set("code",oldCode));
        emailVo = new EmailVo(Collections.singletonList(email),"EL-ADMIN后台管理系统",content);
    }
    return emailVo;
}
 
Example #9
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用插入,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer insert(T t, Boolean ignoreNull) {
	String table = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	String columns = StrUtil.join(Const.SEPARATOR_COMMA, columnList);

	// 构造占位符
	String params = StrUtil.repeatAndJoin("?", columnList.size(), Const.SEPARATOR_COMMA);

	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("INSERT INTO {table} ({columns}) VALUES ({params})", Dict.create().set("table", table).set("columns", columns).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #10
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用根据主键更新,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param pk         主键
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer updateById(T t, P pk, Boolean ignoreNull) {
	String tableName = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> StrUtil.appendIfMissing(s, " = ?")).collect(Collectors.toList());
	String params = StrUtil.join(Const.SEPARATOR_COMMA, columns);

	// 构造值
	List<Object> valueList = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).collect(Collectors.toList());
	valueList.add(pk);

	Object[] values = ArrayUtil.toArray(valueList, Object.class);

	String sql = StrUtil.format("UPDATE {table} SET {params} where id = ?", Dict.create().set("table", tableName).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #11
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 根据对象查询
 *
 * @param t 查询条件
 * @return 对象列表
 */
public List<T> findByExample(T t) {
	String tableName = getTableName(t);
	List<Field> filterField = getField(t, true);
	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> " and " + s + " = ? ").collect(Collectors.toList());

	String where = StrUtil.join(" ", columns);
	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("SELECT * FROM {table} where 1=1 {where}", Dict.create().set("table", tableName).set("where", StrUtil.isBlank(where) ? "" : where));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, values);
	List<T> ret = CollUtil.newArrayList();
	maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, ReflectUtil.newInstance(clazz), true, false)));
	return ret;
}
 
Example #12
Source File: EmailServiceImpl.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(String email, String key) {
	EmailVo emailVo;
	String content;
	String redisKey = key + email;
	// 如果不存在有效的验证码,就创建一个新的
	TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("templates", TemplateConfig.ResourceMode.CLASSPATH));
	Template template = engine.getTemplate("email/email.ftl");
	Object oldCode = RedisUtil.getCacheString(redisKey);
	if (oldCode == null) {
		String code = RandomUtil.randomNumbers(6);

		// 存入缓存
		RedisUtil.setCacheString(redisKey, code, CommonConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);

		content = template.render(Dict.create().set("code", code));
		emailVo = new EmailVo(Collections.singletonList(email), "Albedo后台管理系统", content);
		// 存在就再次发送原来的验证码
	} else {
		content = template.render(Dict.create().set("code", oldCode));
		emailVo = new EmailVo(Collections.singletonList(email), "Albedo后台管理系统", content);
	}
	return emailVo;
}
 
Example #13
Source File: UploadController.java    From spring-boot-demo with MIT License 6 votes vote down vote up
@PostMapping(value = "/local", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Dict local(@RequestParam("file") MultipartFile file) {
	if (file.isEmpty()) {
		return Dict.create().set("code", 400).set("message", "文件内容为空");
	}
	String fileName = file.getOriginalFilename();
	String rawFileName = StrUtil.subBefore(fileName, ".", true);
	String fileType = StrUtil.subAfter(fileName, ".", true);
	String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
	try {
		file.transferTo(new File(localFilePath));
	} catch (IOException e) {
		log.error("【文件上传至本地】失败,绝对路径:{}", localFilePath);
		return Dict.create().set("code", 500).set("message", "文件上传失败");
	}

	log.info("【文件上传至本地】绝对路径:{}", localFilePath);
	return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", fileName).set("filePath", localFilePath));
}
 
Example #14
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用插入,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer insert(T t, Boolean ignoreNull) {
	String table = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	String columns = StrUtil.join(Const.SEPARATOR_COMMA, columnList);

	// 构造占位符
	String params = StrUtil.repeatAndJoin("?", columnList.size(), Const.SEPARATOR_COMMA);

	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("INSERT INTO {table} ({columns}) VALUES ({params})", Dict.create().set("table", table).set("columns", columns).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #15
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用根据主键更新,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param pk         主键
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer updateById(T t, P pk, Boolean ignoreNull) {
	String tableName = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> StrUtil.appendIfMissing(s, " = ?")).collect(Collectors.toList());
	String params = StrUtil.join(Const.SEPARATOR_COMMA, columns);

	// 构造值
	List<Object> valueList = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).collect(Collectors.toList());
	valueList.add(pk);

	Object[] values = ArrayUtil.toArray(valueList, Object.class);

	String sql = StrUtil.format("UPDATE {table} SET {params} where id = ?", Dict.create().set("table", tableName).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #16
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 根据对象查询
 *
 * @param t 查询条件
 * @return 对象列表
 */
public List<T> findByExample(T t) {
	String tableName = getTableName(t);
	List<Field> filterField = getField(t, true);
	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> " and " + s + " = ? ").collect(Collectors.toList());

	String where = StrUtil.join(" ", columns);
	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("SELECT * FROM {table} where 1=1 {where}", Dict.create().set("table", tableName).set("where", StrUtil.isBlank(where) ? "" : where));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, values);
	List<T> ret = CollUtil.newArrayList();
	maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, ReflectUtil.newInstance(clazz), true, false)));
	return ret;
}
 
Example #17
Source File: MessageEventHandler.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@OnEvent(value = Event.CHAT)
public void onChatEvent(SocketIOClient client, AckRequest request, SingleMessageRequest data) {
    Optional<UUID> toUser = dbTemplate.findByUserId(data.getToUid());
    if (toUser.isPresent()) {
        log.info("用户 {} 刚刚私信了用户 {}:{}", data.getFromUid(), data.getToUid(), data.getMessage());
        sendToSingle(toUser.get(), data);
        request.sendAckData(Dict.create().set("flag", true).set("message", "发送成功"));
    } else {
        request.sendAckData(Dict.create()
                .set("flag", false)
                .set("message", "发送失败,对方不想理你(" + data.getToUid() + "不在线)"));
    }
}
 
Example #18
Source File: ServerController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@GetMapping
public Dict serverInfo() throws Exception {
    Server server = new Server();
    server.copyTo();
    ServerVO serverVO = ServerUtil.wrapServerVO(server);
    return ServerUtil.wrapServerDict(serverVO);
}
 
Example #19
Source File: ServerTask.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 按照标准时间来算,每隔 2s 执行一次
 */
@Scheduled(cron = "0/2 * * * * ?")
public void websocket() throws Exception {
    log.info("【推送消息】开始执行:{}", DateUtil.formatDateTime(new Date()));
    // 查询服务器状态
    Server server = new Server();
    server.copyTo();
    ServerVO serverVO = ServerUtil.wrapServerVO(server);
    Dict dict = ServerUtil.wrapServerDict(serverVO);
    wsTemplate.convertAndSend(WebSocketConsts.PUSH_SERVER, JSONUtil.toJsonStr(dict));
    log.info("【推送消息】执行结束:{}", DateUtil.formatDateTime(new Date()));
}
 
Example #20
Source File: ServerUtil.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 包装成 Dict
 *
 * @param serverVO serverVO
 * @return Dict
 */
public static Dict wrapServerDict(ServerVO serverVO) {
    Dict dict = Dict.create()
            .set("cpu", serverVO.getCpu().get(0).getData())
            .set("mem", serverVO.getMem().get(0).getData())
            .set("sys", serverVO.getSys().get(0).getData())
            .set("jvm", serverVO.getJvm().get(0).getData())
            .set("sysFile", serverVO.getSysFile().get(0).getData());
    return dict;
}
 
Example #21
Source File: MessageController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@PostMapping("/broadcast")
public Dict broadcast(@RequestBody BroadcastMessageRequest message) {
    if (isBlank(message)) {
        return Dict.create().set("flag", false).set("code", 400).set("message", "参数为空");
    }
    messageHandler.sendToBroadcast(message);
    return Dict.create().set("flag", true).set("code", 200).set("message", "发送成功");
}
 
Example #22
Source File: UploadController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@PostMapping(value = "/yun", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Dict yun(@RequestParam("file") MultipartFile file) {
	if (file.isEmpty()) {
		return Dict.create().set("code", 400).set("message", "文件内容为空");
	}
	String fileName = file.getOriginalFilename();
	String rawFileName = StrUtil.subBefore(fileName, ".", true);
	String fileType = StrUtil.subAfter(fileName, ".", true);
	String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
	try {
		file.transferTo(new File(localFilePath));
		Response response = qiNiuService.uploadFile(new File(localFilePath));
		if (response.isOK()) {
			JSONObject jsonObject = JSONUtil.parseObj(response.bodyString());

			String yunFileName = jsonObject.getStr("key");
			String yunFilePath = StrUtil.appendIfMissing(prefix, "/") + yunFileName;

			FileUtil.del(new File(localFilePath));

			log.info("【文件上传至七牛云】绝对路径:{}", yunFilePath);
			return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", yunFileName).set("filePath", yunFilePath));
		} else {
			log.error("【文件上传至七牛云】失败,{}", JSONUtil.toJsonStr(response));
			FileUtil.del(new File(localFilePath));
			return Dict.create().set("code", 500).set("message", "文件上传失败");
		}
	} catch (IOException e) {
		log.error("【文件上传至七牛云】失败,绝对路径:{}", localFilePath);
		return Dict.create().set("code", 500).set("message", "文件上传失败");
	}
}
 
Example #23
Source File: MessageEventHandler.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@OnEvent(value = Event.CHAT)
public void onChatEvent(SocketIOClient client, AckRequest request, SingleMessageRequest data) {
    Optional<UUID> toUser = dbTemplate.findByUserId(data.getToUid());
    if (toUser.isPresent()) {
        log.info("用户 {} 刚刚私信了用户 {}:{}", data.getFromUid(), data.getToUid(), data.getMessage());
        sendToSingle(toUser.get(), data);
        request.sendAckData(Dict.create().set("flag", true).set("message", "发送成功"));
    } else {
        request.sendAckData(Dict.create()
                .set("flag", false)
                .set("message", "发送失败,对方不想理你(" + data.getToUid() + "不在线)"));
    }
}
 
Example #24
Source File: BaseDao.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 通用根据主键查询单条记录
 *
 * @param pk 主键
 * @return 单条记录
 */
public T findOneById(P pk) {
	String tableName = getTableName();
	String sql = StrUtil.format("SELECT * FROM {table} where id = ?", Dict.create().set("table", tableName));
	RowMapper<T> rowMapper = new BeanPropertyRowMapper<>(clazz);
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(pk));
	return jdbcTemplate.queryForObject(sql, new Object[]{pk}, rowMapper);
}
 
Example #25
Source File: ServerTask.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 按照标准时间来算,每隔 2s 执行一次
 */
@Scheduled(cron = "0/2 * * * * ?")
public void websocket() throws Exception {
    log.info("【推送消息】开始执行:{}", DateUtil.formatDateTime(new Date()));
    // 查询服务器状态
    Server server = new Server();
    server.copyTo();
    ServerVO serverVO = ServerUtil.wrapServerVO(server);
    Dict dict = ServerUtil.wrapServerDict(serverVO);
    wsTemplate.convertAndSend(WebSocketConsts.PUSH_SERVER, JSONUtil.toJsonStr(dict));
    log.info("【推送消息】执行结束:{}", DateUtil.formatDateTime(new Date()));
}
 
Example #26
Source File: ServerUtil.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 包装成 Dict
 *
 * @param serverVO serverVO
 * @return Dict
 */
public static Dict wrapServerDict(ServerVO serverVO) {
    Dict dict = Dict.create()
            .set("cpu", serverVO.getCpu().get(0).getData())
            .set("mem", serverVO.getMem().get(0).getData())
            .set("sys", serverVO.getSys().get(0).getData())
            .set("jvm", serverVO.getJvm().get(0).getData())
            .set("sysFile", serverVO.getSysFile().get(0).getData());
    return dict;
}
 
Example #27
Source File: ServerController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@GetMapping
public Dict serverInfo() throws Exception {
    Server server = new Server();
    server.copyTo();
    ServerVO serverVO = ServerUtil.wrapServerVO(server);
    return ServerUtil.wrapServerDict(serverVO);
}
 
Example #28
Source File: JobController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@GetMapping
public ResponseEntity<ApiResponse> jobList(Integer currentPage, Integer pageSize) {
    if (ObjectUtil.isNull(currentPage)) {
        currentPage = 1;
    }
    if (ObjectUtil.isNull(pageSize)) {
        pageSize = 10;
    }
    PageInfo<JobAndTrigger> all = jobService.list(currentPage, pageSize);
    return ResponseEntity.ok(ApiResponse.ok(Dict.create().set("total", all.getTotal()).set("data", all.getList())));
}
 
Example #29
Source File: BaseDao.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 通用根据主键查询单条记录
 *
 * @param pk 主键
 * @return 单条记录
 */
public T findOneById(P pk) {
	String tableName = getTableName();
	String sql = StrUtil.format("SELECT * FROM {table} where id = ?", Dict.create().set("table", tableName));
	RowMapper<T> rowMapper = new BeanPropertyRowMapper<>(clazz);
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(pk));
	return jdbcTemplate.queryForObject(sql, new Object[]{pk}, rowMapper);
}
 
Example #30
Source File: JobController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@GetMapping
public ResponseEntity<ApiResponse> jobList(Integer currentPage, Integer pageSize) {
    if (ObjectUtil.isNull(currentPage)) {
        currentPage = 1;
    }
    if (ObjectUtil.isNull(pageSize)) {
        pageSize = 10;
    }
    PageInfo<JobAndTrigger> all = jobService.list(currentPage, pageSize);
    return ResponseEntity.ok(ApiResponse.ok(Dict.create().set("total", all.getTotal()).set("data", all.getList())));
}