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

The following examples show how to use com.alibaba.fastjson.JSONArray#size() . 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: ExcelImpl.java    From tephra with MIT License 6 votes vote down vote up
@Override
public void write(String[] titles, String[] names, JSONArray array, OutputStream outputStream) {
    try (Workbook workbook = new HSSFWorkbook()) {
        Sheet sheet = workbook.createSheet();
        Row row = sheet.createRow(0);
        for (int i = 0; i < titles.length; i++)
            row.createCell(i).setCellValue(titles[i]);
        for (int i = 0, size = array.size(); i < size; i++) {
            JSONObject object = array.getJSONObject(i);
            row = sheet.createRow(i + 1);
            for (int j = 0; j < names.length; j++)
                row.createCell(j).setCellValue(converter.toString(object.get(names[j])));
        }
        workbook.write(outputStream);
        outputStream.close();
    } catch (IOException e) {
        logger.warn(e, "输出Excel文档时发生异常!");
    }
}
 
Example 2
Source File: UserApplicationController.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/userApp/deleteUserApp")
public void deleteUserApp(Model model, @RequestBody JSONArray jsonArray) {

	try {
		String userId = UserUtils.getCurrentUserId();
		StringUtils.isValidString(userId, "账号没有登录");

		StringUtils.isValidObject(jsonArray, "参数错误");
		List<Integer> ids = new ArrayList<>(jsonArray.size());
		for (int i = 0; i < jsonArray.size(); i++) {
			ids.add(jsonArray.getJSONObject(i).getInteger("id"));
		}
		CommonResponseDto response = userApplicationService
				.deleteApplication(userId, ids);
		if (response == null
				|| response.getResult() != UserConstant.SUCCESS) {
			throw new VerificationException(response.getErrorMessage());
		} else {
			model.addAttribute("success", true);
		}
	} catch (VerificationException e) {
		model.addAttribute("success", false);
		model.addAttribute("error", e.getMessage());
	}
}
 
Example 3
Source File: FlushAboutCommentIdListener.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 刷新 subCommentId
 *
 * @param data 数据节点
 */
private void flushSubCommentId(JSONObject data){

    String subCommentId = GenerateCodeFactory.getSubCommentId();
    JSONObject subComment = data.getJSONObject("subComment");
    subComment.put("subCommentId",subCommentId);
    //刷评论属性
    if(data.containsKey("subCommentAttr")) {
        JSONArray subCommentAttrs = data.getJSONArray("subCommentAttr");
        for(int subCommentAttrIndex = 0;subCommentAttrIndex < subCommentAttrs.size();subCommentAttrIndex++) {
            JSONObject subCommentAttr = subCommentAttrs.getJSONObject(subCommentAttrIndex);
            subCommentAttr.put("subCommentId", subCommentId);
        }
    }

    //刷照片
    if(data.containsKey("subCommentPhoto")) {
        JSONArray subCommentPhotos = data.getJSONArray("subCommentPhoto");
        for(int subCommentPhotoIndex = 0;subCommentPhotoIndex < subCommentPhotos.size();subCommentPhotoIndex++) {
            JSONObject subCommentPhoto = subCommentPhotos.getJSONObject(subCommentPhotoIndex);
            subCommentPhoto.put("subCommentId", subCommentId);
        }
    }
}
 
Example 4
Source File: SimpleHintParser.java    From tddl with Apache License 2.0 6 votes vote down vote up
public static RouteCondition decodeDirect(JSONObject jsonObject) {
    DirectlyRouteCondition rc = new DirectlyRouteCondition();
    decodeExtra(rc, jsonObject);
    String tableString = containsKvNotBlank(jsonObject, REALTABS);
    if (tableString != null) {
        JSONArray jsonTables = JSON.parseArray(tableString);
        // 设置table的Set<String>
        if (jsonTables.size() > 0) {
            Set<String> tables = new HashSet<String>(jsonTables.size());
            for (int i = 0; i < jsonTables.size(); i++) {
                tables.add(jsonTables.getString(i));
            }
            rc.setTables(tables);
            // direct只需要在实际表有的前提下解析即可。
            decodeVtab(rc, jsonObject);
        }
    }

    String dbId = containsKvNotBlank(jsonObject, DBID);
    if (dbId == null) {
        throw new RuntimeException("hint contains no property 'dbid'.");
    }

    rc.setDBId(dbId);
    return rc;
}
 
