Java Code Examples for com.alibaba.fastjson.JSONObject

The following are top voted examples for showing how to use com.alibaba.fastjson.JSONObject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: tasfe-framework   File: LogConfigFactory.java   Source Code and License 7 votes vote down vote up
public static LogcenterConfig createConfig(JSONObject jsonInput) throws LogConsumerException {
    String productLine = String.valueOf(jsonInput.get("productLine"));
    String appName = String.valueOf(jsonInput.get("appName"));
    QueryBuilder qb = QueryBuilders.queryStringQuery("productLine:'" + productLine + "' AND appName:'" + appName + "'");
    SearchResponse response = ElasticsearchClient.getClient()
            .prepareSearch(Constants.METADATA_INDEX)
            .setTypes(Constants.METADATA_TYPE)
            .setQuery(qb)
            .get();
    JSONObject jsonObject = JSON.parseObject(response.toString());
    JSONArray hitArray = (JSONArray) jsonObject.getJSONObject("hits").get("hits");
    if (hitArray.size() == 0) {
        throw new LogConsumerException("index does not exist,please check the configuration of the .logcenter index");
    }
    JSONObject document = (JSONObject) hitArray.get(0);
    String jsonStr = document.get("_source").toString();

    return JSONObject.parseObject(jsonStr, LogcenterConfig.class);
}
 
