Java Code Examples for com.alibaba.fastjson.JSONArray#addAll()

The following examples show how to use com.alibaba.fastjson.JSONArray#addAll() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NodeModel.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 返回按照项目分组 排列的数组
 *
 * @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;
}
 
Example 2
Source File: DataTransactionFactory.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 创建请求 order 报文 分装成JSON
 * @param appId
 * @return
 */
public static String createCenterServiceRequestJson(String appId,String userId,String orderTypeCd,String sign,String remark,
                                                    JSONArray orderAttrs,JSONArray businesses){
    JSONObject paramIn = JSONObject.parseObject("{\"orders\":{},\"business\":[]}");
    JSONObject orders = paramIn.getJSONObject("orders");
    orders.put("appId",appId);
    orders.put("transactionId", GenerateCodeFactory.getTransactionId());
    orders.put("userId",userId);
    orders.put("orderTypeCd",orderTypeCd);
    orders.put("requestTime",DateUtil.getNowDefault());
    orders.put("remark",remark);
    if(orderAttrs != null && orderAttrs.size()>0) {
        orders.put("attrs", orderAttrs);
    }
    JSONArray businessArray = paramIn.getJSONArray("business");
    businessArray.addAll(businesses);

    if(!StringUtil.isNullOrNone(sign)) {
        orders.put("sign", AuthenticationFactory.md5(orders.getString("transactionId"), orders.getString("appId"),
                businessArray.toJSONString(), sign));
    }
    return paramIn.toJSONString();
}
 
Example 3
Source File: MysqlDialect.java    From yue-library with Apache License 2.0 5 votes vote down vote up
@Override
public PageBeforeAndAfterVO pageBeforeAndAfter(String querySql, PageIPO pageIPO, Long equalsId) {
	// 1. 参数校验
	if (StringUtils.isEmpty(querySql)) {
		throw new DbException("querySql不能为空");
	}
	
	// 2. 查询数据
	JSONArray array = new JSONArray();
	array.addAll(namedParameterJdbcTemplate.queryForList(querySql, toParamJson(pageIPO)));
	int size = array.size();
	
	// 3. 获得前后值
	Long beforeId = null;
	Long afterId = null;
	String key = DbConstant.PRIMARY_KEY;
	for (int i = 0; i < size; i++) {
		JSONObject json = array.getJSONObject(i);
		// 比较列表中相等的值,然后获取前一条与后一条数据
		if (equalsId.equals(json.getLong(key))) {
			if (i != 0) {// 不是列表中第一条数据
				beforeId = array.getJSONObject(i - 1).getLong(key);
			}
			if (i != size - 1) {// 不是列表中最后一条数据
				afterId = array.getJSONObject(i + 1).getLong(key);
			}
			break;
		}
	}
	
	// 4. 返回结果
	return PageBeforeAndAfterVO.builder()
	.beforeId(beforeId)
	.afterId(afterId)
	.build();
}
 
Example 4
Source File: ExceptionFormatter.java    From xian with Apache License 2.0 5 votes vote down vote up
private static JSONArray stackTraceToJSONArray(Throwable throwable, boolean isCause) {
    JSONArray stackTraceArray = new JSONArray();
    if (isCause) {
        stackTraceArray.add("Caused by: " + throwable.toString());
    } else {
        stackTraceArray.add(throwable.toString());
    }
    for (StackTraceElement stackTraceElement : throwable.getStackTrace()) {
        stackTraceArray.add("   " + stackTraceElement.toString());
    }
    if (throwable.getCause() != null) {
        stackTraceArray.addAll(stackTraceToJSONArray(throwable.getCause(), true));
    }
    return stackTraceArray;
}
 
Example 5
Source File: GrafanaTest.java    From xian with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    JSONArray falconBeans = new JSONArray();

    JSONObject factors = FactorCollector.collect();
    for (String metric : factors.keySet())
        falconBeans.addAll(new FalconBeanBuilder().buildAll(metric, factors.get(metric)));

    GrafanaService.grafana(falconBeans);
}
 