Example 5
Source File: BindingServiceListener.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
@Override
protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {

    JSONArray infos = reqJson.getJSONArray("data");

    Assert.hasKeyByFlowData(infos, "addRouteView", "orderTypeCd", "必填,请填写订单类型");
    Assert.hasKeyByFlowData(infos, "addRouteView", "invokeLimitTimes", "必填,请填写调用次数");
    Assert.hasKeyByFlowData(infos, "addRouteView", "invokeModel", "可填,请填写消息队列,订单在异步调用时使用");

    if(infos == null || infos.size() !=3){
        throw new IllegalArgumentException("请求参数错误,为包含 应用,服务或扩展信息");
    }
}
 
Example 6
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 7
Source File: Permission.java    From evt4j with MIT License 5 votes vote down vote up
@NotNull
public static Permission ofRaw(@NotNull JSONObject raw) {
    Objects.requireNonNull(raw);
    String name = raw.getString("name");
    int threshold = raw.getInteger("threshold");
    List<AuthorizerWeight> authorizers = new ArrayList<>();
    JSONArray authorizersArray = raw.getJSONArray("authorizers");

    for (int i = 0; i < authorizersArray.size(); i++) {
        authorizers.add(AuthorizerWeight.ofRaw((JSONObject) authorizersArray.get(i)));
    }

    return new Permission(name, threshold, authorizers);
}
 
Example 8
Source File: ZkHelper.java    From sofa-dashboard with Apache License 2.0 5 votes vote down vote up
/**
 * 从 ZK 获取   apps/biz/
 * @param appName
 * @param ip
 * @param pluginName
 * @param version
 * @return
 */
public String getAppState(String appName, String ip, String pluginName, String version)
                                                                                       throws Exception {
    String bizPath = SofaDashboardConstants.SOFA_BOOT_CLIENT_ROOT
                     + SofaDashboardConstants.SOFA_BOOT_CLIENT_BIZ;
    CuratorFramework curatorClient = zkCommandClient.getCuratorClient();
    if (curatorClient.checkExists().forPath(bizPath) != null) {
        String bizAppPath = bizPath + SofaDashboardConstants.SEPARATOR + appName
                            + SofaDashboardConstants.SEPARATOR + ip;
        if (curatorClient.checkExists().forPath(bizAppPath) != null) {
            byte[] bytes = curatorClient.getData().forPath(bizAppPath);
            String data = new String(bytes);
            JSONObject json = JSON.parseObject(data);
            String bizInfos = FastJsonUtils.getString(json, "bizInfos");
            JSONArray array = JSONArray.parseArray(bizInfos);
            for (int i = 0; i < array.size(); i++) {
                JSONObject item = array.getJSONObject(i);
                String bizName = FastJsonUtils.getString(item, "bizName");
                String bizVersion = FastJsonUtils.getString(item, "bizVersion");
                if (bizName.equalsIgnoreCase(pluginName)
                    && bizVersion.equalsIgnoreCase(version)) {
                    return FastJsonUtils.getString(item, "bizState");
                }
            }
        }
    }
    return "";
}
 
Example 9
Source File: MediaController.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/admin/media/checkMovies")
public void checkMovies(Model model, @RequestBody JSONArray jsonArray) {
	try {
		String userId = UserUtils.getCurrentUserId();
		StringUtils.isValidString(userId, "账号没有登录");

		StringUtils.isValidObject(jsonArray, "参数错误");

		List<Long> ids = new ArrayList<>(jsonArray.size());

		for (int i = 0; i < jsonArray.size(); i++) {
			ids.add(jsonArray.getJSONObject(i).getLong("id"));
		}

		log.debug("管理员[" + userId + "]正在审核视频.");
		CommonResponseDto response = movieService.checkMovies(userId, ids);

		if (response == null
				|| response.getResult() != UserConstant.SUCCESS) {
			throw new VerificationException(response.getErrorMessage());
		} else {
			model.addAttribute("success", true);
		}

	} catch (VerificationException e) {
		model.addAttribute("success", false);
		model.addAttribute("error", e.getMessage());
	}
}
 
