cn.hutool.json.JSONUtil Java Examples

The following examples show how to use cn.hutool.json.JSONUtil. 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: 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 #2
Source File: JsonBeautyListener.java    From MooTool with MIT License 6 votes vote down vote up
private static String formatJson(String jsonText) {
    try {
        jsonText = JSONUtil.toJsonPrettyStr(jsonText);
    } catch (Exception e1) {
        JOptionPane.showMessageDialog(App.mainFrame, "格式化失败!\n\n" + e1.getMessage(), "失败",
                JOptionPane.ERROR_MESSAGE);
        log.error(ExceptionUtils.getStackTrace(e1));
        try {
            jsonText = JSONUtil.formatJsonStr(jsonText);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(App.mainFrame, "格式化失败!\n\n" + e.getMessage(), "失败",
                    JOptionPane.ERROR_MESSAGE);
            log.error(ExceptionUtils.getStackTrace(e));
        }
    }
    return jsonText;
}
 
Example #3
Source File: ResponseUtil.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 往 response 写出 json
 *
 * @param response  响应
 * @param exception 异常
 */
public static void renderJson(HttpServletResponse response, BaseException exception) {
    try {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(200);

        // FIXME: hutool 的 BUG:JSONUtil.toJsonStr()
        //  将JSON转为String的时候,忽略null值的时候转成的String存在错误
        response.getWriter()
                .write(JSONUtil.toJsonStr(new JSONObject(ApiResponse.ofException(exception), false)));
    } catch (IOException e) {
        log.error("Response写出JSON异常,", e);
    }
}
 
Example #4
Source File: PictureServiceImpl.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
@Override
public void synchronize() {
    //链式构建请求
    String result = HttpRequest.get(CommonConstant.SM_MS_URL + "/v2/upload_history")
            //头信息,多个头信息多次调用此方法即可
            .header("Authorization", token)
            .timeout(20000)
            .execute().body();
    JSONObject jsonObject = JSONUtil.parseObj(result);
    List<Picture> pictures = JSON.parseArray(jsonObject.get("data").toString(), Picture.class);
    for (Picture picture : pictures) {
        if (!pictureDao.existsByUrl(picture.getUrl())) {
            picture.setSize(FileUtils.getSize(Integer.parseInt(picture.getSize())));
            picture.setUsername("System Sync");
            picture.setMd5Code("");
            pictureDao.save(picture);
        }
    }
}
 