Example 6
Source File: RealityLiveService.java    From Alice-LiveMan with GNU Affero General Public License v3.0 5 votes vote down vote up
private void refreshStreamUsers() throws IOException, URISyntaxException {
    log.info("刷新Reality用户列表...");
    URI listStreamerUrl = new URI(LIST_STREAMER_OFFICIAL);
    JSONObject officialUsers = JSON.parseObject(HttpRequestUtil.downloadUrl(listStreamerUrl, null, "{\"official\":\"1\"}", StandardCharsets.UTF_8));
    JSONArray streamerUsers = officialUsers.getJSONObject("payload").getJSONArray("StreamerUsers");
    JSONObject unofficialUsers = JSON.parseObject(HttpRequestUtil.downloadUrl(listStreamerUrl, null, "{\"official\":\"2\"}", StandardCharsets.UTF_8));
    streamerUsers.addAll(unofficialUsers.getJSONObject("payload").getJSONArray("StreamerUsers"));
    JSONObject bangumiUsers = JSON.parseObject(HttpRequestUtil.downloadUrl(listStreamerUrl, null, "{\"official\":\"3\"}", StandardCharsets.UTF_8));
    streamerUsers.addAll(bangumiUsers.getJSONObject("payload").getJSONArray("StreamerUsers"));
    for (int i = 0; i < streamerUsers.size(); i++) {
        JSONObject streamerUser = streamerUsers.getJSONObject(i);
        streamerUsersMap.put(streamerUser.getString("nickname"), streamerUser);
    }
    lastRefreshTime = System.currentTimeMillis();
}
 
Example 7
Source File: AbstractServiceApiPlusListener.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
     * 合并服务 拼接最终报文
     *
     * @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());
    }
 
Example 8
Source File: Json.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Object toJson(Object obj) {
	if (obj != null) {
		if (obj instanceof Collection) {
			JSONArray json = new JSONArray();
			json.addAll((Collection<? extends Object>) obj);
			return json;
		} else if (obj instanceof Map) {
			return new JSONObject((Map<String, Object>) obj);
		}
	}
	return obj;
}
 
Example 9
Source File: ProcessInstanceHighlightsResource.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
@GetMapping(value = "/process-instance/{processInstanceId}/highlights", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Object getHighlighted(@PathVariable String processInstanceId) {

    JSONObject responseJSON = new JSONObject();

    responseJSON.put("processInstanceId", processInstanceId);

    JSONArray activitiesArray = new JSONArray();
    JSONArray flowsArray = new JSONArray();

    HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery()
            .processInstanceId(processInstanceId)
            .singleResult();
    ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) repositoryService
            .getProcessDefinition(processInstance.getProcessDefinitionId());

    responseJSON.put("processDefinitionId", processInstance.getProcessDefinitionId());
    List<String> highLightedActivities;
    if (processInstance.getEndTime() != null) {
        highLightedActivities = historyService
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .activityType("endEvent")
                .list().stream().map(HistoricActivityInstance::getActivityId)
                .collect(Collectors.toList());
    } else {
        highLightedActivities = runtimeService.getActiveActivityIds(processInstanceId);
    }
    List<String> highLightedFlows = getHighLightedFlows(processDefinition, processInstanceId);

    activitiesArray.addAll(highLightedActivities);

    flowsArray.addAll(highLightedFlows);


    responseJSON.put("activities", activitiesArray);
    responseJSON.put("flows", flowsArray);

    return responseJSON;
}
 