Example 10
Source File: GeneratorEditComponent.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 生成API 侦听处理类
 *
 * @param data
 */
private void genneratorListListener(JSONObject data) {
    StringBuffer sb = readFile(GeneratorStart.class.getResource("/web/edit/UpdateListener.java").getFile());
    String fileContext = sb.toString();

    fileContext = super.replaceTemplateContext(fileContext, data);

    //替换校验部分代码 @@validateTemplateColumns@@
    JSONArray columns = data.getJSONArray("columns");
    StringBuffer validateStr = new StringBuffer();
    validateStr.append("Assert.hasKeyAndValue(reqJson, \"" + data.getString("templateKey") + "\", \"" + data.getString("templateKeyName") + "不能为空\");\n");
    for (int columnIndex = 0; columnIndex < columns.size(); columnIndex++) {
        JSONObject column = columns.getJSONObject(columnIndex);
        if (column.getBoolean("required")) {
            validateStr.append("Assert.hasKeyAndValue(reqJson, \"" + column.getString("code") + "\", \"" + column.getString("desc") + "\");\n");
        }
    }

    fileContext = fileContext.replace("@@validateTemplateColumns@@", validateStr.toString());


    String writePath = this.getClass().getResource("/").getPath()
            + "out/api/listener/" + data.getString("templateCode") + "/Update" + toUpperCaseFirstOne(data.getString("templateCode")) + "Listener.java";
    System.out.printf("writePath: " + writePath);
    writeFile(writePath,
            fileContext);
}
 
Example 11
Source File: JsonCommand.java    From Okra with Apache License 2.0 5 votes vote down vote up
private Object[] createParams(Session session, String data) {
    Object[] args = new Object[]{session};
    try {
        JSONArray array = JSONArray.parseArray(data);
        args = new Object[array.size() + 1];
        args[0] = session;
        Class<?>[] parameterTypes = method.getParameterTypes();
        for (int i = 1; i < parameterTypes.length; i++) {
            args[i] = array.getObject(i - 1, parameterTypes[i]);
        }
    } catch (Exception e) {
        LOG.error("Build param failed.", e);
    }
    return args;
}
 
Example 12
Source File: ContractEventParserJson.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * parse Event Topic into map NOTICE: In solidity, Indexed Dynamic types's topic is just
 * EVENT_INDEXED_ARGS
 */
public static Map<String, String> parseTopics(List<byte[]> topicList, JSONObject entry) {
    Map<String, String> map = new HashMap<>();
    if (topicList == null || topicList.isEmpty()) {
        return map;
    }

    // the first is the signature.
    int index = 1;
    JSONArray inputs = entry.getJSONArray(INPUTS);

    // in case indexed topics doesn't match
    if (topicsMatched(topicList, entry)) {
        if (inputs != null) {
            for (int i = 0; i < inputs.size(); ++i) {
                JSONObject param = inputs.getJSONObject(i);
                if (param != null) {
                    Boolean indexed = param.getBoolean(INDEXED);
                    if (indexed == null || !indexed) {
                        continue;
                    }
                    if (index >= topicList.size()) {
                        break;
                    }
                    String str = parseTopic(topicList.get(index++), param.getString("type"));
                    if (StringUtils.isNotNullOrEmpty(param.getString("name"))) {
                        map.put(param.getString("name"), str);
                    }
                    map.put("" + i, str);
                }
            }
        }
    } else {
        for (int i = 1; i < topicList.size(); ++i) {
            map.put("" + (i - 1), Hex.toHexString(topicList.get(i)));
        }
    }
    return map;
}
 
Example 13
Source File: RpcClient.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 
 * @description 根据哈希数组批量获取交易信息
 * @param hashIdList    交易ID列表,用逗号“,”分割
 * @return 交易信息列表
 */