Example #5
Source File: DirectQueueOneHandler.java    From spring-boot-demo with MIT License 6 votes vote down vote up
@RabbitHandler
public void directHandlerManualAck(MessageStruct messageStruct, Message message, Channel channel) {
    //  如果手动ACK,消息会被监听消费,但是消息在队列中依旧存在,如果 未配置 acknowledge-mode 默认是会在消费完毕后自动ACK掉
    final long deliveryTag = message.getMessageProperties().getDeliveryTag();
    try {
        log.info("直接队列1,手动ACK,接收消息:{}", JSONUtil.toJsonStr(messageStruct));
        // 通知 MQ 消息已被成功消费,可以ACK了
        channel.basicAck(deliveryTag, false);
    } catch (IOException e) {
        try {
            // 处理失败,重新压入MQ
            channel.basicRecover();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
 
Example #6
Source File: ResponseUtil.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 往 response 写出 json
 *
 * @param response  响应
 * @param exception 异常
 */
public static void renderJson(HttpServletResponse response, BaseException exception) {
    try {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(200);

        // FIXME: hutool 的 BUG:JSONUtil.toJsonStr()
        //  将JSON转为String的时候,忽略null值的时候转成的String存在错误
        response.getWriter()
                .write(JSONUtil.toJsonStr(new JSONObject(ApiResponse.ofException(exception), false)));
    } catch (IOException e) {
        log.error("Response写出JSON异常,", e);
    }
}
 
Example #7
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 #8
Source File: LmitFilterCluster.java    From fw-spring-cloud with Apache License 2.0 6 votes vote down vote up
@Override
public Object run(){
    RequestContext ctx = RequestContext.getCurrentContext();
    long currentSecond = System.currentTimeMillis() / 1000;
    String key="fw-cloud-zuul-extend:"+"limit:"+currentSecond;
    try{
        if(!redisTemplate.hasKey(key)){
            redisTemplate.opsForValue().set(key,LIMIT_INIT_VALUE,LIMIT_CACHE_TIME,TimeUnit.SECONDS);
        }
        Long increment = redisTemplate.opsForValue().increment(key, 1);
        if(increment>=LIMIT_RATE_CLUSTER){
            ctx.setSendZuulResponse(false);
            //失败之后通知后续不应该执行了
            ctx.set("isShould",false);
            ctx.setResponseBody(JSONUtil.toJsonStr(FwResult.failedMsg("当前访问量较大,请稍后重试")));
            ctx.getResponse().setContentType(APPLICATION_JSON_CHARSET_UTF8);
            return null;
        }

    }catch (Exception e){
        log.error("LmitFilterCluster exception:{}",e);
        rateLimiter.acquire();
    }
    return null;
}
 
Example #9
Source File: DingMsgForm.java    From WePush with MIT License 6 votes vote down vote up
@Override
public void init(String msgName) {
    clearAllField();
    initAppNameList();
    List<TMsgDing> tMsgDingList = msgDingMapper.selectByMsgTypeAndMsgName(MessageTypeEnum.DING_CODE, msgName);
    if (tMsgDingList.size() > 0) {
        TMsgDing tMsgDing = tMsgDingList.get(0);
        String dingMsgType = tMsgDing.getDingMsgType();
        getInstance().getAppNameComboBox().setSelectedItem(agentIdToAppNameMap.get(tMsgDing.getAgentId()));
        getInstance().getMsgTypeComboBox().setSelectedItem(dingMsgType);
        DingMsg dingMsg = JSONUtil.toBean(tMsgDing.getContent(), DingMsg.class);
        getInstance().getContentTextArea().setText(dingMsg.getContent());
        getInstance().getTitleTextField().setText(dingMsg.getTitle());
        getInstance().getPicUrlTextField().setText(dingMsg.getPicUrl());
        getInstance().getUrlTextField().setText(dingMsg.getUrl());
        getInstance().getBtnTxtTextField().setText(dingMsg.getBtnTxt());
        getInstance().getWebHookTextField().setText(tMsgDing.getWebHook());

        switchDingMsgType(dingMsgType);

        switchRadio(tMsgDing.getRadioType());
    } else {
        switchDingMsgType("文本消息");
    }
}
 
Example #10
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 #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: AopLog.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 前置操作
 *
 * @param point 切入点
 */
@Before("log()")
public void beforeLog(JoinPoint point) {
	ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

	HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

	log.info("【请求 URL】:{}", request.getRequestURL());
	log.info("【请求 IP】:{}", request.getRemoteAddr());
	log.info("【请求类名】:{},【请求方法名】:{}", point.getSignature().getDeclaringTypeName(), point.getSignature().getName());

	Map<String, String[]> parameterMap = request.getParameterMap();
	log.info("【请求参数】:{},", JSONUtil.toJsonStr(parameterMap));
	Long start = System.currentTimeMillis();
	request.setAttribute(START_TIME, start);
}
 
Example #13
Source File: UserServiceImpl.java    From fw-spring-cloud with Apache License 2.0 6 votes vote down vote up
@Override
public User getUserById(long id) {
    String userRedis = redisTemplate.opsForValue().get(String.valueOf(id));
    if(StrUtil.isEmpty(userRedis)){
        User userByDao = getUserByDao(id);
        if(null!=userByDao){
            redisTemplate.opsForValue().set(String.valueOf(id),JSONUtil.toJsonStr(userByDao));
            return  userByDao;
        }else{
            return null;
        }
    }else{
        log.info("我是缓存的,有点叼");
        return JSONUtil.toBean(userRedis,User.class);
    }
}
 
Example #14
Source File: ExtractApiController.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
/**
 * 下载压缩文件中的字幕
 * @param data
 * @return
 */
public void down_archive_file() {
	HttpRequest request = getRequest();
	HttpResponse response = getResponse();
	String data = request.getParaToStr("data");
	if(data == null) {
		outJsonpMessage(request,response, 1, "请求数据错误");
		return;
	}
	logger.info("data="+data);
	if(data == null || data.length() < 10) {
		logger.error("data=null");
		outJsonpMessage(request,response, 1, "参数错误");
		return;
	}
	JSONObject dataJson = JSONUtil.parseObj(data);
	JSONArray items = dataJson.getJSONArray("items");
	if(items == null || items.size() == 0) {
		logger.error("items=null");
		outJsonpMessage(request,response, 1, "参数错误");
		return;
	}
	
	JSONObject resp = new JSONObject();
	resp.put("saveSelected", ExtractDialog.extractDialog.saveSelected(items));
	outJsonpMessage(request,response, 0, "OK", resp);
}
 
Example #15
Source File: GlobalExceptionHandler.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ApiResponse handlerException(Exception e) {
    if (e instanceof NoHandlerFoundException) {
        log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", ((NoHandlerFoundException) e).getRequestURL(), ((NoHandlerFoundException) e).getHttpMethod());
        return ApiResponse.ofStatus(Status.REQUEST_NOT_FOUND);
    } else if (e instanceof HttpRequestMethodNotSupportedException) {
        log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", ((HttpRequestMethodNotSupportedException) e).getMethod(), JSONUtil.toJsonStr(((HttpRequestMethodNotSupportedException) e).getSupportedHttpMethods()));
        return ApiResponse.ofStatus(Status.HTTP_BAD_METHOD);
    } else if (e instanceof MethodArgumentNotValidException) {
        log.error("【全局异常拦截】MethodArgumentNotValidException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), ((MethodArgumentNotValidException) e).getBindingResult()
                .getAllErrors()
                .get(0)
                .getDefaultMessage(), null);
    } else if (e instanceof ConstraintViolationException) {
        log.error("【全局异常拦截】ConstraintViolationException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), CollUtil.getFirst(((ConstraintViolationException) e).getConstraintViolations())
                .getMessage(), null);
    } else if (e instanceof MethodArgumentTypeMismatchException) {
        log.error("【全局异常拦截】MethodArgumentTypeMismatchException: 参数名 {}, 异常信息 {}", ((MethodArgumentTypeMismatchException) e).getName(), ((MethodArgumentTypeMismatchException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_MATCH);
    } else if (e instanceof HttpMessageNotReadableException) {
        log.error("【全局异常拦截】HttpMessageNotReadableException: 错误信息 {}", ((HttpMessageNotReadableException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_NULL);
    } else if (e instanceof BadCredentialsException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USERNAME_PASSWORD_ERROR);
    } else if (e instanceof DisabledException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USER_DISABLED);
    } else if (e instanceof BaseException) {
        log.error("【全局异常拦截】DataManagerException: 状态码 {}, 异常信息 {}", ((BaseException) e).getCode(), e.getMessage());
        return ApiResponse.ofException((BaseException) e);
    }

    log.error("【全局异常拦截】: 异常信息 {} ", e.getMessage());
    return ApiResponse.ofStatus(Status.ERROR);
}
 
Example #16
Source File: RestfulAccessDeniedHandler.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpServletRequest request,
                   HttpServletResponse response,
                   AccessDeniedException e) throws IOException, ServletException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage())));
    response.getWriter().flush();
}
 