Example 2
Project: iBase4J-Common   File: WeiXinCompanyOAuth.java   Source Code and License 6 votes vote down vote up
public static String getUserInfo(String code, int agentid) {
		String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+WeiXinCompanyUtils.getToken()+
//				"&code="+code+"&agentid="+CommonUtils.WX_QY_AGENT_TEST;
				"&code="+code+"&agentid="+agentid;
		try {
			URL url = new URL(urlStr);
			HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();

			conn.setDoInput(true);

			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String s = null;
			StringBuilder sb = new StringBuilder();
			while ((s=reader.readLine()) != null) {
				sb.append(s);
			}
			JSONObject jsonObject = JSON.parseObject(sb.toString());
			if(jsonObject.get("UserId") !=null){
				return jsonObject.get("UserId").toString();
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
 
Example 3
Project: pay-xxpay-master   File: PayChannelServiceController.java   Source Code and License 6 votes vote down vote up
@RequestMapping(value = "/pay_channel/select")
public String selectPayChannel(@RequestParam String jsonParam) {
    // TODO 参数校验
    _log.info("selectPayChannel << {}", jsonParam);
    JSONObject retObj = new JSONObject();
    retObj.put("code", "0000");
    if(StringUtils.isBlank(jsonParam)) {
        retObj.put("code", "0001"); // 参数错误
        retObj.put("msg", "缺少参数");
        return retObj.toJSONString();
    }
    JSONObject paramObj = JSON.parseObject(new String(MyBase64.decode(jsonParam)));
    String channelId = paramObj.getString("channelId");
    String mchId = paramObj.getString("mchId");
    PayChannel payChannel = payChannelService.selectPayChannel(channelId, mchId);
    if(payChannel == null) {
        retObj.put("code", "0002");
        retObj.put("msg", "数据对象不存在");
        return retObj.toJSONString();
    }
    retObj.put("result", JSON.toJSON(payChannel));
    _log.info("selectPayChannel >> {}", retObj);
    return retObj.toJSONString();
}
 
Example 4
Project: HiTSDB-Client   File: HiTSDBClient.java   Source Code and License 6 votes vote down vote up
@Override
public List<LastDPValue> lastdp(Collection<Timeline> timelines) throws HttpUnknowStatusException {
	Object timelinesJSON = JSON.toJSON(timelines);
	JSONObject obj = new JSONObject();
	obj.put("queries", timelinesJSON);
	String jsonString = obj.toJSONString();
	HttpResponse httpResponse = httpclient.post(HttpAPI.QUERY_LASTDP, jsonString);
	ResultResponse resultResponse = ResultResponse.simplify(httpResponse, this.httpCompress);
	HttpStatus httpStatus = resultResponse.getHttpStatus();
	switch (httpStatus) {
	case ServerSuccessNoContent:
		return null;
	case ServerSuccess:
		String content = resultResponse.getContent();
		List<LastDPValue> queryResultList = JSON.parseArray(content, LastDPValue.class);
		return queryResultList;
	case ServerNotSupport:
		throw new HttpServerNotSupportException(resultResponse);
	case ServerError:
		throw new HttpServerErrorException(resultResponse);
	default:
		throw new HttpUnknowStatusException(resultResponse);
	}
}
 
Example 5
Project: database-transform-tool   File: ElasticsearchTransportFactory.java   Source Code and License 6 votes vote down vote up
public String bulkUpsert(String index,String type,List<Object> jsons){
	try {
		if(client==null){
			init();
		}
		BulkRequestBuilder bulkRequest = client.prepareBulk();
		for (Object json : jsons) {
			JSONObject obj = JSON.parseObject(JSON.toJSONString(json));
			String id = UUIDs.base64UUID();
			if(obj.containsKey("id")){
				id = obj.getString("id");
				obj.remove("id");
				bulkRequest.add(client.prepareUpdate(index, type, id).setDoc(obj.toJSONString(),XContentType.JSON));
			}else{
				bulkRequest.add(client.prepareIndex(index, type, id).setSource(obj.toJSONString(),XContentType.JSON));
			}
		}
		BulkResponse result = bulkRequest.execute().get();
		return result.toString();
	}catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
Example 6
Project: pay-xxpay-master   File: PayOrderController.java   Source Code and License 6 votes vote down vote up
@RequestMapping("/view.html")
public String viewInput(String payOrderId, ModelMap model) {
    PayOrder item = null;
    if(StringUtils.isNotBlank(payOrderId)) {
        item = payOrderService.selectPayOrder(payOrderId);
    }
    if(item == null) {
        item = new PayOrder();
        model.put("item", item);
        return "pay_order/view";
    }
    JSONObject object = (JSONObject) JSON.toJSON(item);
    if(item.getPaySuccTime() != null) object.put("paySuccTime", DateUtil.date2Str(new Date(item.getPaySuccTime())));
    if(item.getLastNotifyTime() != null) object.put("lastNotifyTime", DateUtil.date2Str(new Date(item.getLastNotifyTime())));
    if(item.getExpireTime() != null) object.put("expireTime", DateUtil.date2Str(new Date(item.getExpireTime())));
    if(item.getAmount() != null) object.put("amount", AmountUtil.convertCent2Dollar(item.getAmount()+""));
    model.put("item", object);
    return "pay_order/view";
}
 
Example 7
Project: pay-xxpay-master   File: PayOrderServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Map createPayOrder(String jsonParam) {
    BaseParam baseParam = JsonUtil.getObjectFromJson(jsonParam, BaseParam.class);
    Map<String, Object> bizParamMap = baseParam.getBizParamMap();
    if (ObjectValidUtil.isInvalid(bizParamMap)) {
        _log.warn("新增支付订单失败, {}. jsonParam={}", RetEnum.RET_PARAM_NOT_FOUND.getMessage(), jsonParam);
        return RpcUtil.createFailResult(baseParam, RetEnum.RET_PARAM_NOT_FOUND);
    }
    JSONObject payOrderObj = baseParam.isNullValue("payOrder") ? null : JSONObject.parseObject(bizParamMap.get("payOrder").toString());
    if(payOrderObj == null) {
        _log.warn("新增支付订单失败, {}. jsonParam={}", RetEnum.RET_PARAM_INVALID.getMessage(), jsonParam);
        return RpcUtil.createFailResult(baseParam, RetEnum.RET_PARAM_INVALID);
    }
    PayOrder payOrder = BeanConvertUtils.map2Bean(payOrderObj, PayOrder.class);
    if(payOrder == null) {
        _log.warn("新增支付订单失败, {}. jsonParam={}", RetEnum.RET_PARAM_INVALID.getMessage(), jsonParam);
        return RpcUtil.createFailResult(baseParam, RetEnum.RET_PARAM_INVALID);
    }
    int result = super.baseCreatePayOrder(payOrder);
    return RpcUtil.createBizResult(baseParam, result);
}
 
Example 8
Project: telemarket-skittle-alley   File: ReadyHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void apply(ApiRequest request, ApiResponse response, WebSocketSession session) {
    DrawGuessContext ctx = (DrawGuessContext) session.getAttributes().get("ctx");
    JSONObject obj = JSONObject.parseObject(request.getMsg());
    boolean ready = obj.getBooleanValue(STATUS_NAME);
    String id = obj.getString(ID_NAME);
    DrawPlayerInfo info = ((DrawPlayerInfo) session.getAttributes().get("info"));
    if (ctx.status() != DrawGameStatus.READY) {
        return;
    }
    if (ready && info.status() == DrawUserStatus.WAIT) {
        info.setStatus(DrawUserStatus.READY);
        ctx.addPlayer(info);
    } else if (!ready && info.status() == DrawUserStatus.READY) {
        info.setStatus(DrawUserStatus.WAIT);
        ctx.removePlayer(id);
    }
    response.setCode(DrawCode.USER_READY.getCode()).setData(info);
}
 
Example 9
Project: uavstack   File: DefaultLogFilterAndRule.java   Source Code and License 6 votes vote down vote up
/**
 * 构造默认的日志规则
 * 
 * @param filterregex
 *            日志过滤规则的正则表达式
 * @param separator
 *            日志字段分隔符
 * @param fields
 *            日志字段名以及对应在的列号
 * @param fieldNumber
 *            指定对应的列号值为时间戳
 * @param version
 *            规则当前的版本
 */
public DefaultLogFilterAndRule(String filterregex, String separator, JSONObject fields, int fieldNumber,
        int version) {

    this.filterPattern = Pattern.compile(filterregex);

    this.separator = Splitter.on(separator).trimResults();
    this.SpecifiedFields = new Integer[fields.size()];
    this.fieldsName = new String[fields.size()];
    int i = 0;
    for (Entry<String, Object> entry : fields.entrySet()) {
        fieldsName[i] = entry.getKey();
        SpecifiedFields[i++] = (Integer) entry.getValue();
    }
    this.timeStampField = fieldNumber;

    this.version = version;

    @SuppressWarnings("rawtypes")
    List<Map> mainlogs = Lists.newLinkedList();

    setMainlogs(mainlogs);
}
 
Example 10
Project: GitHub   File: JSONLibDataFormatSerializer.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("deprecation")
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
	if (object == null) {
		serializer.out.writeNull();
		return;
	}
	
    Date date = (Date) object;
   
    JSONObject json = new JSONObject();
    json.put("date", date.getDate());
    json.put("day", date.getDay());
    json.put("hours", date.getHours());
    json.put("minutes", date.getMinutes());
    json.put("month", date.getMonth());
    json.put("seconds", date.getSeconds());
    json.put("time", date.getTime());
    json.put("timezoneOffset", date.getTimezoneOffset());
    json.put("year", date.getYear());

    serializer.write(json);
}
 
Example 11
Project: ymate-payment-v2   File: WxPayJsApiController.java   Source Code and License 6 votes vote down vote up
private String __buildJsApiConfigStr(String appId, String jsapiTicket, String url, String timestamp, String noncestr, boolean debug) throws Exception {
    String _signature = "jsapi_ticket=" + jsapiTicket + "&" + "noncestr=" + noncestr + "&" + "timeStamp=" + timestamp + "&" + "url=" + url;
    _signature = DigestUtils.sha1Hex(_signature);
    //
    JSONObject _json = new JSONObject();
    _json.put("debug", debug);
    _json.put("appId", appId);
    _json.put("timestamp", timestamp);
    _json.put("nonceStr", noncestr);
    _json.put("signature", _signature);
    _json.put("jsApiList", new String[]{"chooseWXPay"});
    //
    return _json.toJSONString();
}
 
Example 12
Project: xxpay-master   File: WxApi.java   Source Code and License 6 votes vote down vote up
public static OAuthAccessToken getOAuthAccessToken(String appId, String appSecret, String code) {
	OAuthAccessToken token = null;
	String tockenUrl = getOAuthTokenUrl(appId, appSecret, code);
	JSONObject jsonObject = httpsRequest(tockenUrl, HttpMethod.GET, null);
	if (null != jsonObject && !jsonObject.containsKey("errcode")) {
		try {
			token = new OAuthAccessToken();
			token.setAccessToken(jsonObject.getString("access_token"));
			token.setExpiresIn(jsonObject.getInteger("expires_in"));
			token.setOpenid(jsonObject.getString("openid"));
			token.setScope(jsonObject.getString("scope"));
		} catch (JSONException e) {
			token = null;//获取token失败
		}
	}else if(null != jsonObject){
		token = new OAuthAccessToken();
		token.setErrcode(jsonObject.getInteger("errcode"));
	}
	return token;
}
 
Example 13
Project: KettleUtil   File: TimingUtil.java   Source Code and License 6 votes vote down vote up
/**
* 通过作业ID获取作业定时信息<br/>
* @author jingma
* @param dbCode 所在资源库代码
* @param jobId 作业ID
* @return SATRT控件实体
*/
public static JSONObject getTimingByJobId(int jobId) {
    Integer startId = getStartIdByJobId(KuConst.DS_KETTLE, jobId);
    if(startId==null){
        return null;
    }
    String sql = "select ja.value_num,ja.value_str,ja.code from r_jobentry_attribute ja "
            + "where ja.id_jobentry=?";
    List<JSONObject> records = Db.use(KuConst.DS_KETTLE).find(sql, startId);
    JSONObject result = new JSONObject();
    for(JSONObject record:records){
        if(StringUtil.isNotBlank(record.getString("value_str"))){
            result.put(startTimingMap.get(record.getString("code")), record.getString("value_str"));
        }else{
            result.put(startTimingMap.get(record.getString("code")), record.getInteger("value_num"));
        }
    }
    result.put("is_repeat", StringUtil.whether(result.getString("is_repeat")));
    return result;
}
 
Example 14
Project: hermes-java   File: Center.java   Source Code and License 6 votes vote down vote up
/**
 * 请求服务
 *
 * @param serverId 服务ID
 * @param name     方法名
 * @param data     数据
 * @return 响应数据
 * @throws Exception 加解密以及io错误
 */
public String call(String serverId, String name, String data) throws Exception {
    // 加密请求数据
    byte[] in = data.getBytes("utf-8");
    if (in.length > this.length - Constant.RSA_RESERVED_LENGTH) {
        throw new Exception("request data is too big");
    }
    byte[] bytes = RsaUtils.encryptByPublicKey(in, this.publicKey);
    // bytes转16进制发送
    String resp = HttpUtils.sendGet(String.format("http://%s/server?sessionId=%s&serverId=%s&name=%s&data=%s",
            this.host, this.sessionId, serverId, name, CoderUtils.bytesToHex(bytes)));
    JSONObject obj = JSON.parseObject(resp);
    Integer code = obj.getInteger(Constant.CODE);
    if (code != 0) {
        throw new Exception(String.format("call server fail, fail code: %d", code));
    }
    // 解密响应
    byte[] receive = RsaUtils.decryptByPublicKey(obj.getBytes(Constant.DATA), this.publicKey);
    return new String(receive);
}
 
Example 15
Project: SweepRobot   File: JSON.java   Source Code and License 6 votes vote down vote up
private static Message convertJSONObjectToMessage(JSONObject jo, Class c, Registry<Class> r) {
    //System.out.println("JSON.convertJSONObjectToMessage: " + jo.toJSONString());
    try {
        Message result = (Message) c.newInstance();
        for (Field f : c.getFields()) {
            Class fc = getFieldClass(result, jo, f, r);
            Object lookup = jo.get(f.getName());
            if (lookup != null) {
                Object value = convertElementToField(lookup, fc, f, r);
                f.set(result, value);
            }
        }      
        return result;
    }
    catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }        
}
 
Example 16
Project: wakeup-qcloud-sdk   File: DefaultQCloudClient.java   Source Code and License 6 votes vote down vote up
@Override
public boolean verifyUserSig(String identifier, String sig)throws QCloudException {
	try {
		Security.addProvider(new BouncyCastleProvider());
		
		//DeBaseUrl64 urlSig to json
		Base64 decoder = new Base64();

		byte [] compressBytes = Base64Url.base64DecodeUrl(sig.getBytes(Charset.forName("UTF-8")));
		
		//Decompression
		Inflater decompression =  new Inflater();
		decompression.setInput(compressBytes, 0, compressBytes.length);
		byte [] decompressBytes = new byte [1024];
		int decompressLength = decompression.inflate(decompressBytes);
		decompression.end();
		
		String jsonString = new String(Arrays.copyOfRange(decompressBytes, 0, decompressLength));
		
		//Get TLS.Sig from json
		JSONObject jsonObject= JSON.parseObject(jsonString);
		String sigTLS = jsonObject.getString("TLS.sig");
		
		//debase64 TLS.Sig to get serailString
		byte[] signatureBytes = decoder.decode(sigTLS.getBytes(Charset.forName("UTF-8")));
		
		String strSdkAppid = jsonObject.getString("TLS.sdk_appid");
		String sigTime = jsonObject.getString("TLS.time");
		String sigExpire = jsonObject.getString("TLS.expire_after");
		
		if (!imConfig.getSdkAppId().equals(strSdkAppid))
		{
			return false;
		}

		if ( System.currentTimeMillis()/1000 - Long.parseLong(sigTime) > Long.parseLong(sigExpire)) {
			return false;
		}
		
		//Get Serial String from json
		String SerialString = 
			"TLS.appid_at_3rd:" + 0 + "\n" +
			"TLS.account_type:" + 0 + "\n" +
			"TLS.identifier:" + identifier + "\n" + 
			"TLS.sdk_appid:" + imConfig.getSdkAppId() + "\n" + 
			"TLS.time:" + sigTime + "\n" + 
			"TLS.expire_after:" + sigExpire + "\n";
	
        Reader reader = new CharArrayReader(imConfig.getPublicKey().toCharArray());
        PEMParser  parser = new PEMParser(reader);
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        Object obj = parser.readObject();
        parser.close();
        PublicKey pubKeyStruct  = converter.getPublicKey((SubjectPublicKeyInfo) obj);

		Signature signature = Signature.getInstance("SHA256withECDSA","BC");
		signature.initVerify(pubKeyStruct);
		signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
		return signature.verify(signatureBytes);
	}catch (Exception e) {
		throw new QCloudException(e);
	}
}
 
Example 17
Project: kbase-doc   File: IndexController.java   Source Code and License 6 votes vote down vote up
/**
 * 文件列表
 * @author eko.zhan at 2017年8月9日 下午8:32:19
 * @return
 * @throws FileNotFoundException
 */
@ApiOperation(value="获取文件数据列表", notes="获取固定路径下的文件,并返回文件名,文件所在路径和文件大小")
@RequestMapping(value="getDataList", method=RequestMethod.POST)
public JSONArray getDataList() throws FileNotFoundException{
	JSONArray arr = new JSONArray();
	File dir = ResourceUtils.getFile("classpath:static/DATAS");
	File[] files = dir.listFiles();
	for (File file : files){
		if (file.isFile()){
			JSONObject json = new JSONObject();
			json.put("path", file.getPath());
			json.put("name", file.getName());
			json.put("size", file.length());
			arr.add(json);
		}
	}
	return arr;
}
 
Example 18
Project: xxpay-master   File: RefundOrderController.java   Source Code and License 6 votes vote down vote up
@RequestMapping("/list")
@ResponseBody
public String list(@ModelAttribute RefundOrder refundOrder, Integer pageIndex, Integer pageSize) {
    PageModel pageModel = new PageModel();
    int count = refundOrderService.count(refundOrder);
    if(count <= 0) return JSON.toJSONString(pageModel);
    List<RefundOrder> refundOrderList = refundOrderService.getRefundOrderList((pageIndex-1)*pageSize, pageSize, refundOrder);
    if(!CollectionUtils.isEmpty(refundOrderList)) {
        JSONArray array = new JSONArray();
        for(RefundOrder po : refundOrderList) {
            JSONObject object = (JSONObject) JSONObject.toJSON(po);
            if(po.getCreateTime() != null) object.put("createTime", DateUtil.date2Str(po.getCreateTime()));
            if(po.getRefundAmount() != null) object.put("amount", AmountUtil.convertCent2Dollar(po.getRefundAmount()+""));
            array.add(object);
        }
        pageModel.setList(array);
    }
    pageModel.setCount(count);
    pageModel.setMsg("ok");
    pageModel.setRel(true);
    return JSON.toJSONString(pageModel);
}
 
Example 19
Project: snowflake   File: PartnerStore.java   Source Code and License 6 votes vote down vote up
public void addPartner(String key, Partner partner) {
	String partnerPath = ZKPaths.makePath(partnerStorePath, key);
	RetryRunner.create().onFinalError(e -> {
		LOGGER.error("addPartner.error", e);
		ReporterHolder.incException(e);
		throw new ServiceErrorException(ErrorCode.SYSTEM_ERROR);
	}).run((Callable<Void>) () -> {
		if (client.checkExists().creatingParentsIfNeeded().forPath(partnerPath) != null) {
			client.setData()
			      .forPath(partnerPath, JSONObject.toJSONBytes(partner));
		} else {
			client.create()
			      .creatingParentsIfNeeded()
			      .withMode(CreateMode.PERSISTENT)
			      .forPath(partnerPath, JSONObject.toJSONBytes(partner));
		}
		return null;
	});
}
 
Example 20
Project: OftenPorter   File: WPTool.java   Source Code and License 6 votes vote down vote up
/**
 * 在json对象里是否含有指定的键值
 *
 * @param array  存放的是json对象
 * @param key
 * @param object
 * @return 存在则,返回对应索引;不存在返回-1.
 */
public static int containsJsonValue(JSONArray array, String key, Object object)
{
    int index = -1;

    for (int i = 0; i < array.size(); i++)
    {
        JSONObject jsonObject = array.getJSONObject(i);
        if (jsonObject.containsKey(key) && jsonObject.get(key).equals(object))
        {
            index = i;
            break;
        }
    }

    return index;
}
 
Example 21
Project: shuzheng   File: UpmsUserPermissionServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public int permission(JSONArray datas, int id) {
    for (int i = 0; i < datas.size(); i ++) {
        JSONObject json = datas.getJSONObject(i);
        if (json.getBoolean("checked")) {
            // 新增权限
            UpmsUserPermission upmsUserPermission = new UpmsUserPermission();
            upmsUserPermission.setUserId(id);
            upmsUserPermission.setPermissionId(json.getIntValue("id"));
            upmsUserPermission.setType(json.getByte("type"));
            upmsUserPermissionMapper.insertSelective(upmsUserPermission);
        } else {
            // 删除权限
            UpmsUserPermissionExample upmsUserPermissionExample = new UpmsUserPermissionExample();
            upmsUserPermissionExample.createCriteria()
                    .andPermissionIdEqualTo(json.getIntValue("id"))
                    .andTypeEqualTo(json.getByte("type"));
            upmsUserPermissionMapper.deleteByExample(upmsUserPermissionExample);
        }
    }
    return datas.size();
}
 
Example 22
Project: pay-xxpay-master   File: GoodsOrderController.java   Source Code and License 5 votes vote down vote up
private Map createPayOrder(GoodsOrder goodsOrder, Map<String, Object> params) {
    JSONObject paramMap = new JSONObject();
    paramMap.put("mchId", mchId);                       // 商户ID
    paramMap.put("mchOrderNo", goodsOrder.getGoodsOrderId());           // 商户订单号
    paramMap.put("channelId", params.get("channelId"));             // 支付渠道ID, WX_NATIVE,ALIPAY_WAP
    paramMap.put("amount", goodsOrder.getAmount());                          // 支付金额,单位分
    paramMap.put("currency", "cny");                    // 币种, cny-人民币
    paramMap.put("clientIp", "114.112.124.236");        // 用户地址,IP或手机号
    paramMap.put("device", "WEB");                      // 设备
    paramMap.put("subject", goodsOrder.getGoodsName());
    paramMap.put("body", goodsOrder.getGoodsName());
    paramMap.put("notifyUrl", "http://shop.xxpay.org/goods/payNotify");         // 回调URL
    paramMap.put("param1", "");                         // 扩展参数1
    paramMap.put("param2", "");                         // 扩展参数2

    JSONObject extra = new JSONObject();
    extra.put("openId", params.get("openId"));
    paramMap.put("extra", extra.toJSONString());  // 附加参数

    String reqSign = PayDigestUtil.getSign(paramMap, reqKey);
    paramMap.put("sign", reqSign);   // 签名
    String reqData = "params=" + paramMap.toJSONString();
    System.out.println("请求支付中心下单接口,请求数据:" + reqData);
    String url = baseUrl + "/pay/create_order?";
    String result = XXPayUtil.call4Post(url + reqData);
    System.out.println("请求支付中心下单接口,响应数据:" + result);
    Map retMap = JSON.parseObject(result);
    if("SUCCESS".equals(retMap.get("retCode"))) {
        // 验签
        String checkSign = PayDigestUtil.getSign(retMap, resKey, "sign", "payParams");
        String retSign = (String) retMap.get("sign");
        if(checkSign.equals(retSign)) {
            System.out.println("=========支付中心下单验签成功=========");
        }else {
            System.err.println("=========支付中心下单验签失败=========");
            return null;
        }
    }
    return retMap;
}
 
Example 23
Project: UIAutomatorWD   File: ActionController.java   Source Code and License 5 votes vote down vote up
private static boolean pinch(JSONObject args) throws Exception {
    String elementId = args.getString("element");
    Element el;
    if (elementId == null) {
        el = elements.getElement("1");
    } else {
        el = elements.getElement(elementId);
    }
    String direction = args.getString("direction");
    float percent = args.getFloat("percent");
    int steps = args.getInteger("steps");
    return el.pinch(direction, percent, steps);
}
 
Example 24
Project: dooo   File: ArcticleController.java   Source Code and License 5 votes vote down vote up
@SecurityAnnotation
@RequestMapping(value = "addBlog", method = RequestMethod.POST)
@ResponseBody
public ReturnT<String> addBlog(Model model, HttpServletRequest request, HttpServletResponse response, @RequestParam("blog") String blog) {
    HeadPrinter.printHead(model);
    UserAuthDO userAuthDO = UserAuth.getCurrentUser(request);

    JSONObject jsonObject = JSONObject.parseObject(blog);
    String title = jsonObject.getString("title");
    String img = jsonObject.getString("img");

    String content = jsonObject.getString("content");
    Article article = new Article();
    article.setUserId(userService.getByName(userAuthDO.getName()).getId());
    article.setCategory(ArcticleCategoryEnums.BLOG.getMessage());
    article.setTitle(title);
    article.setTag(TagEnums.TAG_2.getMessage());
    article.setImg(img);
    article.setContent(content);
    article.setCreateDate(new Date());
    article.setUpdateDate(new Date());
    Integer id = arcticleService.addArcticle(article);
    if (id <= 0) {
        return ReturnT.FAIL;
    }
    return ReturnT.SUCCESS;
}
 
Example 25
Project: weex-3d-map   File: WXGesture.java   Source Code and License 5 votes vote down vote up
/**
 * Create a touchObject for a pointer at a certain moment.
 * @param motionEvent motionEvent, which contains all pointers event in a period of time
 * @param pos index used to retrieve a certain moment in a period of time.
 * @param pointerIndex pointerIndex
 * @return JSONObject represent a touch event
 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Touch">touch</a>
 */
private JSONObject createJSONObject(MotionEvent motionEvent, int pos, int pointerIndex) {
  PointF screenXY, pageXY;
  if (pos == CUR_EVENT) {
    pageXY = getEventLocInPageCoordinate(motionEvent, pointerIndex);
    screenXY = getEventLocInScreenCoordinate(motionEvent, pointerIndex);
  } else {
    pageXY = getEventLocInPageCoordinate(motionEvent, pointerIndex, pos);
    screenXY = getEventLocInScreenCoordinate(motionEvent, pointerIndex, pos);
  }
  return createJSONObject(screenXY, pageXY, (float) motionEvent.getPointerId(pointerIndex));
}
 
Example 26
Project: Spring-Boot-Server   File: TongzhouDataSync.java   Source Code and License 5 votes vote down vote up
public List<PageData> getCatalogDatas(String url) {
	String result = HttpUtils.getResponse(url, new HashMap(), new ArrayList<UHeader>());
	System.err.println(result);
	JSONObject jo = JSON.parseObject(result);
	List<PageData> pdList = JSON.parseObject(jo.getString("Catalog"), new TypeReference<List<PageData>>() {});
	return pdList;
}
 
Example 27
Project: cstruct-parser   File: DefaultDispatchCenterServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public ResponseResult handle(String id,JSONObject message)
{

	HandleMessageService messageService = getHandleMessageService(id);

	return handle(messageService, message);
}
 
Example 28
Project: weex-uikit   File: WXDomObject.java   Source Code and License 5 votes vote down vote up
/**
 * Parse the jsonObject to {@link WXDomObject} recursively
 * @param map the original JSONObject
 */
public void parseFromJson(JSONObject map){
  if (map == null || map.size() <= 0) {
    return;
  }

  String type = (String) map.get("type");
  this.mType = type;
  this.mRef = (String) map.get("ref");
  Object style = map.get("style");
  if (style != null && style instanceof JSONObject) {
    WXStyle styles = new WXStyle();
    styles.putAll((JSONObject) style,false);
    this.mStyles = styles;
  }
  Object attr = map.get("attr");
  if (attr != null && attr instanceof JSONObject) {
    WXAttr attrs = new WXAttr((JSONObject) attr);
    //WXJsonUtils.putAll(attrs, (JSONObject) attr);
    this.mAttributes = attrs;
  }
  Object event = map.get("event");
  if (event != null && event instanceof JSONArray) {
    WXEvent events = new WXEvent();
    JSONArray eventArray = (JSONArray) event;
    int count = eventArray.size();
    for (int i = 0; i < count; ++i) {
      events.add(eventArray.getString(i));
    }
    this.mEvents = events;
  }

}
 
Example 29
Project: GitHub   File: TypeUtilsTest.java   Source Code and License 5 votes vote down vote up
public void test_2() throws Exception {
    JSONObject map = new JSONObject();
    map.put("id", 1);
    map.put("name", "panlei");

    User user = TypeUtils.castToJavaBean(map, User.class);
    Assert.assertEquals(1L, user.getId());
    Assert.assertEquals("panlei", user.getName());
}
 
Example 30
Project: tangyuan2   File: FastJsonConverter.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isSupportType(Object object) {
	if (object instanceof JSONObject) {
		return true;
	}
	return false;
}
 
Example 31
Project: jsf-core   File: DefaultScheduleDataManager.java   Source Code and License 5 votes vote down vote up
@Override
public void saveWorkerParameters(ScheduleServer currentServer, JSONObject parameters) {
    String zkPath = "/"+Constants.SAF_WORKER_ROOT+"/"+currentServer.getWorkerType()+"/"+Constants.SAF_WORKER_SERVER+"/"+currentServer.getId();
    JSONObject serverJSON = (JSONObject) JSONObject.toJSON(currentServer);
    byte[] serverValue = serverJSON.toJSONString().getBytes();
    try {
        zkClient.writeData(zkPath,serverValue);
    } catch (Exception e) {
        logger.error(" save [{}] parameters on server {} failed",currentServer.getWorkerType(),currentServer.getId(),e);
    }
}
 
Example 32
Project: ucar-weex-core   File: WXComponent.java   Source Code and License 5 votes vote down vote up
private void updateStyleByPesudo(Map<String,Object> styles){
  Message message = Message.obtain();
  WXDomTask task = new WXDomTask();
  task.instanceId = getInstanceId();
  task.args = new ArrayList<>();

  JSONObject styleJson = new JSONObject(styles);
  task.args.add(getRef());
  task.args.add(styleJson);
  task.args.add(true);//flag pesudo
  message.obj = task;
  message.what = WXDomHandler.MsgType.WX_DOM_UPDATE_STYLE;
  WXSDKManager.getInstance().getWXDomManager().sendMessage(message);
}
 
Example 33
Project: xxpay-master   File: WxPayUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 获取微信支付配置
 * @param configParam
 * @param tradeType
 * @param certRootPath
 * @param notifyUrl
 * @return
 */
public static WxPayConfig getWxPayConfig(String configParam, String tradeType, String certRootPath, String notifyUrl) {
    WxPayConfig wxPayConfig = new WxPayConfig();
    JSONObject paramObj = JSON.parseObject(configParam);
    wxPayConfig.setMchId(paramObj.getString("mchId"));
    wxPayConfig.setAppId(paramObj.getString("appId"));
    wxPayConfig.setKeyPath(certRootPath + File.separator + paramObj.getString("certLocalPath"));
    wxPayConfig.setMchKey(paramObj.getString("key"));
    wxPayConfig.setNotifyUrl(notifyUrl);
    wxPayConfig.setTradeType(tradeType);
    return wxPayConfig;
}
 
Example 34
Project: GitHub   File: DenyTest16.java   Source Code and License 5 votes vote down vote up
public void test_deny() throws Exception {
    JSONObject object = new JSONObject();
    object.put("@type", "com.mchange.v2.c3p0.impl.PoolBackedDataSourceBase");

    Throwable error = null;
    try {
        TypeUtils.castToJavaBean(object, Object.class);
    } catch (Exception ex) {
        error = ex;
    }
    assertNotNull(error);
}
 
Example 35
Project: GitHub   File: TypeUtilsTest.java   Source Code and License 5 votes vote down vote up
public void test_cast_to_Timestamp_util_Date() throws Exception {
    long millis = System.currentTimeMillis();

    JSONObject json = new JSONObject();
    json.put("date", new Date(millis));
    Assert.assertEquals(new java.sql.Timestamp(millis), json.getObject("date", java.sql.Timestamp.class));
}
 
Example 36
Project: FCat   File: TMenuController.java   Source Code and License 5 votes vote down vote up
/**
 * 获取完整树形结构
 * @return
 * @throws RuntimeException
 */
@ApiOperation(value = "获取完整树形结构" )
@RequestMapping(value = "allTree", method = RequestMethod.GET)
public JSONObject allTree()throws Exception{
    List<TMenuTree> tMenuTreeList = new ArrayList<>();
    List<TMenu> menuList = bsi.selectListAll();
    for(TMenu tMenu:menuList){
        TMenuTree tMenuTree = new TMenuTree();
        BeanUtils.copyProperties(tMenu,tMenuTree);
        tMenuTreeList.add(tMenuTree);
    }
    List<TMenuTree> result = TreeUtil.buildByRecursive(tMenuTreeList,-1);
    return JsonUtil.getSuccessJsonObject(result);
}
 
Example 37
Project: Thrush   File: MarkDownUtil.java   Source Code and License 5 votes vote down vote up
public static String begin() {
    JSONObject jsonObject = template();
    StringBuilder builder = new StringBuilder("* ").append("开启12306抢票任务").append("\n");
    builder.append("* [开始抢票](").append(HostConfig.domain).append("/task/begin").append(")\n");
    jsonObject.put("text", builder.toString());
    return jsonObject.toJSONString();
}
 
Example 38
Project: spring-boot-wechat   File: ResultResponse.java   Source Code and License 5 votes vote down vote up
/**
 * 返回错误结果
 *
 * @param msg
 * @return
 */
public static Object error(String msg) {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("code", 0);
    jsonObject.put("msg", msg);

    return jsonObject.toJSONString();
}
 
Example 39
Project: OftenPorter   File: JSON2MapParser.java   Source Code and License 5 votes vote down vote up
@Override
public ParseResult parse(@NotNull String name, @NotNull Object value,@MayNull Object dealt)
{
    ParseResult result = super.parse(name, value,dealt);
    if (result.isLegal())
    {
        JSONObject jsonObject = (JSONObject) result.getValue();
        Map<String, Object> map = jsonObject;
        result.setValue(map);
    }
    return result;
}
 
Example 40
Project: GitHub   File: Issue1449.java   Source Code and License 5 votes vote down vote up
public void write(JSONSerializer serializer, Object fieldName, Type fieldType, int features) throws IOException {

            JSONObject object = new JSONObject();
            object.put("code", code);
            object.put("des", des);
            serializer.write(object);

        }
 
Example 41
Project: upgradeToy   File: ParseEventMap.java   Source Code and License 5 votes vote down vote up
/**
 * JSONArray转为List
 * @param array json数组
 * @return 转化后的List
 */
public static List<Object> toList(JSONArray array){
    List<Object> list = new ArrayList<Object>();
    for(int i = 0; i < array.size(); i++) {
        Object value = array.get(i);
        if(value instanceof JSONArray) {
            value = toList((JSONArray) value);
        }else if(value instanceof JSONObject) {
            value = toMap((JSONObject) value);
        }
        list.add(value);
    }
    return list;
}
 
Example 42
Project: fastdfs-quickstart   File: Group2Processor1.java   Source Code and License 5 votes vote down vote up
@Override
protected FResult<JSONObject> doProcess(UploadRequest request, FutureCallback<Object> response) {
  try {
    System.out.println(name);
    if (response!=null) {
      response.onSuccess(name+"response ok");
    }
    JSONObject o = new JSONObject();
    o.put("name", name);
    return FResult.newSuccess(o);
  } catch (Exception e) {
    return FResult.newFailure(1, e.getMessage());
  }
}
 
Example 43
Project: GitHub   File: JSONPParseTest1.java   Source Code and License 5 votes vote down vote up
public void test_f() throws Exception {
    String text = "callback /**/ ({'id':1, 'name':'idonans'} ); ";

    JSONPObject jsonpObject = JSON.parseObject(text, JSONPObject.class);
    assertEquals("callback", jsonpObject.getFunction());

    assertEquals(1, jsonpObject.getParameters().size());
    JSONObject param = (JSONObject) jsonpObject.getParameters().get(0);
    assertEquals(1, param.get("id"));
    assertEquals("idonans", param.get("name"));

    String json = JSON.toJSONString(jsonpObject);
    System.out.println(json);
}
 
Example 44
Project: Spring-Boot-Server   File: TongzhouDataSync.java   Source Code and License 5 votes vote down vote up
/**
	 * 获取同洲视频
	 * 
	 * @param url
	 *            获取Url地址
	 * @return
	 */
	public List<String> getVideosData(String url) {
		String result = HttpUtils.getResponse(url, new HashMap(), new ArrayList<UHeader>());
		System.err.println(result);
		JSONObject jo = JSON.parseObject(result);
		List<String> pdList = JSON.parseArray(jo.getString("playURLList"), String.class);
//		List<PageData> pdList = JSON.parseObject(jo.getString("playURLList"), new TypeReference<List<PageData>>() {});
		return pdList;
	}
 
Example 45
Project: OftenPorter   File: DataUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 若结果码为成功,且结果为JSONObject(不为null)时返回true.
 */
public static boolean resultJSON(JResponse jResponse)
{
    if (jResponse.isSuccess())
    {
        Object object = jResponse.getResult();
        if (object != null && (object instanceof JSONObject))
        {
            return true;
        }
    }
    return false;
}
 
Example 46
Project: yijava   File: InitWeb.java   Source Code and License 5 votes vote down vote up
private void initCache (JSONObject apiJson) {
	Integer cacheSeconds = apiJson.getInteger("cacheSeconds");
	if (cacheSeconds == null || cacheSeconds <= 0) {
		return;
	}
	if (!CacheUtils.CACHES_MAP.containsKey("cache_" + cacheSeconds)) {
		Cache<String, Object> cache = CacheBuilder.newBuilder().expireAfterWrite(cacheSeconds, TimeUnit.SECONDS).build();
		CacheUtils.CACHES_MAP.put("cache_" + cacheSeconds, cache);
	}
}
 
Example 47
Project: TITAN   File: ParamUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 将JSON转换为url参数
 * 
 * @author gaoxianglong
 */
public static String jsonToUrl(String p1, String p2) {
	StringBuffer param = new StringBuffer();
	try {
		JSONObject jsonObj = JSONObject.parseObject(p2);
		Set<String> keys = jsonObj.keySet();
		if (!keys.isEmpty()) {
			// if (StringUtils.isEmpty(p1)) {
			// param.append("?");
			// } else {
			// param.append(p1 + "&");
			// }
			param.append(StringUtils.isEmpty(p1) ? "?" : p1 + "&");
			keys.stream().forEach(key -> {
				param.append(key + "=" + jsonObj.get(key).toString());
				param.append("&");
			});
		}
	} catch (Exception e) {
		log.debug("参数并非是JSON");
	} finally {
		/* 删除最后一个符号& */
		if (!StringUtils.isEmpty(param.toString())) {
			int length = param.length();
			param.delete(length - 1, length);
		}
	}
	return param.toString();
}
 
Example 48
Project: Food_Ordering_System   File: RunningInformationController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/findAll", method = RequestMethod.GET)
public ResponseEntity<?> findAll(
        @RequestParam(name = "page", defaultValue = defaultRequirePage) int page,
        @RequestParam(name = "size", defaultValue = defaultRequireSize) int size) {
    Sort sort = new Sort(Sort.Direction.DESC,"heartRate");
    List<RunningInformation> content = runningInformationService.findAll( new PageRequest(page, size, sort)).getContent();
    return new ResponseEntity<List<JSONObject>>(getJsonResult(content), HttpStatus.OK);
}
 
Example 49
Project: GitHub   File: JSONObjectTest.java   Source Code and License 5 votes vote down vote up
public void test_all() throws Exception {
    JSONObject json = new JSONObject();
    Assert.assertEquals(true, json.isEmpty());
    json.put("C", 51L);
    json.put("B", 52);
    json.put("A", 53);
    Assert.assertEquals(false, json.isEmpty());
    Assert.assertEquals(true, json.containsKey("C"));
    Assert.assertEquals(false, json.containsKey("D"));
    Assert.assertEquals(true, json.containsValue(52));
    Assert.assertEquals(false, json.containsValue(33));
    Assert.assertEquals(null, json.remove("D"));
    Assert.assertEquals(51L, json.remove("C"));
    Assert.assertEquals(2, json.keySet().size());
    Assert.assertEquals(2, json.values().size());
    Assert.assertEquals(new BigDecimal("53"), json.getBigDecimal("A"));

    json.putAll(Collections.singletonMap("E", 99));
    Assert.assertEquals(3, json.values().size());
    json.clear();
    Assert.assertEquals(0, json.values().size());
    json.putAll(Collections.singletonMap("E", 99));
    Assert.assertEquals(99L, json.getLongValue("E"));
    Assert.assertEquals(99, json.getIntValue("E"));
    Assert.assertEquals("99", json.getString("E"));
    Assert.assertEquals(null, json.getString("F"));
    Assert.assertEquals(null, json.getDate("F"));
    Assert.assertEquals(null, json.getBoolean("F"));
}
 
Example 50
Project: FastEc   File: AddressDataConverter.java   Source Code and License 5 votes vote down vote up
@Override
public ArrayList<MultipleItemEntity> convert() {


    final JSONArray array = JSON.parseObject(getJsonData()).getJSONArray("data");
    final int size = array.size();
    for (int i = 0; i < size; i++) {

        final JSONObject data = array.getJSONObject(i);
        final int id = data.getInteger("id");
        final String name = data.getString("name");
        final String phone = data.getString("phone");
        final String address = data.getString("address");
        final boolean isDefault = data.getBoolean("default");

        final MultipleItemEntity entity = MultipleItemEntity.builder()
                .setItemType(AddressItemType.ITEM_ADDRESS)
                .setField(MultipleFields.ID, id)
                .setField(MultipleFields.NAME, name)
                .setField(MultipleFields.TAG, isDefault)
                .setField(AddressItemFields.PHONE, phone)
                .setField(AddressItemFields.ADDRESS, address)
                .build();

        ENTITIES.add(entity);

    }

    return ENTITIES;
}
 
Example 51
Project: pay   File: WeixinUtils.java   Source Code and License 5 votes vote down vote up
public static Map<String, Object> getAccessToken(WxConfig config) {
    String url = String.format(HttpApiUrl.PAY_ACCESS_TOKEN, config.getAppId(), config.getAppSecret());
    Map<String, Object> map = null;
    String res = HttpUtils.get(url);
    LogUtils.logResult("获取ACCESS_TOKEN", res);
    try {
        map = JSONObject.parseObject(res);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return map;
}
 
Example 52
Project: GitHub   File: TypeUtilsTest.java   Source Code and License 5 votes vote down vote up
public void test_cast_to_Timestamp() throws Exception {
    long millis = System.currentTimeMillis();

    JSONObject json = new JSONObject();
    json.put("date", millis);
    Assert.assertEquals(new java.sql.Timestamp(millis), json.getObject("date", java.sql.Timestamp.class));
}
 
Example 53
Project: TPondof   File: UserItemManager.java   Source Code and License 5 votes vote down vote up
public static User getUserInfo (int uid, boolean useCache) throws APIException {
    if (mCachedUsers.containsKey(uid)) {
        return mCachedUsers.get(uid);
    }
    try {
        return getUserInfo(uid
                , JSONObject
                        .parseObject(NetworkUtil
                                .get(ApiManager.API_USER_BY_ID + uid, useCache)), true);
    } catch (IOException|APIException e) {
        throw new APIException(e);
    }
}
 
Example 54
Project: weex-uikit   File: WXDomModule.java   Source Code and License 5 votes vote down vote up
/**
 * Update DOM style.
 * @param ref DOM reference
 * @param style the expected style
 */
public void updateStyle(String ref, JSONObject style) {
  if (TextUtils.isEmpty(ref) || style == null || style.size() < 1) {
    return;
  }
  Message msg = Message.obtain();
  WXDomTask task = new WXDomTask();
  task.instanceId = mWXSDKInstance.getInstanceId();
  task.args = new ArrayList<>();
  task.args.add(ref);
  task.args.add(style);
  msg.what = WXDomHandler.MsgType.WX_DOM_UPDATE_STYLE;
  msg.obj = task;
  WXSDKManager.getInstance().getWXDomManager().sendMessage(msg);
}
 
Example 55
Project: GitHub   File: JSONTest2.java   Source Code and License 5 votes vote down vote up
public void test_0() throws Exception {
    StringReader reader = new StringReader("{a:1,b:2}");
    String text = IOUtils.toString(reader);
    JSONObject json = (JSONObject) JSON.parse(text);
    Assert.assertEquals(2, json.size());
    Assert.assertEquals(1, json.getIntValue("a"));
    Assert.assertEquals(2, json.getIntValue("b"));
}
 
Example 56
Project: xxpay-master   File: WxPayUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 获取微信支付配置
 * @param configParam
 * @param tradeType
 * @param certRootPath
 * @param notifyUrl
 * @return
 */
public static WxPayConfig getWxPayConfig(String configParam, String tradeType, String certRootPath, String notifyUrl) {
    WxPayConfig wxPayConfig = new WxPayConfig();
    JSONObject paramObj = JSON.parseObject(configParam);
    wxPayConfig.setMchId(paramObj.getString("mchId"));
    wxPayConfig.setAppId(paramObj.getString("appId"));
    wxPayConfig.setKeyPath(certRootPath + File.separator + paramObj.getString("certLocalPath"));
    wxPayConfig.setMchKey(paramObj.getString("key"));
    wxPayConfig.setNotifyUrl(notifyUrl);
    wxPayConfig.setTradeType(tradeType);
    return wxPayConfig;
}
 
Example 57
Project: GitHub   File: FastJsonControllerTest.java   Source Code and License 5 votes vote down vote up
@RequestMapping("test2")
public
@ResponseBody
JSONObject test1(@RequestBody List<FastJsonParentTestVO> vos) {

    JSONObject jsonObj = new JSONObject();

    for (FastJsonParentTestVO fastJsonParentTestVO : vos) {

        jsonObj.put(fastJsonParentTestVO.getName(), fastJsonParentTestVO.getSonList().size());
    }

    return jsonObj;
}
 
Example 58
Project: minsx-ccs   File: App.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	COSCredentials cred = new BasicCOSCredentials("1251505282", "AKIDCXrebct3IXl0HXrvcHHLYp6UpKwMlFY0", "kaQEEFIMRYhr2OqImHoR5jQbgow7KYn2");
	ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
	COSClient cosClient = new COSClient(cred, clientConfig);
	String bucketName = "minsx";
	
	File localFile = new File("E:\\document\\编程文档\\Java真题库_电子书.pdf");
	String key = "/腾讯-COS.pdf";
	PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
	PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
	cosClient.shutdown();
	
	new CosClientException("");
	new CosServiceException("");
	
	
	//String result = cosClient.statFile(new StatFileRequest(bucketName, "/腾讯-COS.pdf"));
	String result = "{\"code\":0,\"message\":\"SUCCESS\",\"request_id\":\"NWEwMTlkMTNfZTlhMDY4NjRfOTRkZl8yMTkwYjA=\",\"data\":{\"access_url\":\"http://minsx-1251505282.file.myqcloud.com/%E8%85%BE%E8%AE%AF-COS.pdf\",\"authority\":\"eInvalid\",\"biz_attr\":\"\",\"ctime\":1509793525,\"custom_headers\":{},\"filelen\":3032065,\"filesize\":3032065,\"forbid\":0,\"mtime\":1509793525,\"sha\":\"8d32e1cc59a978a84556ab38fa9ca7ebbcdd7b04\",\"slicesize\":1048576,\"source_url\":\"http://minsx-1251505282.cossh.myqcloud.com/%E8%85%BE%E8%AE%AF-COS.pdf\"}}\r\n";
	System.out.println(result);
	JSONObject jsonObject = JSON.parseObject(result);
	System.out.println("code = "+jsonObject.get("code"));
	System.out.println("message = "+jsonObject.get("message"));
	System.out.println("access_url = "+jsonObject.getJSONObject("data").get("access_url"));
	System.out.println("authority = "+jsonObject.getJSONObject("data").get("authority"));
	System.out.println("biz_attr = "+jsonObject.getJSONObject("data").get("biz_attr"));
	System.out.println("ctime = "+jsonObject.getJSONObject("data").get("ctime"));
	System.out.println("custom_headers = "+jsonObject.getJSONObject("data").get("custom_headers"));
	System.out.println("filelen = "+jsonObject.getJSONObject("data").get("filelen"));
	System.out.println("filesize = "+jsonObject.getJSONObject("data").get("filesize"));
	System.out.println("forbid = "+jsonObject.getJSONObject("data").get("forbid"));
	System.out.println("mtime = "+jsonObject.getJSONObject("data").get("mtime"));
	System.out.println("sha = "+jsonObject.getJSONObject("data").get("sha"));
	System.out.println("slicesize = "+jsonObject.getJSONObject("data").get("slicesize"));
	System.out.println("source_url = "+jsonObject.getJSONObject("data").get("source_url"));
	
	System.out.println(new Date(1509793525000L));
	
}
 
Example 59
Project: FCat   File: JsonUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 格式日期后得到的返回结果,日期需要@JSONField(format="yyyy-MM-dd HH:mm:ss")进行注解
 * @param obj
 * @return
 */
public static JSONObject getSuccessResultJsonFormatDate(Object obj) {
    JSONObject resultJsonObject = getResultJson(ResultCodeEnum.SUCCESS);
    resultJsonObject.put(CODE, ResultCodeEnum.SUCCESS.getValue());
    resultJsonObject.put(MSG, ResultCodeEnum.SUCCESS.getKey());
    setData(resultJsonObject,JSONObject.toJSON(obj));
    return resultJsonObject;
}
 
Example 60
Project: framework   File: UserManager.java   Source Code and License 5 votes vote down vote up
/**
 * 批量移动用户分组
 *
 * @param openIds 用户唯一标识符openid的列表(size不能超过50)
 * @param groupId 分组id
 * @return 是否修改成功
 * @throws WeChatException
 */
public void membersDatchUpdateGroup(String[] openIds, int groupId) throws WeChatException {
	JSONObject jsonObject = new JSONObject();
	jsonObject.put("openid_list", openIds);
	jsonObject.put("to_groupid", groupId);
	String requestData = jsonObject.toString();
	logger.info("request data " + requestData);
	String resultStr = HttpUtils.post(GROUP_MEMBERS_DATCHUPDATE_POST_URL + TokenProxy.accessToken(), requestData);
	logger.info("return data " + resultStr);
	WeChatUtil.isSuccess(resultStr);
}