下面列出了com.alibaba.fastjson.JSONArray#forEach ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 接收前端的值
*
* @param classFeature 功能
* @param jsonArray array
* @return list
*/
default List<RoleModel.TreeLevel> parserValue(ClassFeature classFeature, JSONArray jsonArray) {
if (jsonArray == null) {
return null;
}
List<RoleModel.TreeLevel> list = new ArrayList<>();
jsonArray.forEach(o -> {
JSONObject jsonObject = (JSONObject) o;
JSONArray children = jsonObject.getJSONArray("children");
RoleModel.TreeLevel treeLevel = new RoleModel.TreeLevel();
if (children != null && !children.isEmpty()) {
treeLevel.setChildren(parserChildren(classFeature, children));
}
String id = jsonObject.getString("id");
if (id.contains(StrUtil.COLON)) {
id = id.split(StrUtil.COLON)[2];
}
treeLevel.setData(id);
treeLevel.setClassFeature(classFeature.name());
list.add(treeLevel);
});
return list;
}
/**
* 返回按照项目分组 排列的数组
*
* @return array
*/
public JSONArray getGroupProjects() {
JSONArray array = getProjects();
if (array == null) {
return null;
}
JSONArray newArray = new JSONArray();
Map<String, JSONObject> map = new HashMap<>(array.size());
array.forEach(o -> {
JSONObject pItem = (JSONObject) o;
String group = pItem.getString("group");
JSONObject jsonObject = map.computeIfAbsent(group, s -> {
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("group", s);
jsonObject1.put("projects", new JSONArray());
return jsonObject1;
});
JSONArray jsonArray = jsonObject.getJSONArray("projects");
jsonArray.add(pItem);
});
newArray.addAll(map.values());
return newArray;
}
@Override
public void addAuth(Long taskId, String userAuthJson, int sourceType, int targetType) {
if (StringUtils.isNotBlank(userAuthJson)) {
JSONArray datas = JSON.parseArray(userAuthJson);
if (datas != null && datas.size() > 0) {
List<UserGroupAuthMid> userGroupAuthMids = new ArrayList<>();
datas.forEach(obj -> {
Long sourceId = (Long) ((JSONObject) obj).get("sourceId");
Integer canEdit = (Integer) ((JSONObject) obj).get("canEdit");
Integer canExecute = (Integer) ((JSONObject) obj).get("canExecute");
UserGroupAuthMid model = new UserGroupAuthMid();
model.setSourceId(sourceId);
model.setTargetId(taskId);
model.setSourceType(sourceType);
model.setTargetType(targetType);
model.setHasEditAuth(canEdit);
model.setHasExecuteAuth(canExecute);
userGroupAuthMids.add(model);
});
this.addBatch(userGroupAuthMids);
}
}
}
private static JSONObject packPath(Path path) {
JSONObject graph = new JSONObject();
JSONArray relationships = new JSONArray();
JSONArray nodes = new JSONArray();
JSONArray objectNodes = packNodeByPath(path);
objectNodes.forEach(node -> {
JSONObject nodeObj = (JSONObject) node;
if (!nodes.contains(nodeObj)) nodes.add(nodeObj);
});
JSONArray objectRelas = packRelations(path);
objectRelas.forEach(relation -> {
JSONObject relationObj = (JSONObject) relation;
if (!relationships.contains(relationObj)) relationships.add(relationObj);
});
graph.put("relationships", relationships);
graph.put("nodes", nodes);
return graph;
}
public List<TokenDomain> request(RequestParams requestParams) throws ApiResponseException {
String res = super.makeRequest(requestParams);
if (Utils.isJsonEmptyArray(res)) {
return new ArrayList<>();
}
JSONObject payload = JSONObject.parseObject(res);
List<TokenDomain> tokens = new ArrayList<>();
Set<String> domains = payload.keySet();
for (String key : domains) {
JSONArray tokensInDomain = payload.getJSONArray(key);
tokensInDomain.forEach(tokenInDomain -> tokens.add(new TokenDomain((String) tokenInDomain, key)));
}
return tokens;
}
/**
* 每小时同步一次价格
*
* @throws UnirestException
*/
@Scheduled(cron = "0 0 * * * *")
public void syncPrice() throws UnirestException {
String url = "https://forex.1forge.com/1.0.2/quotes";
//如有报错 请自行官网申请获取汇率 或者默认写死
HttpResponse<JsonNode> resp = Unirest.get(url)
.queryString("pairs", "USDCNH,USDJPY,USDHKD,SGDCNH")
.queryString("api_key", "y4lmqQRykolDeO3VkzjYp2XZfgCdo8Tv")
.asJson();
log.info("forex result:{}", resp.getBody());
JSONArray result = JSON.parseArray(resp.getBody().toString());
result.forEach(json -> {
JSONObject obj = (JSONObject) json;
if ("USDCNH".equals(obj.getString("symbol"))) {
setUsdCnyRate(new BigDecimal(obj.getDouble("price")).setScale(2, RoundingMode.DOWN));
log.info(obj.toString());
} else if ("USDJPY".equals(obj.getString("symbol"))) {
setUsdJpyRate(new BigDecimal(obj.getDouble("price")).setScale(2, RoundingMode.DOWN));
log.info(obj.toString());
} else if ("USDHKD".equals(obj.getString("symbol"))) {
setUsdHkdRate(new BigDecimal(obj.getDouble("price")).setScale(2, RoundingMode.DOWN));
log.info(obj.toString());
} else if("SGDCNH".equals(obj.getString("symbol"))){
setSgdCnyRate(new BigDecimal(obj.getDouble("price")).setScale(2,RoundingMode.DOWN));
log.info(obj.toString());
}
});
}
/**
* 查询功能下面的所有动态数据
*
* @param classFeature 功能
* @param roleId 角色id
* @param dataId 上级数据id
* @return tree array
*/
default JSONArray listDynamic(ClassFeature classFeature, String roleId, String dataId) {
JSONArray listToArray;
try {
listToArray = listToArray(dataId);
if (listToArray == null || listToArray.isEmpty()) {
return null;
}
} catch (Exception e) {
DefaultSystemLog.getLog().error("拉取动态信息错误", e);
return null;
}
JSONArray jsonArray = new JSONArray();
listToArray.forEach(obj -> {
JSONObject jsonObject = new JSONObject();
JSONObject data = (JSONObject) obj;
String name = data.getString("name");
String id = data.getString("id");
jsonObject.put("title", name);
jsonObject.put("id", StrUtil.emptyToDefault(dataId, "") + StrUtil.COLON + classFeature.name() + StrUtil.COLON + id);
boolean doChildren = this.doChildren(classFeature, roleId, id, jsonObject);
if (!doChildren) {
// 没有子级
RoleService bean = SpringUtil.getBean(RoleService.class);
List<String> checkList = bean.listDynamicData(roleId, classFeature, dataId);
if (checkList != null && checkList.contains(id)) {
jsonObject.put("checked", true);
}
}
jsonArray.add(jsonObject);
});
return jsonArray;
}
/**
* 将二级数据转换为map
*
* @param jsonArray array
* @return map
*/
default Map<ClassFeature, JSONArray> convertArray(JSONArray jsonArray) {
Map<ClassFeature, JSONArray> newMap = new HashMap<>();
jsonArray.forEach(o -> {
JSONObject jsonObject = (JSONObject) o;
String id = jsonObject.getString("id");
ClassFeature classFeature = ClassFeature.valueOf(id);
newMap.put(classFeature, jsonObject.getJSONArray("children"));
});
return newMap;
}
public static <T> JSONObject arrayToObjById(JSONArray array) {
JSONObject jsonObject = new JSONObject();
array.forEach(o -> {
JSONObject jsonObject1 = (JSONObject) o;
jsonObject.put(jsonObject1.getString("id"), jsonObject1);
});
return jsonObject;
}
/**
* 每小时同步一次价格
*
* @throws UnirestException
*/
@Scheduled(cron = "0 0 * * * *")
public void syncPrice() throws UnirestException {
String url = "https://forex.1forge.com/1.0.2/quotes";
HttpResponse<JsonNode> resp = Unirest.get(url)
.queryString("pairs", "USDCNH,USDJPY,USDHKD,SGDCNH")
.queryString("api_key", "y4lmqQRykolHFp3VkzjYp2XZfgCdo8Tv")
.asJson();
log.info("forex result:{}", resp.getBody());
JSONArray result = JSON.parseArray(resp.getBody().toString());
result.forEach(json -> {
JSONObject obj = (JSONObject) json;
if ("USDCNH".equals(obj.getString("symbol"))) {
setUsdCnyRate(new BigDecimal(obj.getDouble("price")).setScale(2, RoundingMode.DOWN));
log.info(obj.toString());
} else if ("USDJPY".equals(obj.getString("symbol"))) {
setUsdJpyRate(new BigDecimal(obj.getDouble("price")).setScale(2, RoundingMode.DOWN));
log.info(obj.toString());
} else if ("USDHKD".equals(obj.getString("symbol"))) {
setUsdHkdRate(new BigDecimal(obj.getDouble("price")).setScale(2, RoundingMode.DOWN));
log.info(obj.toString());
} else if("SGDCNH".equals(obj.getString("symbol"))){
setSgdCnyRate(new BigDecimal(obj.getDouble("price")).setScale(2,RoundingMode.DOWN));
log.info(obj.toString());
}
});
}
public static Hashtable<String, Integer> loadToken() {
Hashtable<String, Integer> tokens = new Hashtable<>(ValueConsts.SIXTEEN_INT);
try {
String token = FileExecutor.readFile(SettingConfig.getStoragePath(ConfigConsts.TOKEN_OF_SETTINGS));
JSONArray array = JSON.parseArray(token);
array.forEach(object -> {
JSONObject jsonObject = (JSONObject) object;
tokens.put(jsonObject.getString(ValueConsts.KEY_STRING), jsonObject.getInteger(ValueConsts
.VALUE_STRING));
});
} catch (Exception e) {
logger.error("load token error: " + e.getMessage());
}
return tokens;
}
private void addRoles(String userId){
String roleIds = getParaString("roleIds");
if(StrUtil.isNotBlank(roleIds)){
JSONArray ids = JSONArray.parseArray(roleIds);
ids.forEach(id -> {
Record record = Record.empty();
record.set(AoomsVar.ID,IDGenerator.getStringValue());
record.set("user_id",userId);
record.set("role_id",id);
record.set("create_time",DateUtil.now());
db.insert("aooms_rbac_userrole", record);
});
}
}
/**
* 初始化
*/
public CustomConfig(JSONObject object) {
super();
this.overrideFile = object.getBoolean("overrideFile");
JSONArray array = object.getJSONArray("tableItem");
if (array != null) {
array.forEach(v -> {
tableItem.add(new TableAttributeKeyValueTemplate((JSONObject) v));
});
}
}
/**
* 初始化
*/
public CustomConfig(JSONObject object) {
super();
this.overrideFile = object.getBoolean("overrideFile");
JSONArray array = object.getJSONArray("tableItem");
if (array != null) {
array.forEach(v -> {
tableItem.add(new TableAttributeKeyValueTemplate((JSONObject) v));
});
}
}
public static List<String> getQueries() {
List<String> strs = new ArrayList<>();
JSONArray jsonArray = jo.getJSONArray("queries");
if (jsonArray == null) {
return strs;
}
jsonArray.forEach(s -> strs.add(s.toString()));
return strs;
}
@RequestMapping(value = "save.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@Feature(method = MethodFeature.EDIT)
@OptLog(value = UserOperateLogV1.OptType.EditRole)
public String save(String id,
@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "请输入角色名称") String name,
@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "请输入选择权限") String feature) {
JSONArray jsonArray = JSONArray.parseArray(feature);
RoleModel item = roleService.getItem(id);
if (item == null) {
item = new RoleModel();
item.setId(IdUtil.fastSimpleUUID());
}
item.setName(name);
List<RoleModel.RoleFeature> roleFeatures = new ArrayList<>();
jsonArray.forEach(o -> {
JSONObject jsonObject = (JSONObject) o;
JSONArray children = jsonObject.getJSONArray("children");
if (children == null || children.isEmpty()) {
return;
}
String id1 = jsonObject.getString("id");
ClassFeature classFeature = ClassFeature.valueOf(id1);
RoleModel.RoleFeature roleFeature = new RoleModel.RoleFeature();
roleFeature.setFeature(classFeature);
roleFeatures.add(roleFeature);
//
List<MethodFeature> methodFeatures = new ArrayList<>();
children.forEach(o1 -> {
JSONObject childrenItem = (JSONObject) o1;
String id11 = childrenItem.getString("id");
id11 = id11.substring(id1.length() + 1);
MethodFeature methodFeature = MethodFeature.valueOf(id11);
methodFeatures.add(methodFeature);
});
roleFeature.setMethodFeatures(methodFeatures);
});
item.setFeatures(roleFeatures);
//
if (StrUtil.isNotEmpty(id)) {
roleService.updateItem(item);
} else {
roleService.addItem(item);
}
return JsonMessage.getString(200, "操作成功");
}
/**
* 增加或修改监控
*
* @param id id
* @param name name
* @param notifyUser user
* @return json
*/
@RequestMapping(value = "updateMonitor", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@OptLog(UserOperateLogV1.OptType.EditMonitor)
@Feature(method = MethodFeature.EDIT)
public String updateMonitor(String id,
@ValidatorConfig(@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "监控名称不能为空")) String name,
String notifyUser) {
int cycle = getParameterInt("cycle", Cycle.five.getCode());
String status = getParameter("status");
String autoRestart = getParameter("autoRestart");
JSONArray jsonArray = JSONArray.parseArray(notifyUser);
List<String> notifyUsers = jsonArray.toJavaList(String.class);
if (notifyUsers == null || notifyUsers.isEmpty()) {
return JsonMessage.getString(405, "请选择报警联系人");
}
String projects = getParameter("projects");
JSONArray projectsArray = JSONArray.parseArray(projects);
if (projectsArray == null || projectsArray.size() <= 0) {
return JsonMessage.getString(400, "请至少选择一个项目");
}
boolean start = "on".equalsIgnoreCase(status);
MonitorModel monitorModel = monitorService.getItem(id);
if (monitorModel == null) {
monitorModel = new MonitorModel();
}
//
List<MonitorModel.NodeProject> nodeProjects = new ArrayList<>();
projectsArray.forEach(o -> {
JSONObject jsonObject = (JSONObject) o;
nodeProjects.add(jsonObject.toJavaObject(MonitorModel.NodeProject.class));
});
monitorModel.setAutoRestart("on".equalsIgnoreCase(autoRestart));
monitorModel.setCycle(cycle);
monitorModel.setProjects(nodeProjects);
monitorModel.setStatus(start);
monitorModel.setNotifyUser(notifyUsers);
monitorModel.setName(name);
if (StrUtil.isEmpty(id)) {
//添加监控
id = IdUtil.objectId();
UserModel user = getUser();
monitorModel.setId(id);
monitorModel.setParent(UserModel.getOptUserName(user));
monitorService.addItem(monitorModel);
return JsonMessage.getString(200, "添加成功");
}
monitorService.updateItem(monitorModel);
return JsonMessage.getString(200, "修改成功");
}
@Override
public JSONObject remove(JSONObject object) {
JSONArray array = object.getJSONArray("items");
array.forEach(file -> FileExecutor.deleteFile(file.toString()));
return getBasicResponse(ValueConsts.TRUE);
}
private void initConsumer(JSONArray topicInfos) throws Exception {
// 初始化数据consumer
int taskIndex = context.getThisTaskIndex();
int spoutSize = context.getComponentTasks(context.getThisComponentId()).size();
List<String> allTopics = inner.sourceTopics;
List<String> topicList = getResultTopics(allTopics, taskIndex, spoutSize);
logger.info("[kafka read spout] will init consumer with task index: {}, spout size: {}, topics: {} ", taskIndex, spoutSize, topicList);
Properties properties = inner.zkHelper.loadSinkerConf(SinkerConstants.CONSUMER);
properties.put("client.id", inner.sinkerName + "SinkerKafkaReadClient_" + taskIndex);
this.consumer = new KafkaConsumer<>(properties);
Map<String, List<PartitionInfo>> topicsMap = consumer.listTopics();
List<TopicPartition> topicPartitions = new ArrayList<>();
topicList.forEach(topic -> {
List<PartitionInfo> partitionInfos = topicsMap.get(topic);
if (partitionInfos != null && !partitionInfos.isEmpty()) {
partitionInfos.forEach(partitionInfo -> topicPartitions.add(new TopicPartition(topic, partitionInfo.partition())));
} else {
topicPartitions.add(new TopicPartition(topic, 0));
}
});
consumer.assign(topicPartitions);
if (topicInfos != null) {
topicInfos.forEach(info -> {
JSONObject topicInfo = (JSONObject) info;
if (topicList.contains(topicInfo.getString("topic"))) {
TopicPartition topicPartition = new TopicPartition(topicInfo.getString("topic"), topicInfo.getInteger("partition"));
consumer.seek(topicPartition, topicInfo.getLong("position"));
}
});
}
logger.info("[kafka read spout] init consumer success with task index: {}, spout size: {}, topicPartitions: {} ", taskIndex, spoutSize, topicPartitions);
// 初始化 commitInfoMap
this.commitInfoMap = new HashMap<>();
topicPartitions.forEach(topicPartition -> {
commitInfoMap.put(topicPartition.topic() + "-" + topicPartition.partition(), System.currentTimeMillis());
});
// 初始化ctrl consumer
logger.info("[kafka read spout] will init ctrl consumer with task index: {},topic: {} ", taskIndex, getCtrlTopic());
properties.put("group.id", inner.sinkerName + "SinkerCtrlGroup_" + taskIndex);
properties.put("client.id", inner.sinkerName + "SinkerCtrlClient_" + taskIndex);
//ctrl topic不跟踪消息处理
properties.put("enable.auto.commit", true);
this.ctrlConsumer = new KafkaConsumer<>(properties);
List<TopicPartition> ctrlTopicPartitions = Collections.singletonList(new TopicPartition(getCtrlTopic(), 0));
ctrlConsumer.assign(ctrlTopicPartitions);
ctrlConsumer.seekToEnd(Collections.singletonList(new TopicPartition(getCtrlTopic(), 0)));
logger.info("[kafka read spout] init ctrl consumer success with task index: {}, topicPartitions: {} ", taskIndex, ctrlTopicPartitions);
}
/**
* 将JSON集合,合并到数组的JSON集合
* <p>
* 以条件key获得JSONObject数组中每个对象的value作为JSON对象的key,然后进行合并。<br>
* JSON对象key获得的值,应该是一个JSONObject对象<br>
* </p>
* <blockquote>示例:
* <pre>
* JSONArray array = [
* {
* "id": 1,
* "name": "name"
* }
* ]
* JSONObject json = {
* 1: {
* "sex": "男",
* "age": 18
* }
* }
*
* String key = "id";
*
* JSONArray mergeResult = merge(array, json, key);
* System.out.println(mergeResult);
* </pre>
* 结果:
* [{"id": 1, "name": "name", "sex": "男", "age": 18}]
* </blockquote>
* @param array JSONObject数组
* @param json JSON对象
* @param key 条件
* @return 合并后的JSONArray
*/
public static JSONArray merge(JSONArray array, JSONObject json, String key) {
array.forEach(arrayObj -> {
JSONObject temp = Convert.toJSONObject(arrayObj);
String value = temp.getString(key);
temp.putAll(json.getJSONObject(value));
});
return array;
}