Example #17
Source File: RestAuthenticationEntryPoint.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage())));
    response.getWriter().flush();
}
 
Example #18
Source File: PictureServiceImpl.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Throwable.class)
public Picture upload(MultipartFile multipartFile, String username) {
    File file = FileUtils.toFile(multipartFile);
    // 验证是否重复上传
    Picture picture = pictureDao.findByMd5Code(FileUtils.getMd5(file));
    if (picture != null) {
        return picture;
    }
    HashMap<String, Object> paramMap = new HashMap<>(1);
    paramMap.put("smfile", file);
    // 上传文件
    String result = HttpRequest.post(CommonConstant.SM_MS_URL + "/v2/upload")
            .header("Authorization", token)
            .form(paramMap)
            .timeout(20000)
            .execute().body();
    JSONObject jsonObject = JSONUtil.parseObj(result);
    if (!jsonObject.get(CODE).toString().equals(SUCCESS)) {
        throw new SkException(TranslatorUtil.translate(jsonObject.get(MSG).toString()));
    }
    picture = JSON.parseObject(jsonObject.get("data").toString(), Picture.class);
    picture.setSize(FileUtils.getSize(Integer.parseInt(picture.getSize())));
    picture.setUsername(username);
    picture.setMd5Code(FileUtils.getMd5(file));
    picture.setFilename(FileUtils.getFileNameNoEx(multipartFile.getOriginalFilename()) + "." + FileUtils.getExtensionName(multipartFile.getOriginalFilename()));
    pictureDao.save(picture);
    //删除临时文件
    FileUtils.del(file);
    return picture;

}
 