public List<QueryTransactionResult> getTxByHashes(String hashIdList) {
    if (StringUtil.isEmpty(hashIdList)) {
        return null;
    }
    String[] hashArr = hashIdList.split(",");
    for (int i = 0; i < hashArr.length; i++) {
        String hash = hashArr[i];
        if (StringUtil.isNotEmpty(hash) && hash.startsWith("0x")) {
            hashArr[i] = HexUtil.removeHexHeader(hash);
        }
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("hashes", hashArr);
    RpcRequest postData = getPostData(RpcMethod.GET_TX_BY_HASHES);
    postData.addJsonParams(jsonObject);
    String result = HttpUtil.httpPostBody(getUrl(), postData.toJsonString());
    if (StringUtil.isNotEmpty(result)) {
        JSONObject parseObject = JSONObject.parseObject(result);
        if (messageValidate(parseObject))
            return null;
        JSONObject resultJson = parseObject.getJSONObject("result");
        JSONArray jsonArray = resultJson.getJSONArray("txs");
        if (jsonArray != null && jsonArray.size() != 0) {
            List<QueryTransactionResult> resultList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject txJson = jsonArray.getJSONObject(i);
                if (txJson == null) {
                    continue;
                }
                QueryTransactionResult transactionResult = txJson.toJavaObject(QueryTransactionResult.class);
                transactionResult.setBlocktime(new Date(transactionResult.getBlocktime().getTime() * 1000));
                resultList.add(transactionResult);
            }
            return resultList;
        }
    }
    return null;
}
 
Example 14
Source File: PptxWriterImpl.java    From tephra with MIT License 5 votes vote down vote up
private void parseShapes(WriterContext writerContext, JSONArray shapes) {
    for (int i = 0, size = shapes.size(); i < size; i++) {
        JSONObject shape = shapes.getJSONObject(i);
        XSLFShape xslfShape = parser.createShape(writerContext, shape);
        if (xslfShape == null) {
            logger.warn(null, "无法处理PPTx形状[{}]!", shape);

            continue;
        }

        if (xslfShape instanceof XSLFSimpleShape)
            parser.parseShape(writerContext, (XSLFSimpleShape) xslfShape, shape);
    }
}
 
Example 15
Source File: Actions.java    From ucar-weex-core with Apache License 2.0 4 votes vote down vote up
public static Action get(String actionName,JSONArray args){
  switch (actionName) {
    case CREATE_BODY:
      if (args == null) {
        return null;
      }
      return new CreateBodyAction(args.getJSONObject(0));
    case UPDATE_ATTRS:
      if (args == null) {
        return null;
      }
      return new UpdateAttributeAction(args.getString(0),args.getJSONObject(1));
    case UPDATE_STYLE:
      if (args == null) {
        return null;
      }
      return new UpdateStyleAction(args.getString(0),args.getJSONObject(1));
    case REMOVE_ELEMENT:
      if (args == null) {
        return null;
      }
      return new RemoveElementAction(args.getString(0));
    case ADD_ELEMENT:
      if (args == null) {
        return null;
      }
      return new AddElementAction(args.getJSONObject(1),args.getString(0),args.getInteger(2));
    case MOVE_ELEMENT:
      if (args == null) {
        return null;
      }
      return new MoveElementAction(args.getString(0),args.getString(1),args.getInteger(2));
    case ADD_EVENT:
      if (args == null) {
        return null;
      }
      return new AddEventAction(args.getString(0),args.getString(1));
    case REMOVE_EVENT:
      if (args == null) {
        return null;
      }
      return new RemoveEventAction(args.getString(0),args.getString(1));
    case CREATE_FINISH:
      return new CreateFinishAction();
    case REFRESH_FINISH:
      return new RefreshFinishAction();
    case UPDATE_FINISH:
      return new UpdateFinishAction();
    case SCROLL_TO_ELEMENT:
      if (args == null) {
        return null;
      }
      String ref = args.size() >= 1 ? args.getString(0) : null;
      JSONObject options = args.size() >= 2 ? args.getJSONObject(1) : null;
      return new ScrollToElementAction(ref, options);
    case ADD_RULE:
      if (args == null) {
        return null;
      }
      return new AddRuleAction(args.getString(0),args.getJSONObject(1));
    case GET_COMPONENT_RECT:
      if(args == null){
        return null;
      }
      return new GetComponentRectAction(args.getString(0),args.getString(1));
    case INVOKE_METHOD:
      if(args == null){
        return null;
      }
      return new InvokeMethodAction(args.getString(0),args.getString(1),args.getJSONArray(2));
  }

  return null;
}
 
Example 16
Source File: SocialDetailActivity.java    From FanXin-based-HuanXin with GNU General Public License v2.0 4 votes vote down vote up
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_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);
}
 