Example 10
Source File: LoginServiceImpl.java    From xiaoV with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void webWxGetContact() {
	String url = String.format(URLEnum.WEB_WX_GET_CONTACT.getUrl(), core
			.getLoginInfo().get(StorageLoginInfoEnum.url.getKey()));
	Map<String, Object> paramMap = core.getParamMap();
	HttpEntity entity = httpClient.doPost(url, JSON.toJSONString(paramMap));

	try {
		String result = EntityUtils.toString(entity, Consts.UTF_8);
		// System.out.println("webWxGetContact:" + result);//CPP
		JSONObject fullFriendsJsonList = JSON.parseObject(result);
		// 查看seq是否为0,0表示好友列表已全部获取完毕,若大于0,则表示好友列表未获取完毕,当前的字节数(断点续传)
		long seq = 0;
		long currentTime = 0L;
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		if (fullFriendsJsonList.get("Seq") != null) {
			seq = fullFriendsJsonList.getLong("Seq");
			currentTime = new Date().getTime();
		}
		core.setMemberCount(fullFriendsJsonList
				.getInteger(StorageLoginInfoEnum.MemberCount.getKey()));
		JSONArray member = fullFriendsJsonList
				.getJSONArray(StorageLoginInfoEnum.MemberList.getKey());
		// 循环获取seq直到为0,即获取全部好友列表 ==0:好友获取完毕 >0:好友未获取完毕,此时seq为已获取的字节数
		while (seq > 0) {
			// 设置seq传参
			params.add(new BasicNameValuePair("r", String
					.valueOf(currentTime)));
			params.add(new BasicNameValuePair("seq", String.valueOf(seq)));
			entity = httpClient.doGet(url, params, false, null);

			params.remove(new BasicNameValuePair("r", String
					.valueOf(currentTime)));
			params.remove(new BasicNameValuePair("seq", String.valueOf(seq)));

			result = EntityUtils.toString(entity, Consts.UTF_8);
			fullFriendsJsonList = JSON.parseObject(result);

			if (fullFriendsJsonList.get("Seq") != null) {
				seq = fullFriendsJsonList.getLong("Seq");
				currentTime = new Date().getTime();
			}

			// 累加好友列表
			member.addAll(fullFriendsJsonList
					.getJSONArray(StorageLoginInfoEnum.MemberList.getKey()));
		}
		core.setMemberCount(member.size());
		for (Iterator<?> iterator = member.iterator(); iterator.hasNext();) {
			JSONObject o = (JSONObject) iterator.next();
			if ((o.getInteger("VerifyFlag") & 8) != 0) { // 公众号/服务号
				core.getPublicUsersList().add(o);
			} else if (Config.API_SPECIAL_USER.contains(o
					.getString("UserName"))) { // 特殊账号
				core.getSpecialUsersList().add(o);
			} else if (o.getString("UserName").indexOf("@@") != -1) { // 群聊
				if (!core.getGroupIdList()
						.contains(o.getString("UserName"))) {
					core.getGroupNickNameList()
							.add(o.getString("NickName"));
					core.getGroupIdList().add(o.getString("UserName"));
					core.getGroupList().add(o);
				}
			} else if (o.getString("UserName").equals(
					core.getUserSelf().getString("UserName"))) { // 自己
				core.getContactList().remove(o);
			} else { // 普通联系人
				core.getContactList().add(o);
			}
		}
		return;
	} catch (Exception e) {
		LOG.error(e.getMessage(), e);
	}
	return;
}
 
Example 11
Source File: ClientServiceRedisImpl.java    From kkbinlog with Apache License 2.0 4 votes vote down vote up
@Override
public String getqueuesize(String clientName,String type,int page) {
    int repage=10*(page-1);

    JSONObject object = new JSONObject();
    String ClientId;
    if (ClientInfo.QUEUE_TYPE_REDIS.equals(type)) {
            ClientId="BIN-LOG-DATA-".concat(clientName);
            object.put("queueSize",redissonClient.getList(ClientId).size());
            object.put("queue",redissonClient.getList(ClientId)
                    .get(repage,repage+1,repage+2,repage+3,repage +4,repage+5,repage+6,repage+7,repage+8,repage+9));
            return object.toJSONString();
    } else if (ClientInfo.QUEUE_TYPE_RABBIT.equals(type)) {
            ClientId="BIN-LOG-DATA-".concat(clientName);
            QueueInfo queueInfo = rabbitMQService.getQueue(ClientId);
            if (queueInfo == null || new Long(0L).equals(queueInfo.getMessagesReady())) {
                object.put("queueSize", 0);
                object.put("queue", new ArrayList<>());
                return object.toJSONString();
            } else {
                long queueSize = queueInfo.getMessagesReady();
                long count = (repage + 10) > queueSize ? queueSize : (repage + 10);
                List<EventBaseDTO> list = rabbitMQService.getMessageList(ClientId, count);
                list = list.subList(repage, list.size());
                object.put("queueSize", queueSize);
                object.put("queue", list);
                return object.toJSONString();
            }
    } else if (ClientInfo.QUEUE_TYPE_KAFKA.equals(type)) {

            // TODO 增加Kafka队列查询
            object.put("queueSize", 0);
            object.put("queue",new ArrayList<>());
            return object.toJSONString();

    } else {
            ClientId=clientName;
            object.put("queueSize",redissonClient.getMap(ClientId).size());
            RMap<String, JSONObject> map = redissonClient.getMap(ClientId,new JsonJacksonMapCodec(String.class,JSONObject.class));
            Collection<JSONObject> values = map.values();
            JSONArray array1 = new JSONArray();
            array1.addAll(values);
            object.put("queue",array1);
            return object.toJSONString();
    }
}
 
Example 12
Source File: GeneratorViewComponent.java    From MicroCommunity with Apache License 2.0 4 votes vote down vote up
/**
 * 生成 html js java 类
 *
 * @param data
 */