Example #19
Source File: RedisUtils.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * Object转成JSON数据
 */
private String toJson(Object object){
    if (object instanceof Integer || object instanceof Long || object instanceof Float || object instanceof Double || object instanceof Boolean || object instanceof String){
        return String.valueOf(object);
    }
    return JSONUtil.toJsonStr(object);
}
 
Example #20
Source File: RestfulAccessDeniedHandler.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpServletRequest request,
                   HttpServletResponse response,
                   AccessDeniedException e) throws IOException, ServletException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage())));
    response.getWriter().flush();
}
 
Example #21
Source File: Neo4jTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 测试查询 鸣人 学了哪些课程
 */
@Test
public void testFindLessonsByStudent() {
    // 深度为1,则课程的任教老师的属性为null
    // 深度为2,则会把课程的任教老师的属性赋值
    List<Lesson> lessons = neoService.findLessonsFromStudent("漩涡鸣人", 2);

    lessons.forEach(lesson -> log.info("【lesson】= {}", JSONUtil.toJsonStr(lesson)));
}
 
Example #22
Source File: SysUserServiceTest.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 查询符合条件的第一条数据
 */
@Test
public void findOneTest(){
    Query query = Query.query(Criteria.where("user_name").is("root"));
    SysUser sysUser= mongoTemplate.findOne(query, SysUser.class);
    log.info("find 影响数据:"+JSONUtil.toJsonStr(sysUser));
}
 
Example #23
Source File: BaseDao.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 通用根据主键删除
 *
 * @param pk 主键
 * @return 影响行数
 */
protected Integer deleteById(P pk) {
	String tableName = getTableName();
	String sql = StrUtil.format("DELETE FROM {table} where id = ?", Dict.create().set("table", tableName));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(pk));
	return jdbcTemplate.update(sql, pk);
}
 
Example #24
Source File: GenUtils.java    From ruoyiplus with MIT License 5 votes vote down vote up
private static void setColumnConfigInfo(ColumnInfo column,Map<String,String[]> params){
    //格式形如:{type:'dict',url:''},type:text(默认),select(下拉框,配合url获取下拉列表),dict(数据词典下拉框),checkbox,radio,date(配合format),autocomplete(配合url),tree(选择树,配合url),switch等
    String _paramValue = Convert.toStr(getParam(params,column.getAttrname() + "_editArg"),"");
    if(!_paramValue.startsWith("{")) _paramValue = "{" + _paramValue;
    if(!_paramValue.endsWith("}")) _paramValue = _paramValue + "}";
    JSONObject json = JSONUtil.parseObj(_paramValue);

    ColumnConfigInfo cci = new ColumnConfigInfo();
    cci.setType(Convert.toStr(json.get("type"),"text"));
    cci.setValue(json.toString());
    cci.setTitle(column.getColumnComment());
    column.setConfigInfo(cci);

}
 