Example 17
Source File: TuRingRobotServiceImpl.java    From xechat with MIT License 4 votes vote down vote up
/**
 * 解析响应数据
 *
 * @param resp 响应数据
 * @return 解析后的字符串
 */
private String parseData(ResponseEntity<JSONObject> resp) {
    if (resp.getStatusCodeValue() != HttpStatus.SC_OK) {
        return null;
    }

    StringBuffer sb = new StringBuffer();
    JSONObject data = resp.getBody();
    log.debug("data -> {}", data);

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

    JSONObject obj;
    JSONObject values;
    JSONArray news;
    JSONObject newsInfo;
    for (int i = 0; i < results.size(); i++) {
        obj = results.getJSONObject(i);
        String type = obj.getString("resultType");
        values = obj.getJSONObject("values");

        switch (type) {
            case "text":
                sb.append(StringEscapeUtils.unescapeHtml4(values.getString("text")));
                break;
            case "url":
                String url = values.getString("url");
                sb.append("<a href='");
                sb.append(url);
                sb.append("' target='_blank'>");
                sb.append(url);
                sb.append("</a><br/>");
                break;
            case "news":
                news = values.getJSONArray("news");
                for (int j = 0; j < news.size(); j++) {
                    newsInfo = news.getJSONObject(j);
                    sb.append("<br/><a href='");
                    sb.append(newsInfo.getString("detailurl"));
                    sb.append("' target='_blank'>");
                    sb.append(j + 1);
                    sb.append(". ");
                    sb.append(newsInfo.getString("name"));
                    sb.append("</a>");
                    sb.append("<br/><img src='");
                    sb.append(newsInfo.getString("icon"));
                    sb.append("' >");
                }
                break;
            default:
                break;
        }
    }

    return sb.toString();
}
 
Example 18
Source File: HcFtpToFileSystemConfigAction.java    From MicroCommunity with Apache License 2.0 4 votes vote down vote up
/**
 * 删除ftp配置
 *
 * @return
 */
public JSONObject deleteFtpItem(HttpServletRequest request) {

	// 请求参数为{"tasks":[{"taskId":1},{"taskId":2}],"state":"DELETE"}
	String ftpItemJson = request.getParameter("ftpItemJson");
	if (logger.isDebugEnabled()) {
		logger.debug("---【PrvncFtpToFileSystemConfigAction.deleteFtpItem】入参为:" + ftpItemJson, ftpItemJson);
	}

	JSONObject paramIn = null;

	try {
		// 校验格式是否正确
		paramIn = JSONObject.parseObject(ftpItemJson);
	} catch (Exception e) {
		logger.error("传入参数格式不正确:" + ftpItemJson, e);
		resultMsg = createResultMsg("1999", "传入参数格式不正确:" + ftpItemJson + e, "");
		return resultMsg;
	}

	// 传入报文不为空
	if (paramIn == null || !paramIn.containsKey("tasks") || !paramIn.containsKey("state")) {

		resultMsg = createResultMsg("1999", "传入参数格式不正确(必须包含tasks 和  state节点):" + ftpItemJson, "");
		return resultMsg;
	}

	// 校验当前是否为启动侦听
	if (!"DELETE".equals(paramIn.get("state"))) {

		resultMsg = createResultMsg("1999", "传入参数格式不正确(state的值必须是DELETE):" + ftpItemJson, "");
		return resultMsg;
	}

	// 查询需要操作的任务
	JSONArray taskInfos = paramIn.getJSONArray("tasks");
	String taskIds = "";

	for (int taskIndex = 0; taskIndex < taskInfos.size(); taskIndex++) {
		taskIds += (taskInfos.getJSONObject(taskIndex).getString("taskId") + ",");
	}

	if (taskIds.length() > 0) {
		taskIds = taskIds.substring(0, taskIds.length() - 1);
	}
	// 将ftpItemJson装为Map保存操作
	Map paramInfo = new HashMap();
	paramInfo.put("taskIds", taskIds.split(","));
	// 更新数据
	int updateFtpItemFlag = iHcFtpFileDAO.deleteFtpItemByTaskId(paramInfo);
	if (updateFtpItemFlag > 0) {
		resultMsg = this.createResultMsg("0000", "成功", ftpItemJson);
		return resultMsg;
	}

	resultMsg = this.createResultMsg("1999", "删除数据已经不存在,或删除失败", "");

	return resultMsg;
}
 