private void generatorComponentHtml(JSONObject data) {

    StringBuffer sb = readFile(GeneratorStart.class.getResource("/web/view/viewInfo.html").getFile());
    String fileContext = sb.toString();

    fileContext = super.replaceTemplateContext(fileContext, data);

    // 处理 th 信息

    StringBuffer thSb = new StringBuffer();

    JSONArray columns = data.getJSONArray("columns");

    JSONArray cols = new JSONArray();
    JSONObject col = new JSONObject();
    col.put("cnCode", data.getString("templateKeyName"));
    col.put("code", data.getString("templateKey"));
    cols.addAll(columns);
    for (int columnIndex = 0; columnIndex < cols.size(); columnIndex++) {
        JSONObject column = cols.getJSONObject(columnIndex);
        if (columnIndex % 3 == 0) {
            thSb.append("<div class=\"row\">\n");
        }

        thSb.append("<div class=\"col-sm-4\">\n" +
                "                        <div class=\"form-group\">\n" +
                "                            <label class=\"col-form-label\" >" + column.getString("cnCode") + ":</label>\n" +
                "                            <label class=\"\">{{view" + toUpperCaseFirstOne(data.getString("templateCode")) + "Info." + column.getString("code") + "}}</label>\n" +
                "                        </div>\n" +
                "</div>\n");

        if (columnIndex % 3 == 2 || columnIndex == columns.size() - 1) {
            thSb.append("</div>\n");
        }

    }

    fileContext = fileContext.replace("@@viewInfo@@", thSb.toString());


    String writePath = this.getClass().getResource("/").getPath()
            + "out/web/components/" + data.getString("directories") + "/view" + toUpperCaseFirstOne(data.getString("templateCode")) + "Info/view" + toUpperCaseFirstOne(data.getString("templateCode")) + "Info.html";
    System.out.printf("writePath: " + writePath);
    writeFile(writePath,
            fileContext);


}
 
Example 13
Source File: PdfReaderImpl.java    From tephra with MIT License 4 votes vote down vote up
private void merge(JSONArray elements, JSONArray array) {
    if (!array.isEmpty())
        elements.addAll(array);
}
 
Example 14
Source File: MirrorMakerManagerRestletResource.java    From uReplicator with Apache License 2.0 4 votes vote down vote up
@Override
@Get
public Representation get() {
  final String instanceName = (String) getRequest().getAttributes().get("instanceName");
  try {
    JSONObject responseJson = new JSONObject();

    PriorityQueue<InstanceTopicPartitionHolder> currentServingInstance = _helixMirrorMakerManager
        .getCurrentServingInstance();
    WorkloadInfoRetriever workloadRetriever = _helixMirrorMakerManager.getWorkloadInfoRetriever();
    Iterator<InstanceTopicPartitionHolder> iter = currentServingInstance.iterator();
    JSONObject instanceMapJson = new JSONObject();
    while (iter.hasNext()) {
      InstanceTopicPartitionHolder instance = iter.next();
      String name = instance.getInstanceName();
      if (instanceName == null || instanceName.equals(name)) {
        if (!instanceMapJson.containsKey(name)) {
          instanceMapJson.put(name, new JSONArray());
        }
        double totalWorkload = 0;
        for (TopicPartition tp : instance.getServingTopicPartitionSet()) {
          double tpw = workloadRetriever.topicWorkload(tp.getTopic()).getBytesPerSecondPerPartition();
          totalWorkload += tpw;
          instanceMapJson.getJSONArray(name).add(tp.getTopic() + "." + tp.getPartition() + ":" + Math.round(tpw));
        }
        instanceMapJson.getJSONArray(name).add("TOTALWORKLOAD." + instance.getServingTopicPartitionSet().size()
            + ":" + Math.round(totalWorkload));
      }
    }
    responseJson.put("instances", instanceMapJson);

    JSONArray blacklistedArray = new JSONArray();
    blacklistedArray.addAll(_helixMirrorMakerManager.getBlacklistedInstances());
    responseJson.put("blacklisted", blacklistedArray);

    JSONArray allInstances = new JSONArray();
    allInstances.addAll(_helixMirrorMakerManager.getCurrentLiveInstanceNames());
    responseJson.put("allInstances", allInstances);

    return new StringRepresentation(responseJson.toJSONString());
  } catch (Exception e) {
    LOGGER.error("Got error during processing Get request", e);
    getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
    return new StringRepresentation(String
        .format("Failed to get serving topics for %s, with exception: %s",
            instanceName == null ? "all instances" : instanceName, e));
  }
}