Java Code Examples for cn.hutool.json.JSONUtil

The following examples show how to use cn.hutool.json.JSONUtil. These examples are extracted from open source projects. 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 Project: sk-admin   Source File: PictureServiceImpl.java    License: 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 2
Source Project: MooTool   Source File: JsonBeautyListener.java    License: 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 Project: spring-boot-demo   Source File: ResponseUtil.java    License: 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 Project: spring-boot-demo   Source File: ResponseUtil.java    License: 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 5
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 Project: spring-boot-demo   Source File: BaseDao.java    License: 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 7
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 8
Source Project: fw-spring-cloud   Source File: UserServiceImpl.java    License: 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 9
Source Project: spring-boot-demo   Source File: AopLog.java    License: 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 10
Source Project: spring-boot-demo   Source File: BaseDao.java    License: 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 11
Source Project: WePush   Source File: DingMsgForm.java    License: 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 12
Source Project: fw-spring-cloud   Source File: LmitFilterCluster.java    License: 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 13
Source Project: spring-boot-demo   Source File: DirectQueueOneHandler.java    License: 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 14
Source Project: sk-admin   Source File: PictureServiceImpl.java    License: 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 15
Source Project: spring-boot-demo   Source File: Neo4jTest.java    License: 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 16
Source Project: mall-swarm   Source File: WebLogAspect.java    License: Apache License 2.0 5 votes vote down vote up
@Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息(通过Logstash传入Elasticsearch)
        WebLog webLog = new WebLog();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation log = method.getAnnotation(ApiOperation.class);
            webLog.setDescription(log.value());
        }
        long endTime = System.currentTimeMillis();
        String urlStr = request.getRequestURL().toString();
        webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        webLog.setIp(request.getRemoteUser());
        webLog.setMethod(request.getMethod());
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
        webLog.setResult(result);
        webLog.setSpendTime((int) (endTime - startTime));
        webLog.setStartTime(startTime);
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(request.getRequestURL().toString());
        Map<String,Object> logMap = new HashMap<>();
        logMap.put("url",webLog.getUrl());
        logMap.put("method",webLog.getMethod());
        logMap.put("parameter",webLog.getParameter());
        logMap.put("spendTime",webLog.getSpendTime());
        logMap.put("description",webLog.getDescription());
//        LOGGER.info("{}", JSONUtil.parse(webLog));
        LOGGER.info(Markers.appendEntries(logMap), JSONUtil.parse(webLog).toString());
        return result;
    }
 
Example 17
Source Project: spring-boot-demo   Source File: Neo4jTest.java    License: MIT License 5 votes vote down vote up
/**
 * 测试根据课程查询同学关系
 */
@Test
public void testFindClassmates() {
    Map<String, List<Student>> classmates = neoService.findClassmatesGroupByLesson();
    classmates.forEach((k, v) -> log.info("因为一起上了【{}】这门课,成为同学关系的有:{}", k, JSONUtil.toJsonStr(v.stream()
            .map(Student::getName)
            .collect(Collectors.toList()))));
}
 
Example 18
@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 19
Source Project: spring-boot-demo   Source File: ArticleRepositoryTest.java    License: MIT License 5 votes vote down vote up
/**
 * 测试新增列表
 */
@Test
public void testSaveList() {
    List<Article> articles = Lists.newArrayList();
    for (int i = 0; i < 10; i++) {
        articles.add(new Article(snowflake.nextId(), RandomUtil.randomString(20), RandomUtil.randomString(150), DateUtil
                .date(), DateUtil.date(), 0L, 0L));
    }
    articleRepo.saveAll(articles);

    log.info("【articles】= {}", JSONUtil.toJsonStr(articles.stream()
            .map(Article::getId)
            .collect(Collectors.toList())));
}
 
Example 20
Source Project: SubTitleSearcher   Source File: ApiController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 查询字幕
 */
public void zimu_list() {
	HttpRequest request = getRequest();
	HttpResponse response = getResponse();
	String data = request.getParaToStr("data");
	if(data == null) {
		outJsonpMessage(request,response, 1, "请求数据错误");
		return;
	}
	
	JSONObject dataJson = JSONUtil.parseObj(data);
	
	
	SearchParm searchParm = new SearchParm();
	searchParm.from_sheshou = dataJson.getJSONObject("searchParm").getBool("from_sheshou");
	searchParm.from_subhd = dataJson.getJSONObject("searchParm").getBool("from_subhd");
	searchParm.from_xunlei = dataJson.getJSONObject("searchParm").getBool("from_xunlei");
	searchParm.from_zimuku = dataJson.getJSONObject("searchParm").getBool("from_zimuku");
	try {
		DownZIMu.searchList(searchParm);
		System.out.println(DownZIMu.dataArr);
	}catch(Exception e) {
		logger.error(e);
		outJsonpMessage(request,response, 1, "查询出错");
		return;
	}
	
	JSONObject resp = new JSONObject();
	resp.put("list", DownZIMu.dataArr);
	outJsonpMessage(request,response, 0, "OK", resp);
}
 
Example 21
Source Project: cms   Source File: OauthController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("/{type}/callback")
public void login(@PathVariable String type, String redirect, AuthCallback callback, HttpServletResponse response) throws IOException {
    AuthRequest authRequest = factory.get(type);
    AuthResponse authResponse = authRequest.login(callback);
    log.info("【response】= {}", JSONUtil.toJsonStr(authResponse));
    response.sendRedirect(redirect);
}
 