Example 19
Source File: SubmissionManager.java    From leetcode-editor with Apache License 2.0 4 votes vote down vote up
public static List<Submission> getSubmissionService(Question question, Project project) {

        if (!HttpRequestUtils.isLogin()) {
            MessageUtils.getInstance(project).showWarnMsg("info", PropertiesUtils.getInfo("login.not"));
            return null;
        }

        List<Submission> submissionList = new ArrayList<Submission>();

        try {
            HttpRequest httpRequest = HttpRequest.post(URLUtils.getLeetcodeGraphql(),"application/json");
            httpRequest.setBody("{\"operationName\":\"Submissions\",\"variables\":{\"offset\":0,\"limit\":20,\"lastKey\":null,\"questionSlug\":\"" + question.getTitleSlug() + "\"},\"query\":\"query Submissions($offset: Int!, $limit: Int!, $lastKey: String, $questionSlug: String!) {\\n  submissionList(offset: $offset, limit: $limit, lastKey: $lastKey, questionSlug: $questionSlug) {\\n    lastKey\\n    hasNext\\n    submissions {\\n      id\\n      statusDisplay\\n      lang\\n      runtime\\n      timestamp\\n      url\\n      isPending\\n      memory\\n      __typename\\n    }\\n    __typename\\n  }\\n}\\n\"}");
            httpRequest.addHeader("Accept", "application/json");
            HttpResponse response = HttpRequestUtils.executePost(httpRequest);
            if (response != null && response.getStatusCode() == 200) {
                String body = response.getBody();
                if (StringUtils.isNotBlank(body)) {

                    JSONArray jsonArray = JSONObject.parseObject(body).getJSONObject("data").getJSONObject("submissionList").getJSONArray("submissions");
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        Submission submission = new Submission();
                        submission.setId(object.getString("id"));
                        submission.setStatus(object.getString("statusDisplay"));
                        submission.setLang(object.getString("lang"));
                        submission.setRuntime(object.getString("runtime"));
                        submission.setTime(object.getString("timestamp"));
                        submission.setMemory(object.getString("memory"));
                        submissionList.add(submission);
                    }
                    if (submissionList.size() == 0) {
                        MessageUtils.getInstance(project).showInfoMsg("info", PropertiesUtils.getInfo("submission.empty"));
                    }
                }
            } else {
                MessageUtils.getInstance(project).showWarnMsg("info", PropertiesUtils.getInfo("request.failed"));
            }

        } catch (Exception io) {
            MessageUtils.getInstance(project).showWarnMsg("info", PropertiesUtils.getInfo("request.failed"));
        }
        return submissionList;
    }
 
Example 20
Source File: JsonConfigUtil.java    From framework with Apache License 2.0 4 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @param obj
 * @return <br>
 */
@SuppressWarnings("rawtypes")
public static FlowConfig getFlowConfig(final JSONObject obj) {

    FlowConfig config = new FlowConfig();

    String component = obj.getString("component");
    if (StringUtils.isNotEmpty(component)) {
        FlowComponent flowComponent = ContextHolder.getContext().getBean(component, FlowComponent.class);
        Assert.notNull(flowComponent, ErrorCodeDef.FLOW_COMPONENT_NOT_FOUND, component);
        config.setComponent(flowComponent);
    }

    String name = obj.getString("name");
    if (StringUtils.isEmpty(name)) {
        name = component;
    }
    config.setName(name);

    String version = obj.getString("version");
    if (StringUtils.isEmpty(version)) {
        version = "1.0";
    }

    JSONArray children = obj.getJSONArray("children");

    if (CollectionUtils.isNotEmpty(children)) {
        List<FlowConfig> childConfigList = new ArrayList<FlowConfig>();
        for (int i = 0, size = children.size(); i < size; i++) {
            childConfigList.add(getFlowConfig(children.getJSONObject(i)));
        }
        config.setChildrenConfigList(childConfigList);
    }

    obj.remove("component");
    obj.remove("name");
    obj.remove("version");
    obj.remove("children");
    config.setConfigAttrMap(obj);
    return config;
}