下面列出了com.alibaba.fastjson.JSONArray#getJSONObject ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static List<Tag> parseTag(String str) {
List<Tag> tags = new ArrayList<Tag>();
if (StringUtils.isNotBlank(str)) {
JSONArray jsonArray = JSONObject.parseObject(str).getJSONArray("topics");
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Tag tag = new Tag();
tag.setSlug(object.getString("slug"));
String name = object.getString(URLUtils.getTagName());
if (StringUtils.isBlank(name)) {
name = object.getString("name");
}
tag.setName(name);
JSONArray questionArray = object.getJSONArray("questions");
for (int j = 0; j < questionArray.size(); j++) {
tag.addQuestion(questionArray.getInteger(j).toString());
}
tags.add(tag);
}
}
return tags;
}
private List<OJContest> getWebDate() {
List<OJContest> list = new ArrayList<>();
try {
String str = httpUtil.readURL("http://contests.acmicpc.info/contests.json");
JSONArray array = JSON.parseArray(str);
for(int i = 0; i < array.size(); ++i) {
JSONObject object = array.getJSONObject(i);
OJContest contest = new OJContest();
contest.setId(object.getInteger("id"));
contest.setAccess(object.getString("access"));
contest.setLink(object.getString("link"));
contest.setName(object.getString("name"));
contest.setOj(object.getString("oj"));
contest.setStart_time(object.getString("start_time"));
contest.setWeek(object.getString("week"));
list.add(contest);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 保存商户照片
*
* @param business 业务对象
* @param businessStorePhotos 商户照片
*/
private void doBusinessStorePhoto(Business business, JSONArray businessStorePhotos) {
for (int businessStorePhotoIndex = 0; businessStorePhotoIndex < businessStorePhotos.size(); businessStorePhotoIndex++) {
JSONObject businessStorePhoto = businessStorePhotos.getJSONObject(businessStorePhotoIndex);
Assert.jsonObjectHaveKey(businessStorePhoto, "storeId", "businessStorePhoto 节点下没有包含 storeId 节点");
if (businessStorePhoto.getString("storePhotoId").startsWith("-")) {
throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "storePhotoId 错误,不能自动生成(必须已经存在的storePhotoId)" + businessStorePhoto);
}
//自动保存DEL信息
autoSaveDelBusinessStorePhoto(business, businessStorePhoto);
businessStorePhoto.put("bId", business.getbId());
businessStorePhoto.put("operate", StatusConstant.OPERATE_ADD);
//保存商户信息
storeServiceDaoImpl.saveBusinessStorePhoto(businessStorePhoto);
}
}
private static Permission json2Permission(JSONObject json) {
Permission.Builder permissionBuilder = Permission.newBuilder();
if (json.containsKey("type")) {
int type = json.getInteger("type");
permissionBuilder.setTypeValue(type);
}
if (json.containsKey("permission_name")) {
String permissionName = json.getString("permission_name");
permissionBuilder.setPermissionName(permissionName);
}
if (json.containsKey("threshold")) {
// long threshold = json.getLong("threshold");
long threshold = Long.parseLong(json.getString("threshold"));
permissionBuilder.setThreshold(threshold);
}
if (json.containsKey("parent_id")) {
int parentId = json.getInteger("parent_id");
permissionBuilder.setParentId(parentId);
}
if (json.containsKey("operations")) {
byte[] operations = ByteArray.fromHexString(json.getString("operations"));
permissionBuilder.setOperations(ByteString.copyFrom(operations));
}
if (json.containsKey("keys")) {
JSONArray keys = json.getJSONArray("keys");
List<Key> keyList = new ArrayList<>();
for (int i = 0; i < keys.size(); i++) {
Key.Builder keyBuilder = Key.newBuilder();
JSONObject key = keys.getJSONObject(i);
String address = key.getString("address");
// long weight = key.getLong("weight");
long weight = Long.parseLong(key.getString("weight"));
keyBuilder.setAddress(ByteString.copyFrom(WalletClient.decodeFromBase58Check(address)));
keyBuilder.setWeight(weight);
keyList.add(keyBuilder.build());
}
permissionBuilder.addAllKeys(keyList);
}
return permissionBuilder.build();
}
/**
* 合并服务 拼接最终报文
*
* @param dataFlowContext
* @return
*/
private JSONObject mergeService(DataFlowContext dataFlowContext) {
JSONArray services = dataFlowContext.getServiceBusiness();
JSONArray tmpServices = new JSONArray();
JSONObject service = null;
JSONObject existsService = null;
for (int serIndex = 0; serIndex < services.size(); serIndex++) {
service = services.getJSONObject(serIndex);
service.put(CommonConstant.HTTP_SEQ, serIndex + 1);
existsService = getTmpService(tmpServices, service.getString(CommonConstant.HTTP_BUSINESS_TYPE_CD));
if (existsService == null) {
tmpServices.add(service);
continue;
}
JSONObject data = existsService.getJSONObject(CommonConstant.HTTP_BUSINESS_DATAS);
// //获取到business
// JSONArray businesses = data.getJSONArray(service.getString(CommonConstant.HTTP_BUSINESS_TYPE_CD));
JSONObject tmpData = service.getJSONObject(CommonConstant.HTTP_BUSINESS_DATAS);
// businesses.addAll(tmpData.getJSONArray(service.getString(CommonConstant.HTTP_BUSINESS_TYPE_CD)));
//循环当前data 中的节点
for (String businessName : tmpData.keySet()) {
//已经存在这个 节点
if (data.containsKey(businessName)) {
JSONArray tmpDataBusinesses = data.getJSONArray(businessName);
tmpDataBusinesses.addAll(tmpData.getJSONArray(businessName));
} else {
data.put(businessName, tmpData.getJSONArray(businessName));
}
}
}
return restToCenterProtocol(tmpServices, dataFlowContext.getRequestCurrentHeaders());
}
public static List<Music> getAllMusic(JSONArray arr) {
List<Music> list = new ArrayList<>();
for (int i = 0; i < arr.size(); i++) {
JSONObject obj = arr.getJSONObject(i);
Music music = new Music();
music.setName(obj.getString("name"));
music.setUrl(getRedirectUrl(PLAY_URL + obj.getString("id") + ".mp3"));
music.setArtist(obj.getJSONArray("artists").getJSONObject(0).getString("name"));
music.setCover(obj.getJSONObject("album").getString("blurPicUrl").replaceFirst("http://","https://"));
music.setLrc("");
list.add(music);
}
return list;
}
/**
* {
* "item": [
* {
* "media_id": "6ijw4_-RotS_ChUsdkPM8pewCGRPo2udeb6T4LV0nb0",
* "name": "CropImage",
* "update_time": 1538105998,
* "url": "http:\/\/mmbiz.qpic.cn\/mmbiz_jpg\/OQcmKXAIJV1tQmwR3Lc9ePDup5byH5KVT7TMH5KjVY2Z70Ztmy4c0lYdVoasbvQl4Au4Wqfa5LXdKia8aFj9jug\/0?wx_fmt=jpeg"
* }
* ],
* "total_count": 12,
* "item_count": 13
* }
* <p>
* https://www.cnblogs.com/softidea/p/9438783.html
*/
@Test
public void download() {
String tmpDir = System.getProperty("java.io.tmpdir");
File dir = new File(tmpDir, "media");
String batchGetUrl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={accessToken}";
Map<String, String> request = new HashMap<>();
request.put("offset", "20");
request.put("count", "20");
request.put("type", "image");
String accessToken = "14_rcAT5z3Kz7iYDhv0NQrCV5zxUH12dZB0azjLnRAdM1xGVnfV73hVc9oDdkMd1wJMMt9pQRrLYyK8mdXEpqBs5PoO90C_-LJyRDNYR-H6SqwsOsCdRivpj1ifWzuJLsOTUyTXHggNQNHAJRs4UCEfAFAIQS";
ResponseEntity<String> responseEntity = restTemplate.postForEntity(batchGetUrl, request, String.class, accessToken);
String body = responseEntity.getBody();
JSONObject jsonObject = JSON.parseObject(body);
String total_count = jsonObject.getString("total_count");
String item_count = jsonObject.getString("item_count");
log.info("total_count:{} , item_count:{}", total_count, item_count);
JSONArray item = jsonObject.getJSONArray("item");
for (int i = 0; i < item.size(); i++) {
JSONObject material = item.getJSONObject(i);
String url = material.getString("url");
String media_id = material.getString("media_id");
String name = material.getString("name");
ResponseEntity<byte[]> oneImageFile = restTemplate.getForEntity(url, byte[].class);
try (ByteArrayInputStream source = new ByteArrayInputStream(oneImageFile.getBody())) {
File destination = new File(dir, String.join("-", String.valueOf(i), media_id, name, ".jpg"));
FileUtils.copyInputStreamToFile(source, destination);
log.info(destination.getAbsolutePath());
} catch (IOException e) {
log.warn(e.getMessage(), e);
}
}
log.info("tmpDir:{}", dir.getAbsolutePath());
}
/**
* 统一解析Trades
*/
public static Trades parseTrades(JSONArray r) {
List<Trade> trades = new ArrayList<>(r.size());
for (int i = 0, l = r.size(); i < l; i++) {
/*
* [
* {
* "time":"2019-01-11T14:02:02.536Z",
* "timestamp":"2019-01-11T14:02:02.536Z",
* "trade_id":"861471459",
* "price":"3578.8482",
* "size":"0.0394402",
* "side":"sell"
* },
*/
JSONObject t = r.getJSONObject(i);
Long time = t.getDate("timestamp").getTime();
String id = t.getString("trade_id");
Side side = Side.valueOf(t.getString("side").toUpperCase());
BigDecimal price = t.getBigDecimal("price");
BigDecimal amount = t.getBigDecimal("size");
Trade trade = new Trade(r.getString(i), time, id, side, price, amount);
trades.add(trade);
}
return new Trades(trades.stream()
.sorted((t1, t2) -> t2.getTime().compareTo(t1.getTime()))
.collect(Collectors.toList()));
}
public static JSONObject getOneBusinessFromCenterServiceResponseJson(String resJson){
JSONArray paramOut = getBusinessFromCenterServiceResponseJson(resJson);
if(paramOut != null && paramOut.size() > 0){
JSONObject business = paramOut.getJSONObject(0);
if(!"0000".equals(business.getJSONObject("response").getString("code"))){
return null;
}
return business;
}
return null;
}
public static LinkedHashMap<String,BundleListing.BundleInfo> parseArray(String listingStr,LinkedHashMap<String,BundleListing.BundleInfo>currentBundleInfo) throws Exception{
LinkedHashMap<String,BundleListing.BundleInfo> infos= new LinkedHashMap<>();
JSONArray array = JSON.parseArray(listingStr);
for(int x=0; x<array.size(); x++){
JSONObject object = array.getJSONObject(x);
BundleListing.BundleInfo info = new BundleListing.BundleInfo();
info.setName(object.getString("name"));
info.setPkgName(object.getString("pkgName"));
info.setApplicationName(object.getString("applicationName"));
info.setVersion(object.getString("version"));
info.setDesc(object.getString("desc"));
info.setUrl(object.getString("url"));
info.setMd5(object.getString("md5"));
String uniqueTag = object.getString("unique_tag");
if(StringUtils.isEmpty(uniqueTag)){
throw new IOException("uniqueTag is empty");
}
info.setUnique_tag(object.getString("unique_tag"));
if (currentBundleInfo==null) {
info.setCurrent_unique_tag(info.getUnique_tag());
}else {
if (currentBundleInfo.get(info.getPkgName())!= null){
info.setCurrent_unique_tag(currentBundleInfo.get(info.getPkgName()).getUnique_tag());
}
}
infos.put(info.getPkgName(),info);
}
return infos.size()>0 ? infos : null;
}
private static List<List<Object>> genRspArgs(String parentKey, JSONArray jsonArray) {
if (jsonArray == null || jsonArray.isEmpty()) {
return new ArrayList<>();
}
List<List<Object>> result = new ArrayList<>();
if (parentKey == null) {
Object[] header = new Object[]{"参数名称", "是否必须", "数据类型", "描述"};
result.add(Arrays.asList(header));
}
if (parentKey != null) {
parentKey += PLACEHOLDER_CHILDPARAM;
}
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject entry = jsonArray.getJSONObject(i);
String name = entry.getString("name");
if (parentKey != null) {
name = parentKey + name;
}
String require = entry.getString("require");
String type = entry.getString("type");
String description = entry.getString("description");
Object[] param = new Object[]{name, require, type, description};
result.add(Arrays.asList(param));
JSONArray children = entry.getJSONArray("children");
if (children != null && !children.isEmpty()) {
parentKey = parentKey == null ? "" : parentKey;
result.addAll(genRspArgs(parentKey, children));
}
}
return result;
}
private List<CollectObject> getNetMetrics(String containerName,JSONObject container){
List<CollectObject> collectObjectList = new ArrayList<>();
boolean hasNetwork = container.getJSONObject("spec").getBoolean("has_network");
collectObjectList.add(new CollectObject(containerName,"has_network",hasNetwork ? "1" : "0",""));
if(hasNetwork){
JSONArray stats = container.getJSONArray("stats");
int count = stats.size();
JSONObject stat = stats.getJSONObject(count - 1);
JSONObject network = stat.getJSONObject("network");
JSONArray interfaces = network.getJSONArray("interfaces");
for (Object ifObj : interfaces) {
JSONObject ifJson = (JSONObject) ifObj;
String ifName = ifJson.getString("name");
String tag = "ifName=" + ifName;
long rxBytes = ifJson.getLong("rx_bytes");
long rxPackets = ifJson.getLong("rx_packets");
long rxErrors = ifJson.getLong("rx_errors");
long rxDropped = ifJson.getLong("rx_dropped");
long txBytes = ifJson.getLong("tx_bytes");
long txPackets = ifJson.getLong("tx_packets");
long txErrors = ifJson.getLong("tx_errors");
long txDropped = ifJson.getLong("tx_dropped");
collectObjectList.add(new CollectObject(containerName,"net.if.in.bytes",String.valueOf(rxBytes),tag));
collectObjectList.add(new CollectObject(containerName,"net.if.in.packets",String.valueOf(rxPackets),tag));
collectObjectList.add(new CollectObject(containerName,"net.if.in.errors",String.valueOf(rxErrors),tag));
collectObjectList.add(new CollectObject(containerName,"net.if.in.dropped",String.valueOf(rxDropped),tag));
collectObjectList.add(new CollectObject(containerName,"net.if.out.bytes",String.valueOf(txBytes),tag));
collectObjectList.add(new CollectObject(containerName,"net.if.out.packets",String.valueOf(txPackets),tag));
collectObjectList.add(new CollectObject(containerName,"net.if.out.errors",String.valueOf(txErrors),tag));
collectObjectList.add(new CollectObject(containerName,"net.if.out.dropped",String.valueOf(txDropped),tag));
}
}
return collectObjectList;
}
/**
* 获取新闻列表
*
* @param keyword
* @param page
* @return
*/
public static List<News> getNewsList(String keyword, int page)
{
List<News> newsList = new ArrayList<News>();
String path = "http://m.baidu.com/news?tn=bdapisearch&word=" + keyword + "&pn=" + page * 20
+ "&rn=20&t=1386838893136";
AsyncHttpClient asyncHttpClient = Wo2bAsyncHttpClient.newAsyncHttpClient();
SyncHttpResponse httpResponse = SyncHttpClient.getSync(asyncHttpClient, path, null);
if (httpResponse == null || !httpResponse.isOK())
{
return null;
}
String response = httpResponse.getContent();
JSONArray jsonArray = JSON.parseArray(response);
if (jsonArray == null)
{
return newsList;
}
JSONObject jsonObject = null;
News news = null;
int count = jsonArray.size();
for (int i = 0; i < count; i++)
{
jsonObject = jsonArray.getJSONObject(i);
news = new News();
news.setTitle(jsonObject.getString("title"));
news.setSource(jsonObject.getString("author"));
news.setUrl(jsonObject.getString("url"));
news.setPhotoUrl(jsonObject.getString("imgUrl"));
Long sortTime = jsonObject.getLong("sortTime") * 1000;
String date = DateUtils.getStringByStyle(sortTime, "yyyy-MM-dd HH:mm");
news.setDate(date);
newsList.add(news);
}
return newsList;
}
@Override
public List<ExpressInfo> query(ExpressCompany company, String num) {
String appId = JPressOptions.get("express_api_appid");
String appSecret = JPressOptions.get("express_api_appsecret");
String param = "{\"com\":\"" + company.getCode() + "\",\"num\":\"" + num + "\"}";
String sign = HashKit.md5(param + appSecret + appId);
HashMap params = new HashMap();
params.put("showapi_appid", appId);
params.put("com", sign);
params.put("nu", num);
params.put("contentType", "bodyString");
params.put("showapi_sign", signRequest(params, appSecret));
String result = HttpUtil.httpGet("http://route.showapi.com/64-19", params);
if (StrUtil.isBlank(result)) {
return null;
}
try {
JSONObject object = JSONObject.parseObject(result);
JSONObject body = object.getJSONObject("showapi_res_body");
if (body != null) {
JSONArray jsonArray = body.getJSONArray("data");
if (jsonArray != null && jsonArray.size() > 0) {
List<ExpressInfo> list = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject expObject = jsonArray.getJSONObject(i);
ExpressInfo ei = new ExpressInfo();
ei.setInfo(expObject.getString("context"));
ei.setTime(expObject.getString("time"));
list.add(ei);
}
return list;
}
}
} catch (Exception ex) {
LOG.error(ex.toString(), ex);
}
LOG.error(result);
return null;
}
private void setGoodTextClick(TextView mTextView2, JSONArray data,
LinearLayout ll_goodmembers, View view, int cSize) {
if (data == null || data.size() == 0) {
ll_goodmembers.setVisibility(View.GONE);
} else {
ll_goodmembers.setVisibility(View.VISIBLE);
}
if (cSize > 0 && data.size() > 0) {
view.setVisibility(View.VISIBLE);
} else {
view.setVisibility(View.GONE);
}
SpannableStringBuilder ssb = new SpannableStringBuilder();
int start = 0;
for (int i = 0; i < data.size(); i++) {
JSONObject json_good = data.getJSONObject(i);
// String userID = json_good.getString("userID");
String userID_temp = json_good.getString("userID");
String nick = userID_temp;
if (userID_temp.equals(myuserID)) {
nick = myNick;
} else {
User user = MYApplication.getInstance().getContactList()
.get(userID_temp);
if (user != null) {
nick = user.getNick();
}
}
if (i != (data.size() - 1) && data.size() > 1) {
ssb.append(nick + ",");
} else {
ssb.append(nick);
}
ssb.setSpan(new TextViewURLSpan(nick, userID_temp, 0), start, start
+ nick.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
start = ssb.length();
}
mTextView2.setText(ssb);
mTextView2.setMovementMethod(LinkMovementMethod.getInstance());
// SpannableStringBuilder newString = new SpannableStringBuilder();
// SpannableString temp = (SpannableString) mTextView2.getText();
// newString.append("000000");
// newString.append(temp);
// mTextView2.setText(newString);
}
/**
*
* 取消点赞
*
*/
public void cancelGood(String sID, TextView tv_good, JSONArray jsons,
LinearLayout ll_goodmembers_temp, View view, int cSize) {
// 即时改变当前UI
for (int i = 0; i < jsons.size(); i++) {
JSONObject json = jsons.getJSONObject(i);
if (json.getString("userID").equals(myuserID)) {
jsons.remove(i);
}
}
setGoodTextClick(tv_good, jsons, ll_goodmembers_temp, view, cSize);
Map<String, String> map = new HashMap<String, String>();
map.put("sID", sID);
map.put("userID", myuserID);
SocialApiTask task = new SocialApiTask(SocialDetailActivity.this,
Constant.URL_SOCIAL_GOOD_CANCEL, map);
task.getData(new DataCallBack() {
@Override
public void onDataCallBack(JSONObject data) {
// dialog.dismiss();
if (data == null) {
Log.e("hideCommentEditText()-->>>>",
"hideCommentEditText()-----ERROR");
return;
}
int code = data.getInteger("code");
if (code == 1000) {
Log.e("hideCommentEditText()-->>>>",
"hideCommentEditText()-----SUCCESS");
} else {
Log.e("hideCommentEditText()-->>>>",
"hideCommentEditText()-----ERROR_2");
}
}
});
}
@Override
protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {
Assert.hasKeyAndValue(reqJson, "flowId", "flowId不能为空");
Assert.hasKeyAndValue(reqJson, "flowName", "请求报文中未包含flowName");
Assert.hasKeyAndValue(reqJson, "communityId", "请求报文中未包含communityId");
Assert.hasKeyAndValue(reqJson, "storeId", "请求报文中未包含商户ID");
if (!reqJson.containsKey("steps")) {
Assert.hasKeyAndValue(reqJson, "steps", "请求报文中未包含步骤节点");
}
JSONArray steps = reqJson.getJSONArray("steps");
if (steps == null || steps.size() < 1) {
throw new IllegalArgumentException("未包含步骤");
}
JSONObject step = null;
JSONObject subStaff = null;
for (int stepIndex = 0; stepIndex < steps.size(); stepIndex++) {
step = steps.getJSONObject(stepIndex);
Assert.hasKeyAndValue(step, "staffId", "步骤中未包含员工");
Assert.hasKeyAndValue(step, "staffName", "步骤中未包含员工");
Assert.hasKeyAndValue(step, "type", "步骤中类型会签还是正常流程");
//正常流程
if (WorkflowStepDto.TYPE_NORMAL.equals(step.getString("type"))) {
continue;
}
//会签流程
if (!step.containsKey("subStaff")) {
throw new IllegalArgumentException("未包含会签员工信息");
}
JSONArray subStaffs = step.getJSONArray("subStaff");
if (subStaffs == null || subStaffs.size() < 1) {
throw new IllegalArgumentException("未包含会签员工信息");
}
for (int subStaffIndex = 0; subStaffIndex < subStaffs.size(); subStaffIndex++) {
subStaff = subStaffs.getJSONObject(subStaffIndex);
Assert.hasKeyAndValue(subStaff, "staffId", "会签中未包含员工");
Assert.hasKeyAndValue(subStaff, "staffName", "会签中未包含员工");
}
}
}
@Override
public Page<Product> search(String keyword, int pageNum, int pageSize) {
Config config = new Config();
config.addToAppNames(appName);
config.setStart((pageNum - 1) * pageSize);
config.setHits(pageSize);
config.setSearchFormat(SearchFormat.JSON);
config.setFetchFields(Lists.newArrayList("id", "title", "content"));
SearchParams searchParams = new SearchParams(config);
// query 组合搜索的文档:https://help.aliyun.com/document_detail/29191.html
// // String query = "title:'"+keyword+"' OR content:'"+keyword+"'";
String query = "default:'" + keyword + "'";
searchParams.setQuery(query);
try {
SearchResult searchResult = searcherClient.execute(searchParams);
String resultJson = searchResult.getResult();
/**
* {
* "status": "OK",
* "request_id": "154883085219726516242866",
* "result": {
* "searchtime": 0.004142,
* "total": 1,
* "num": 1,
* "viewtotal": 1,
* "compute_cost": [
* {
* "index_name": "apptest",
* "value": 0.302
* }
* ],
* "items": [
* {
* "content": "ddddd ",
* "id": "109",
* "title": "<em>aaaa</em>",
* "index_name": "apptest"
* }
* ],
* "facet": []
* },
* "errors": [],
* "tracer": "",
* "ops_request_misc": "%7B%22request%5Fid%22%3A%22154883085219726516242866%22%2C%22scm%22%3A%2220140713.160006631..%22%7D"
* }
*/
JSONObject jsonObject = JSONObject.parseObject(resultJson);
if (!"ok".equalsIgnoreCase(jsonObject.getString("status"))) {
return null;
}
JSONObject resultObject = jsonObject.getJSONObject("result");
int total = resultObject.getInteger("total");
List<Product> products = new ArrayList<>();
JSONArray jsonArray = resultObject.getJSONArray("items");
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
Product product = new Product();
product.put(item.getInnerMap());
products.add(product);
}
return new Page<>(products, pageNum, pageSize, total / pageSize, total);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void translation(List<Question> questions) {
if (URLUtils.isCn() && !PersistentConfig.getInstance().getConfig().getEnglishContent()) {
String filePathTranslation = PersistentConfig.getInstance().getTempFilePath() + TRANSLATIONNAME;
try {
HttpRequest httpRequest = HttpRequest.post(URLUtils.getLeetcodeGraphql(), "application/json");
httpRequest.setBody("{\"operationName\":\"getQuestionTranslation\",\"variables\":{},\"query\":\"query getQuestionTranslation($lang: String) {\\n translations: allAppliedQuestionTranslations(lang: $lang) {\\n title\\n questionId\\n __typename\\n }\\n}\\n\"}");
httpRequest.addHeader("Accept", "application/json");
HttpResponse response = HttpRequestUtils.executePost(httpRequest);
String body;
if (response != null && response.getStatusCode() == 200) {
body = response.getBody();
FileUtils.saveFile(filePathTranslation, body);
} else {
body = FileUtils.getFileBody(filePathTranslation);
}
if (StringUtils.isNotBlank(body)) {
Map<String, String> translationMap = new HashMap<String, String>();
JSONArray jsonArray = JSONObject.parseObject(body).getJSONObject("data").getJSONArray("translations");
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
translationMap.put(object.getString("questionId"), object.getString("title"));
}
for (Question question : questions) {
if (translationMap.containsKey(question.getQuestionId())) {
question.setTitle(translationMap.get(question.getQuestionId()));
}
}
} else {
LogUtils.LOG.error("读取翻译内容为空");
}
} catch (Exception e1) {
LogUtils.LOG.error("获取题目翻译错误", e1);
}
}
}
/**
* 生成 html js java 类
*
* @param data
*/
private void generatorComponentJs(JSONObject data) {
StringBuffer sb = readFile(GeneratorStart.class.getResource("/web/add/add.js").getFile());
String fileContext = sb.toString();
fileContext = super.replaceTemplateContext(fileContext, data);
//替换 变量@@[email protected]@
JSONArray columns = data.getJSONArray("columns");
StringBuffer variable = new StringBuffer();
String defaultValue = "";
String validateInfo = "";
for (int columnIndex = 0; columnIndex < columns.size(); columnIndex++) {
JSONObject column = columns.getJSONObject(columnIndex);
defaultValue = column.getBoolean("hasDefaultValue") ? column.getString("defaultValue") : "";
defaultValue = "'" + defaultValue + "'";
variable.append(column.getString("code") + ":" + defaultValue + ",\n");
validateInfo += "'add" + toUpperCaseFirstOne(data.getString("templateCode")) + "Info." + column.getString("code") + "':[\n";
if (column.getBoolean("required")) {
validateInfo += "{\n" +
" limit:\"required\",\n" +
" param:\"\",\n" +
" errInfo:\"" + column.getString("cnCode") + "不能为空\"\n" +
" },\n";
}
if (column.containsKey("limit") && !StringUtils.isEmpty(column.getString("limit"))) {
validateInfo += " {\n" +
" limit:\"" + column.getString("limit") + "\",\n" +
" param:\"" + column.getString("limitParam") + "\",\n" +
" errInfo:\"" + column.getString("limitErrInfo") + "\"\n" +
" },\n" +
" ],\n";
}
}
fileContext = fileContext.replace("@@[email protected]@", variable.toString());
fileContext = fileContext.replace("@@[email protected]@", validateInfo);
// 替换 数据校验部分代码
String writePath = this.getClass().getResource("/").getPath()
+ "out/web/components/" + data.getString("directories") + "/add" + toUpperCaseFirstOne(data.getString("templateCode")) + "/add" + toUpperCaseFirstOne(data.getString("templateCode")) + ".js";
System.out.printf("writePath: " + writePath);
writeFile(writePath,
fileContext);
}