下面列出了org.apache.log4j.spi.ErrorCode#com.alibaba.fastjson.JSON 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 级联选择数据
*/
@RequestMapping("/ajax-select-chained")
public void ajaxAdd(HttpServletResponse response) throws IOException {
boolean result = false;
String message = "";
Map<String, String> data = Maps.newHashMap();
data.put("", "--");
data.put("series-1", "1 series");
data.put("series-2", "2 series");
data.put("series-3", "3 series");
data.put("series-4", "4 series");
data.put("selected", "series-3");
JsonUtils.setResponse(response);
response.getWriter().print(JSON.toJSONString(data));
}
static String uploadStream(InputStream is, String fileName) {
UploadManager uploadManager = UploadConfiguration.getUploadManager();
try {
String key = SysConfigMap.get(SysConfigKeys.QINIU_BUCKET) + '/' + DateUtils.format(LocalDateTime.now(), DateUtils.NORM_DATE_PATTERN) + "/" + fileName;
Response response = uploadManager.put(is, key, UploadConfiguration.getToken(), null, null);
if (response.isOK()) {
DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
return putRet.key;
}
} catch (QiniuException e) {
throw new RuntimeException("上传文件失败");
}
return null;
}
/**
* 同步执行HTTP请求
*
* @param
* @return org.springframework.http.ResponseEntity<java.lang.String>
* @throws IOException
* @author wliduo[[email protected]]
* @date 2019/8/8 17:15
*/
@GetMapping("/es")
public ResponseBean getEsInfo() throws IOException {
Request request = new Request("GET", "/");
// performRequest是同步的,将阻塞调用线程并在请求成功时返回Response,如果失败则抛出异常
Response response = restClient.performRequest(request);
// 获取请求行
RequestLine requestLine = response.getRequestLine();
// 获取host
HttpHost host = response.getHost();
// 获取状态码
int statusCode = response.getStatusLine().getStatusCode();
// 获取响应头
Header[] headers = response.getHeaders();
// 获取响应体
String responseBody = EntityUtils.toString(response.getEntity());
return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody));
}
@Override
public void synchronize() {
//链式构建请求
String result = HttpRequest.get(ElAdminConstant.Url.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(!pictureRepository.existsByUrl(picture.getUrl())){
picture.setSize(FileUtil.getSize(Integer.parseInt(picture.getSize())));
picture.setUsername("System Sync");
picture.setMd5Code(null);
pictureRepository.save(picture);
}
}
}
/**
* 获得SqlAndParams配置文件信息
*
* @return
* @throws Exception
*/
public static CustomPropertyConfig getCustomPropertyConfig(String name) throws Exception {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
conn = getConnection();
stat = conn.createStatement();
String sql = String.format("select * from CustomPropertyConfig where name='%s'", name);
ResultSet resultSet = stat.executeQuery(sql);
while (resultSet.next()) {
CustomPropertyConfig result = JSON.parseObject(resultSet.getString("value"), CustomPropertyConfig.class);
return result;
}
} finally {
if (rs != null)
rs.close();
if (stat != null)
stat.close();
if (conn != null)
conn.close();
}
return null;
}
private static Set<String> getRegisteredApps() {
if (AVOSCloud.applicationContext == null) {
return null;
}
File registerFile = getRegisterAppsFile();
Set<String> appSet = new HashSet<String>();
if (registerFile.exists()) {
String registerApps = AVPersistenceUtils.sharedInstance().readContentFromFile(registerFile);
if (!StringUtil.isEmpty(registerApps)) {
// catch parse Exception
try {
appSet.addAll(JSON.parseObject(registerApps, Set.class));
} catch (Exception e) {
if (AVOSCloud.showInternalDebugLog()) {
Log.e(TAG, "getRegisteredApps", e);
}
}
return appSet;
}
}
return appSet;
}
@Test
public void testRowsChainRelative() {
// |月份 | 产品 |交易笔数 | 环比 | 金额 | 环比 | 收入 | 环比 |
// | 5月 | 香蕉 | 2000 | 环比 | 金额 | 环比 | 收入 | 环比 |
// | 5月 | 苹果 | 2000 | 环比 | 金额 | 环比 | 收入 | 环比 |
// | 4月 | 香蕉 | 2000 | 环比 | 金额 | 环比 | 收入 | 环比 |0
// | 4月 | 苹果 | 2000 | 环比 | 金额 | 环比 | 收入 | 环比 |1
// | 3月 | 香蕉 | 2000 | 环比 | 金额 | 环比 | 收入 | 环比 |
// | 3月 | 苹果 | 2000 | 环比 | 金额 | 环比 | 收入 | 环比 |
Object[][] values = { { "5月", "香蕉", 2000 }, { "5月", "苹果", 1900 }, { "4月", "香蕉", 1800 }, { "4月", "苹果", 1800 },
{ "3月", "香蕉", 1600 }, { "3月", "苹果", 1700 } };
List result = CollectionUtil.arrayToDeepList(values);
RowsChainRelativeModel rowsRelative = new RowsChainRelativeModel();
rowsRelative.setGroupColumn("1");
rowsRelative.setReduceOne(false);
rowsRelative.setRelativeColumns(new String[] { "2" });
rowsRelative.setFormat("#.00%");
rowsRelative.setReverse(true);
HashMap<String, Integer> labelIndexMap = new HashMap<String, Integer>();
RowsChainRelative.process(rowsRelative, labelIndexMap, result);
for (int i = 0; i < result.size(); i++) {
System.out.println(JSON.toJSONString(result.get(i)));
}
}
@Test
@SuppressWarnings("unchecked")
public void methodMap() throws Exception {
JsonRequest request = new JsonRequest();
request.setRid(1);
ServiceManager manager = AppContext.getBean(ServiceManager.class);
manager.registerService(new DemoComponent());
// list
request.setData(JSON.toJSONString(new HashMap<Integer, Integer>() {{
put(1, 1);
put(2, 2);
}}));
manager.getCommand("methodMapBase").execute(null, request);
// list
request.setData(JSON.toJSONString(new HashMap<Integer, VoObj>() {{
put(1, new VoObj(100));
put(2, new VoObj(101));
}}));
manager.getCommand("methodMapObject").execute(null, request);
}
@Test
public void test() {
JSONObject auth = new JSONObject();
auth.put("personnel", Maps.buildMap()
.put("id", "1234")
.put("name", "234")
.get());
auth.put("orgIds", JSON.parseArray("[{\"value\":\"123\",\"children\":[{\"value\":\"234\"}]}]"));
auth.put("positions", JSON.parseArray("[{\"id\":\"1234\"," +
"\"department\":{\"id\":\"1234\",\"org\":{\"id\":\"234\",\"district\":{\"id\":\"test\"}}}}]"));
SimplePersonnelAuthentication authorization = fromJson(auth.toJSONString());
Object json = JSON.toJSON(authorization);
System.out.println(JSON.toJSONString(json, SerializerFeature.PrettyFormat));
System.out.println(JSON.toJSONString(FastBeanCopier.copy(authorization,new JSONObject())).equals(json.toString()));
}
@RequestMapping("/list")
@ResponseBody
public String list(@ModelAttribute MchNotify mchNotify, Integer pageIndex, Integer pageSize) {
PageModel pageModel = new PageModel();
int count = mchNotifyService.count(mchNotify);
if(count <= 0) return JSON.toJSONString(pageModel);
List<MchNotify> mchNotifyList = mchNotifyService.getMchNotifyList((pageIndex-1)*pageSize, pageSize, mchNotify);
if(!CollectionUtils.isEmpty(mchNotifyList)) {
JSONArray array = new JSONArray();
for(MchNotify po : mchNotifyList) {
JSONObject object = (JSONObject) JSONObject.toJSON(po);
if(po.getCreateTime() != null) object.put("createTime", DateUtil.date2Str(po.getCreateTime()));
if(po.getLastNotifyTime() != null) object.put("lastNotifyTime", DateUtil.date2Str(po.getLastNotifyTime()));
array.add(object);
}
pageModel.setList(array);
}
pageModel.setCount(count);
pageModel.setMsg("ok");
pageModel.setRel(true);
return JSON.toJSONString(pageModel);
}
/**
* 查询是否关注某个贴吧
* @param tbName 贴吧名称
* @param bduss bduss
* @return true or false
*/
public Boolean isFocus(String tbName, String bduss) {
HttpKit hk = HttpKit.getInstance();
Boolean flag = false;
try {
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("BDUSS", bduss));
list.add(new BasicNameValuePair("fid", api.getFid(tbName)));
list.add(new BasicNameValuePair("kw", tbName));
list.add(new BasicNameValuePair("tbs", api.getTbs(bduss)));
list.add(new BasicNameValuePair("sign", StrKit.md5Sign(list)));
HttpResponse response = hk.execute(Constants.LIKE_TIEBA_URL, null, list);
String fr = EntityUtils.toString(response.getEntity());
Integer isLike = (Integer)JSONPath.eval(JSON.parse(fr), "$.info.is_like");
if(isLike == 1) {
flag = true;
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
if(flag == false) {
//查询结果后如果未关注,需要取消关注
this.unfocus(bduss, tbName);
}
return flag;
}
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, Object o, Exception e) {
LOGGER.error("rest error:", e);
ModelAndView modelAndView = new ModelAndView();
try {
ResultInfo resultInfo = new ResultInfo().setStatus(ResultStatus.ERROR.getCode())
.setMsg(ResultInfo.MSG_ERROR);
Map<String, Object> attr = JSON.parseObject(JSON.toJSONString(resultInfo), Map.class);
MappingJackson2JsonView view = new MappingJackson2JsonView();
view.setAttributesMap(attr);
modelAndView.setView(view);
} catch (Exception e1) {
e1.printStackTrace();
}
return modelAndView;
}
private List<BoardCategory> loadPreloadBoards() {
String categoryJson = StringUtils.getStringFromAssets("json/category_old.json");
List<BoardBean> beans = JSON.parseArray(categoryJson, BoardBean.class);
List<BoardCategory> categories = new ArrayList<>();
for (BoardBean categoryBean : beans) {
BoardCategory category = new BoardCategory(categoryBean.name);
for (BoardBean.ContentBean contentBean : categoryBean.content) {
if (TextUtils.isEmpty(contentBean.nameS)) {
category.addBoard(new Board(contentBean.fid, contentBean.stid, contentBean.name));
} else {
category.addBoard(new Board(contentBean.fid, contentBean.stid, contentBean.nameS));
}
}
categories.add(category);
}
return categories;
}
@Test
public void invokeSayHello(){
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/net.dubboclub.restful.api.FirstRestfulService1/sayHello/1.0.1/all");
Map<String,String> requestEntity = new HashMap<String,String>();
requestEntity.put("arg1","Bieber");
HttpEntity httpEntity = new ByteArrayEntity(JSON.toJSONBytes(requestEntity));
httpPost.setEntity(httpEntity);
try {
CloseableHttpResponse response = httpclient.execute(httpPost);
System.out.println(response.getStatusLine());
HttpEntity entity2 = response.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
System.out.println(EntityUtils.toString(entity2));
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String randomKey = "1xm7hw";
BaseTransferEntity baseTransferEntity = new BaseTransferEntity();
SimpleObject simpleObject = new SimpleObject();
simpleObject.setUser("fsn");
baseTransferEntity.setObject("123123");
String json = JSON.toJSONString(simpleObject);
//md5签名
String encrypt = MD5Util.encrypt(json + randomKey);
baseTransferEntity.setSign(encrypt);
System.out.println(JSON.toJSONString(baseTransferEntity));
}
/**
* 解析单个精度
* @param result 请求结果
* @param symbol 解析币对
* @return 精度
*/
public static Precision parsePrecision(String result, String symbol) {
JSONObject r = JSON.parseObject(result);
if (OK.equals(r.getString(STATUS))) {
JSONArray data = r.getJSONArray(DATA);
for (int i = 0; i < data.size(); i++) {
JSONObject t = data.getJSONObject(i);
if (symbol.equalsIgnoreCase(t.getString("symbol"))) {
symbol = t.getString("base-currency") + "_" + t.getString("quote-currency");
symbol = symbol.toUpperCase();
Integer base = t.getInteger("amount-precision");
Integer count = t.getInteger("price-precision");
return new Precision(data.getString(i), symbol,
base, count,
null, null,
null, null,
null, null);
}
}
}
return null;
}
/**
* 新增用户
*
* @throws Exception
*/
@Test
public void test_user_3_add() throws Exception {
AddUserRequestBody body = new AddUserRequestBody();
body.setAccount("sctang");
body.setEmail("[email protected]");
body.setPhone("13739263609");
body.setUserName("sctang");
String result = this.mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/user/add")
.content(JSON.toJSONString(body))
.contentType(MediaType.APPLICATION_JSON)
.session((MockHttpSession) Utils.getLoginSession(this.mockMvc))
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn().getResponse().getContentAsString();
Utils.assertResult(result);
}
@Test(priority = 1)
public void testApplyStaff() throws IOException {
ApplyStaffInfo info = new ApplyStaffInfo();
info.setFromPage("http://163.com");
info.setFromTitle("网易首页");
info.setUid(foreignId);
info.setProductId("com.163");
info.setDeviceType("Web#Windows#10#Chrome");
info.setStaffType(1);
ApplyStaffResult result = client.applyStaff(info);
if (result.getCode() == 200 && result.getSession().getStaffType() == 1) {
sessionId = result.getSession().getSessionId();
}
out("applyStaff", JSON.toJSONString(result));
}
private void testOkHttpPost() throws Exception {
PostBody postBody = new PostBody();
postBody.setAge(111);
postBody.setFemale(false);
postBody.setName("guanchao.ygc/xuelian");
String httpGetUrl = urlHttpPrefix + "/httpclient";
//baggage
SofaTracer sofaTracer = OkHttpTracer.getOkHttpTracerSingleton().getSofaTracer();
SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
SofaTracerSpan sofaTracerSpan = (SofaTracerSpan) sofaTracer.buildSpan(
"HttpClientTracer Baggage").start();
sofaTracerSpan.setBaggageItem("key1", "baggage1");
sofaTracerSpan.setBaggageItem("key2", "baggage2");
sofaTraceContext.push(sofaTracerSpan);
String responseStr = new OkHttpClientInstance().executePost(httpGetUrl,
JSON.toJSONString(postBody));
PostBody resultPostBody = JSON.parseObject(responseStr, PostBody.class);
assertEquals(postBody, resultPostBody);
}
private static AgentArgs convert(String agentArgs){
JSONObject jsonObject = JSON.parseObject(agentArgs);
AgentArgs model = new AgentArgs();
model.setClassName(jsonObject.getString("className"));
model.setMethodName(jsonObject.getString("methodName"));
model.setTranslateType(TranslateType.valueOf(jsonObject.getString("translateType")));
return model;
}
public GitHubAccessToken getAccessToken(String code,String redirect_uri) throws Exception{
String oschinaAuthUrl = "https://gitee.com/oauth/token";
Map<String,String> params = Tools.getStrMap("grant_type", "authorization_code", "client_id", Config.oschinaClientID,
"client_secret", Config.oschinaClientSecret,"code", code,"redirect_uri", redirect_uri);
String rs = HttpPostGet.post(oschinaAuthUrl, params, Tools.getStrMap("Accept","application/json"), 6000);
System.out.println(rs);
GitHubAccessToken accessToken = JSON.parseObject(rs, GitHubAccessToken.class);
if(accessToken == null || accessToken.getAccess_token() == null) {
throw new MyException(MyError.E000026);
}
return accessToken;
}
@Override
public ConfigEntry clone() {
ConfigEntry c = new ConfigEntry();
for (Map.Entry<String, Object> e : this.entryMap.entrySet()) {
Object v = e.getValue();
if (v instanceof JSON) {
v = JSONUtils.clone((JSON) v);
}
c.set(e.getKey(), v);
}
return c;
}
/**
* 初始化支付宝配置
* @param configParam
* @return
*/
public AlipayConfig init(String configParam) {
Assert.notNull(configParam, "init alipay config error");
JSONObject paramObj = JSON.parseObject(configParam);
this.setApp_id(paramObj.getString("appid"));
this.setRsa_private_key(paramObj.getString("private_key"));
this.setAlipay_public_key(paramObj.getString("alipay_public_key"));
this.setIsSandbox(paramObj.getShortValue("isSandbox"));
if(this.getIsSandbox() == 1) this.setUrl("https://openapi.alipaydev.com/gateway.do");
return this;
}
public String queryTokenByID(String tokenID) throws Exception {
if (contractAddress == null) {
throw new SDKException(ErrorCode.NullCodeHash);
}
AbiInfo abiinfo = JSON.parseObject(oep5abi, AbiInfo.class);
AbiFunction func = abiinfo.getFunction("queryTokenByID");
func.setParamsValue(tokenID);
Object obj = sdk.neovm().sendTransaction(Helper.reverse(contractAddress),null,null,0,0,func, true);
return ((JSONObject) obj).getString("Result");
}
@RequiresPermissions("sys:gen:update")
@PostMapping("/update.do")
public ResponeModel update(@Validated @RequestBody SysGen sysGen, BindingResult bindingResult) {
List<GenColumnInfo> columnInfos = sysGen.getColumnInfos();
Collections.sort(columnInfos);
sysGen.setColumns(JSON.toJSONString(columnInfos));
int cnt = sysGenService.updateSelective(sysGen);
return ResponeModel.ok(cnt);
}
public X8BaseCamJsonData setVideoResolution(String param) {
String sendString = JSON.toJSONString(createBaseCmd(2, param, "video_resolution"));
X8BaseCamJsonData baseCamJsonData = new X8BaseCamJsonData();
baseCamJsonData.setAddToSendQueue(false);
baseCamJsonData.setOutTime(1000);
baseCamJsonData.setMsgId(2);
baseCamJsonData.setCamKey("video_resolution");
baseCamJsonData.setPayLoad(sendString.getBytes());
baseCamJsonData.packCmd();
return baseCamJsonData;
}
@Override
public String saveLastestSearch(String projectName) {
SearchCondition searchCondition = new SearchCondition();
searchCondition.setProject(projectName);
String condition = JSON.toJSONString(searchCondition);
String url = this.getRequestURI();
//同步搜索条件
this.lastestSearchConditionImpl.syncSearchCondition(url, condition);
return condition;
}
@JavascriptInterface
public String onRefresh() {
List<MapConfigBean> list = LitePal
.findAll(MapConfigBean.class);
List<String> name = new ArrayList<>();
for (MapConfigBean bean : list) {
name.add(bean.name);
}
return JSON.toJSONString(name);
}
/**
* create by: cjl
* description:
* 获取商品类别树数据
* create time: 2019/2/19 11:49
* @Param:
* @return com.alibaba.fastjson.JSONArray
*/
@RequestMapping(value = "/getMaterialCategoryTree")
public JSONArray getMaterialCategoryTree(@RequestParam("id") Long id) throws Exception{
JSONArray arr=new JSONArray();
List<TreeNode> materialCategoryTree = materialCategoryService.getMaterialCategoryTree(id);
if(materialCategoryTree!=null&&materialCategoryTree.size()>0){
for(TreeNode node:materialCategoryTree){
String str=JSON.toJSONString(node);
JSONObject obj=JSON.parseObject(str);
arr.add(obj) ;
}
}
return arr;
}
/**
* 构建并下载zip文件.仅支持POST请求
*
* @param name 文件名
* @param dataStr 数据,jsonArray. 格式:[{"name":"fileName","text":"fileText"}]
* @param response {@link HttpServletResponse}
* @throws IOException 写出zip文件错误
* @throws RuntimeException 构建zip文件错误
*/
@RequestMapping(value = "/download-zip/{name:.+}", method = {RequestMethod.POST})
@ApiOperation("构建zip文件并下载")
@Authorize(action = "download", description = "下载文件")
public void downloadZip(@ApiParam("zip文件名") @PathVariable("name") String name,
@ApiParam(value = "zip文件内容", example = "[" +
"{\"name\":\"textFile.txt\",\"text\":\"fileText\"}," +
"{\"name\":\"uploadedFile.png\",\"file\":\"fileId or file md5\"}" +
"{\"name\":\"base64File.text\",\"base64\":\"aGVsbG8=\"}" +
"]") @RequestParam("data") String dataStr,
HttpServletResponse response) throws IOException {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));
ZIPWriter writer = Compress.zip();
List<Map<String, String>> data = (List) JSON.parseArray(dataStr, Map.class);
data.forEach(map -> {
String entryName = map.get("name");
String text = map.get("text");
String file = map.get("file");
String fileBase64 = map.get("base64");
if (text != null) {
writer.addTextFile(map.get("name"), text);
} else if (file != null) {
writer.addFile(entryName, fileService.readFile(file));
} else if (fileBase64 != null) {
writer.addFile(entryName, new ByteArrayInputStream(Base64.decodeBase64(fileBase64)));
}
});
writer.write(response.getOutputStream());
}