Example #25
Source File: RestAuthenticationEntryPoint.java    From mall-swarm with Apache License 2.0 5 votes vote down vote up
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Cache-Control","no-cache");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage())));
    response.getWriter().flush();
}
 
Example #26
Source File: RestfulAccessDeniedHandler.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpServletRequest request,
                   HttpServletResponse response,
                   AccessDeniedException e) throws IOException, ServletException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage())));
    response.getWriter().flush();
}
 
Example #27
Source File: AliOssTemplate.java    From magic-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取上传凭证,普通上传
 * TODO 上传大小限制、基础路径
 *
 * @param bucketName 存储桶名称
 * @param expireTime 过期时间,单位秒
 * @return 上传凭证
 */
public String getUploadToken(String bucketName, long expireTime) {
	String baseDir = "upload";

	long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
	Date expiration = new Date(expireEndTime);

	PolicyConditions policy = new PolicyConditions();
	// 默认大小限制10M
	policy.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, ossProperties.getAliOss()
		.getArgs()
		.get("contentLengthRange", 1024 * 1024 * 10));
	policy.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, baseDir);

	String postPolicy = ossClient.generatePostPolicy(expiration, policy);
	byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
	String encodedPolicy = BinaryUtil.toBase64String(binaryData);
	String postSignature = ossClient.calculatePostSignature(postPolicy);

	Map<String, String> respMap = new LinkedHashMap<>(16);
	respMap.put("accessid", ossProperties.getAliOss()
		.getAccessKey());
	respMap.put("policy", encodedPolicy);
	respMap.put("signature", postSignature);
	respMap.put("dir", baseDir);
	respMap.put("host", getOssEndpoint(bucketName));
	respMap.put("expire", String.valueOf(expireEndTime / 1000));
	return JSONUtil.toJsonStr(respMap);
}
 
Example #28
Source File: WebUtil.java    From magic-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 返回json
 *
 * @param response    HttpServletResponse
 * @param result      结果对象
 * @param contentType contentType
 */
public static void renderJson(HttpServletResponse response, Object result, String contentType) {
	response.setCharacterEncoding("UTF-8");
	response.setContentType(contentType);
	try (PrintWriter out = response.getWriter()) {
		out.append(JSONUtil.toJsonStr(result));
	} catch (IOException e) {
		log.error(e.getMessage(), e);
	}
}
 
Example #29
Source File: FabricService.java    From fabric-java-block with GNU General Public License v3.0 5 votes vote down vote up
public InvokeAsyncQueryResult asyncQueryResult(InvokeAsyncQueryRequest invokeAsyncQueryRequest)  {
    HFClient client = HFClient.createNewInstance();
    Channel currentChannel = super.initChannel(client, invokeAsyncQueryRequest);

    FabricTemplate fabricTemplate = new FabricTemplate();
    FabricTemplate.setClient(client);

    InvokeAsyncQueryResult result = fabricTemplate.asyncQueryResult(currentChannel,invokeAsyncQueryRequest.getTxId());

    result.setOrderNo(invokeAsyncQueryRequest.getOrderNo());
    result.setRequestContext(JSONUtil.toJsonStr(invokeAsyncQueryRequest));
    result.setReturnNo(invokeAsyncQueryRequest.getTxId());
    result.setResponseContext(JSONUtil.toJsonStr(result));
    return result;
}
 
Example #30
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()));
}