Example 22
Source Project: SubTitleSearcher   Source File: WinRarUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	binPath = "E:\\workspace\\_me\\dev\\my_libs\\test_lib\\data\\file\\archive\\UnRAR.exe";

	String srcData = "E:\\workspace\\_me\\dev\\my_libs\\test_lib\\data\\file\\archive\\test2.rar";
	byte[] data = MyFileUtil.fileReadBin(srcData);
	String objPath = "E:\\workspace\\_me\\dev\\my_libs\\test_lib\\data\\file\\archive\\"+System.currentTimeMillis();
	String extName = "rar";
	List<File> result = unRar(extName, data, objPath);
	
	System.out.println(JSONUtil.toJsonPrettyStr(result));
	clear(objPath);
}
 
Example 23
Source Project: SubTitleSearcher   Source File: XunLeiCommon.java    License: Apache License 2.0 5 votes vote down vote up
public static JSONArray DownList(String fileName) throws Exception {
	String cid = getCid(fileName);
	String result = HtHttpUtil.http.get(String.format("http://sub.xmp.sandai.net:8000/subxl/%s.json", cid));
	if(result == null) {
		logger.error("未查询到结果");
		return null;
	}
	//System.out.println(result);
	JSONObject json = JSONUtil.parseObj(result);
	return json.getJSONArray("sublist");
}
 
Example 24
Source Project: SubTitleSearcher   Source File: UpgradeCommon.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 判断是否有新版
 * @return
 */
public static boolean checkNewVersion() {
	String url = AppConfig.upgradeUrl;
	String str = HtHttpUtil.http.get(url);
	logger.info(str);
	data = JSONUtil.parseObj(str);
	if(data==null) {
		logger.error("未发现新版");
		return false;
	}
	//System.out.println(data);
	return compareVersion(data.getStr("version"), AppConfig.appVer) > 0;
}
 
Example 25
Source Project: yshopmall   Source File: YxArticleServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private WxMpMaterialUploadResult uploadPhotoToWx(WxMpService wxMpService, String picPath) throws WxErrorException {
    WxMpMaterial wxMpMaterial = new WxMpMaterial();

    String filename = String.valueOf( (int)System.currentTimeMillis() ) + ".png";
    String downloadPath = uploadDirStr + filename;
    long size = HttpUtil.downloadFile(picPath, cn.hutool.core.io.FileUtil.file(downloadPath));
    picPath = downloadPath;
    File picFile = new File( picPath );
    wxMpMaterial.setFile( picFile );
    wxMpMaterial.setName( picFile.getName() );
    log.info( "picFile name : {}", picFile.getName() );
    WxMpMaterialUploadResult wxMpMaterialUploadResult = wxMpService.getMaterialService().materialFileUpload( WxConsts.MediaFileType.IMAGE, wxMpMaterial );
    log.info( "wxMpMaterialUploadResult : {}", JSONUtil.toJsonStr( wxMpMaterialUploadResult ) );
    return wxMpMaterialUploadResult;
}
 
Example 26
Source Project: SubTitleSearcher   Source File: SubHDCommon.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 下载字幕
 * @param url
 * @return
 */
public static JSONObject downContent(String url) {
	String result = HtHttpUtil.http.get(baseUrl+url, HtHttpUtil.http.default_charset, HtHttpUtil.http._ua, baseUrl+url);
	Document doc = Jsoup.parse(result);
	Elements matchList = doc.select("#down");
	if(matchList.size() == 0)return null;
	Element down = matchList.get(0);
	Map<String, Object> postData = new HashMap<String, Object>();
	postData.put("sub_id", matchList.attr("sid"));
	postData.put("dtoken", down.attr("dtoken"));
	result = HtHttpUtil.http.post(baseUrl+"/ajax/down_ajax", postData);
	if(result == null || !result.contains("}"))return null;
	JSONObject resultJson = JSONUtil.parseObj(result);
	if(resultJson == null || !resultJson.getBool("success"))return null;
	String downUrl = resultJson.getStr("url");
	String filename = StringUtil.basename(downUrl);
	//HtHttpUtil.http.debug=true;
	byte[] data = HtHttpUtil.http.getBytes(downUrl, HtHttpUtil.http._ua, baseUrl+url);
	
	JSONObject resp = new JSONObject();
	resp.put("filename", filename);
	resp.put("ext", StringUtil.extName(filename).toLowerCase());
	resp.put("data", Base64.encode(data));

	
	return resp;
}
 
Example 27
Source Project: mall-tiny   Source File: RestfulAccessDeniedHandler.java    License: 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 28
Source Project: mall-tiny   Source File: WebLogAspect.java    License: Apache License 2.0 5 votes vote down vote up
@Around("webLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    long startTime = System.currentTimeMillis();
    //获取当前请求对象
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    //记录请求信息
    WebLog webLog = new WebLog();
    Object result = joinPoint.proceed();
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    if (method.isAnnotationPresent(ApiOperation.class)) {
        ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
        webLog.setDescription(apiOperation.value());
    }
    long endTime = System.currentTimeMillis();
    String urlStr = request.getRequestURL().toString();
    webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
    webLog.setIp(request.getRemoteUser());
    webLog.setMethod(request.getMethod());
    webLog.setParameter(getParameter(method, joinPoint.getArgs()));
    webLog.setResult(result);
    webLog.setSpendTime((int) (endTime - startTime));
    webLog.setStartTime(startTime);
    webLog.setUri(request.getRequestURI());
    webLog.setUrl(request.getRequestURL().toString());
    LOGGER.info("{}", JSONUtil.parse(webLog));
    return result;
}
 
Example 29
Source Project: HIS   Source File: RestAuthenticationEntryPoint.java    License: 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 30
Source Project: HIS   Source File: RestfulAccessDeniedHandler.java    License: 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();
}