Java Code Examples for com.alibaba.fastjson.JSONObject#getBoolean()

The following examples show how to use com.alibaba.fastjson.JSONObject#getBoolean() . 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: BaseOperationAdapter.java    From java-unified-sdk with Apache License 2.0 6 votes vote down vote up
private <T> T parseJSONObject(JSONObject jsonObject) {
  if (jsonObject.containsKey(ATTR_OP) && jsonObject.containsKey(ATTR_FIELD)) {
    String op = jsonObject.getString(ATTR_OP);
    String field = jsonObject.getString(ATTR_FIELD);
    boolean isFinal = jsonObject.containsKey(ATTR_FINAL)? jsonObject.getBoolean(ATTR_FINAL) : false;

    OperationBuilder.OperationType opType = OperationBuilder.OperationType.valueOf(op);

    Object obj = jsonObject.containsKey(ATTR_OBJECT) ? jsonObject.get(ATTR_OBJECT) : null;
    Object parsedObj = getParsedObject(obj);

    ObjectFieldOperation result = OperationBuilder.gBuilder.create(opType, field, parsedObj);
    ((BaseOperation)result).isFinal = isFinal;

    if (jsonObject.containsKey(ATTR_SUBOPS) && result instanceof CompoundOperation) {
      List<JSONObject> subOps = jsonObject.getObject(ATTR_SUBOPS, List.class);
      for (JSONObject o : subOps) {
        result.merge((BaseOperation)parseJSONObject(o));
      }
    }

    return (T) result;
  }
  return (T) new NullOperation("Null", null);
}
 
Example 2
Source File: ControllerHelixManager.java    From uReplicator with Apache License 2.0 6 votes vote down vote up
/**
 * RPC call to notify controller to change autobalancing status. No retry
 *
 * @param controllerInstance The controller InstanceName
 * @param enable whether to enable autobalancing
 */
public boolean notifyControllerAutobalancing(String controllerInstance, boolean enable)
    throws ControllerException {
  String cmd = enable ? "enable_autobalancing" : "disable_autobalancing";
  try {
    HostAndPort hostInfo = getHostInfo(controllerInstance);
    String result = HttpClientUtils
        .postData(_httpClient, _requestConfig, hostInfo.getHost(), hostInfo.getPort(),
            "/admin/" + cmd);
    JSONObject resultJson = JSON.parseObject(result);
    return resultJson.getBoolean("auto_balancing") == enable;
  } catch (IOException | URISyntaxException ex) {
    String msg = String.format("Got error from controller %s when trying to do %s",
        controllerInstance, cmd);
    LOGGER.error(msg, ex);
    throw new ControllerException(msg, ex);
  }
}
 
Example 3
Source File: ContractEventParserJson.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static boolean topicsMatched(List<byte[]> topicList, JSONObject entry) {
    if (topicList == null || topicList.isEmpty()) {
        return true;
    }
    int inputSize = 1;
    JSONArray inputs = entry.getJSONArray(INPUTS);
    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) {
                    inputSize++;
                }
            }
        }
    }
    return inputSize == topicList.size();
}
 
Example 4
Source File: EntityConfig.java    From Spring-generator with MIT License 5 votes vote down vote up
/**
 * 实例化
 * 
 * @param obj
 */
public EntityConfig(JSONObject obj) {
	super();
	this.templateName = obj.getString("templateName");
	this.fieldCamel = obj.getBoolean("fieldCamel");
	this.overrideFile = obj.getBoolean("overrideFile");
}
 
Example 5
Source File: TwitcastingLiveService.java    From Alice-LiveMan with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public VideoInfo getLiveVideoInfo(URI videoInfoUrl, ChannelInfo channelInfo, String resolution) throws Exception {
    if (videoInfoUrl == null) {
        return null;
    }
    String roomName = videoInfoUrl.toString().replace("https://twitcasting.tv/", "").replace("/", "");
    URI streamCheckerUrl = new URI("https://twitcasting.tv/streamchecker.php?u=" + roomName + "&v=999&myself=&islive=1&lastitemid=-1&__c=" + System.currentTimeMillis());
    String streamChecker = HttpRequestUtil.downloadUrl(streamCheckerUrl, channelInfo != null ? channelInfo.getCookies() : null, Collections.emptyMap(), StandardCharsets.UTF_8);
    String[] checkes = streamChecker.split("\t");
    Video video = parseVideo(checkes[0], Integer.parseInt(checkes[1]), checkes[7], Integer.parseInt(checkes[19].trim()));
    if (!video.getOnline()) {
        return null;
    }
    if (video.getPrivate()) {
        log.warn("频道[" + channelInfo.getChannelName() + "]正在直播的内容已加密!");
    }
    if (video.getWatchable()) {
        URI streamServerUrl = new URI("https://twitcasting.tv/streamserver.php?target=" + roomName + "&mode=client");
        String serverInfo = HttpRequestUtil.downloadUrl(streamServerUrl, channelInfo != null ? channelInfo.getCookies() : null, Collections.emptyMap(), StandardCharsets.UTF_8);

        JSONObject streamServer = JSONObject.parseObject(serverInfo);
        JSONObject movie = streamServer.getJSONObject("movie");
        if (movie.getBoolean("live")) {
            String videoTitle = "";
            String roomHtml = HttpRequestUtil.downloadUrl(videoInfoUrl, channelInfo != null ? channelInfo.getCookies() : null, Collections.emptyMap(), StandardCharsets.UTF_8);
            Matcher matcher = ROOM_TITLE_PATTERN.matcher(roomHtml);
            if (matcher.find()) {
                videoTitle = matcher.group(1);
            }
            String videoId = movie.getString("id");
            String mediaUrl = "wss://" + streamServer.getJSONObject("fmp4").getString("host") + "/ws.app/stream/" + videoId + "/fmp4/bd/1/1500?mode=main";
            return new VideoInfo(channelInfo, videoId, video.getTelop() == null ? videoTitle : video.getTelop(), videoInfoUrl, new URI(mediaUrl), "mp4");
        }
    }
    return null;
}
 
Example 6
Source File: SolutionResource.java    From cubeai with Apache License 2.0 5 votes vote down vote up
/**
 * PUT  /solutions/publish-status : 批准模型上架/下架申请
 * @param jsonObject the JSONObject with publishStatus and publishRequest to be updated
 * @return the ResponseEntity with status 200 (OK) and with body the updated solution, or status 400 (Bad Request)
 */
@PutMapping("/solutions/publish-approve")
@Timed
@Secured({"ROLE_MANAGER"})  // 模型上架/下架申请只能由平台管理员进行批准
public ResponseEntity<Solution> approvePublish(HttpServletRequest httpServletRequest,
                                               @Valid @RequestBody JSONObject jsonObject) {
    log.debug("REST request to update Solution publishStatus: {}", jsonObject);
    String userLogin = JwtUtil.getUserLogin(httpServletRequest);

    Solution solution = solutionRepository.findOne(jsonObject.getLong("solutionId"));
    if (jsonObject.getBoolean("toPublish")) {
        solution.setPublishStatus(jsonObject.getBoolean("approved") ? "上架" : "下架");
    } else {
        solution.setPublishStatus(jsonObject.getBoolean("approved") ? "下架" : "上架");
    }
    solution.setPublishRequest("无申请");
    solution.setModifiedDate(Instant.now());
    Solution result = solutionRepository.save(solution);

    PublishRequest publishRequest = publishRequestRepository.findOne(jsonObject.getLong("publishRequestId"));
    publishRequest.setReviewUserLogin(userLogin);
    publishRequest.setReviewed(true);
    publishRequest.setReviewResult(jsonObject.getBoolean("approved") ? "批准" : "拒绝");
    publishRequest.setReviewComment(jsonObject.getString("reviewComment"));
    publishRequest.setReviewDate(Instant.now());
    publishRequestRepository.save(publishRequest);

    String title = "模型" + publishRequest.getSolutionName() + publishRequest.getRequestType() + "审批被" + publishRequest.getReviewResult();
    String content = "你的模型" + publishRequest.getSolutionName() + publishRequest.getRequestType() + "审批被" + publishRequest.getReviewResult()
        + "。\n\n请点击下方[目标页面]按钮进入模型页面进行后续处理...";
    String url = "/ucumos/solution/" + publishRequest.getSolutionUuid() + "/edit";
    messageService.sendMessage(publishRequest.getRequestUserLogin(), title, content, url, false);

    return ResponseEntity.ok().body(result);
}
 
Example 7
Source File: CustomConfig.java    From Spring-generator with MIT License 5 votes vote down vote up
/**
 * 初始化
 */
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));
		});
	}
}
 
Example 8
Source File: Parsers.java    From Glin with Apache License 2.0 5 votes vote down vote up
@Override
public Parser getParser() {
    return new Parser() {
        @Override
        public <T> Result<T> parse(Class<T> klass, RawResult netResult) {
            Result<T> result = new Result<>();
            try {
                JSONObject baseObject = JSON.parseObject(netResult.getResponse());
                if (baseObject.getBoolean("ok")) {
                    if (baseObject.containsKey("data")) {
                        T t = baseObject.getObject("data", klass);
                        result.setResult(t);
                        result.ok(true);
                        return result;
                    }
                }

                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
                result.ok(false);
                result.setMessage("error");
            }
            return result;
        }
    };
}
 
Example 9
Source File: GeneratorEditComponent.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 生成接口类
 *
 * @param data
 */
private void genneratorListSmoImpl(JSONObject data) throws Exception {
    StringBuffer sb = readFile(GeneratorStart.class.getResource("/web/edit/EditSMOImpl.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(paramIn, \"" + 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(paramIn, \"" + column.getString("code") + "\", \"" + column.getString("desc") + "\");\n");
        }
    }

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


    String writePath = this.getClass().getResource("/").getPath()
            + "out/web/smo/" + data.getString("templateCode") + "/impl/Edit" + toUpperCaseFirstOne(data.getString("templateCode")) + "SMOImpl.java";
    System.out.printf("writePath: " + writePath);
    writeFile(writePath,
            fileContext);
    //复制生成的文件到对应分区目录下
    FileUtilBase.copyfile(writePath, "FrontService\\src\\main\\java\\com\\java110\\front\\smo\\" + data.getString("templateCode") + "/impl/Edit" + toUpperCaseFirstOne(data.getString("templateCode")) + "SMOImpl.java");

}
 
Example 10
Source File: AVIMConversation.java    From java-unified-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * parse AVIMConversation from jsonObject
 * @param client client instance
 * @param jsonObj json object
 * @return conversation instance.
 */
public static AVIMConversation parseFromJson(AVIMClient client, JSONObject jsonObj) {
  if (null == jsonObj || null == client) {
    return null;
  }

  String conversationId = jsonObj.getString(AVObject.KEY_OBJECT_ID);
  if (StringUtil.isEmpty(conversationId)) {
    return null;
  }
  boolean systemConv = false;
  boolean transientConv = false;
  boolean tempConv = false;
  if (jsonObj.containsKey(Conversation.SYSTEM)) {
    systemConv = jsonObj.getBoolean(Conversation.SYSTEM);
  }
  if (jsonObj.containsKey(Conversation.TRANSIENT)) {
    transientConv = jsonObj.getBoolean(Conversation.TRANSIENT);
  }
  if (jsonObj.containsKey(Conversation.TEMPORARY)) {
    tempConv = jsonObj.getBoolean(Conversation.TEMPORARY);
  }
  AVIMConversation originConv = null;
  if (systemConv) {
    originConv = new AVIMServiceConversation(client, conversationId);
  } else if (tempConv) {
    originConv = new AVIMTemporaryConversation(client, conversationId);
  } else if (transientConv) {
    originConv = new AVIMChatRoom(client, conversationId);
  } else {
    originConv = new AVIMConversation(client, conversationId);
  }
  originConv.updateFetchTimestamp(System.currentTimeMillis());

  return updateConversation(originConv, jsonObj);
}
 
Example 11
Source File: Okexv3Exchange.java    From GOAi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected Boolean transformCancelOrder(List<String> results, ExchangeInfo info) {
    String result = results.get(0);
    if (useful(result)) {
        JSONObject r = JSON.parseObject(result);
        if (r.containsKey(RESULT)) {
            return r.getBoolean(RESULT);
        }
    }
    return null;
}
 
Example 12
Source File: JSONUtil.java    From easyweb-shiro with MIT License 5 votes vote down vote up
/**
 * 得到Boolean类型的值
 */
public static boolean getBoolean(String json, String key) {
    Boolean result = null;
    try {
        JSONObject jsonObject = JSON.parseObject(json);
        result = jsonObject.getBoolean(key);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 13
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 14
Source File: EntityConfig.java    From Vert.X-generator with MIT License 5 votes vote down vote up
/**
 * 实例化
 * 
 * @param obj
 */
public EntityConfig(JSONObject obj) {
	super();
	this.templateName = obj.getString("templateName");
	this.fieldCamel = obj.getBoolean("fieldCamel");
	this.overrideFile = obj.getBoolean("overrideFile");
}
 
Example 15
Source File: CustomConfig.java    From Vert.X-generator with MIT License 5 votes vote down vote up
/**
 * 初始化
 */
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));
		});
	}
}
 
Example 16
Source File: HTMLUtil.java    From DBus with Apache License 2.0 4 votes vote down vote up
public static String isVersionChangeCompatible(JSONObject payload) {
    JSONObject compareResult = payload.getJSONObject("compare-result");
    boolean isCompatible = compareResult.getBoolean("compatible");
    if (isCompatible) return "兼容性";
    else return "";
}
 
Example 17
Source File: BulkParseHandler.java    From DataLink with Apache License 2.0 4 votes vote down vote up
@Override
public Object checkError(JSONObject json) {
	return json.getBoolean(ParseHandler.ERRORS_NAME);
}
 
Example 18
Source File: Okexv3WebSocketClient.java    From GOAi with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void transform(String message) {
    JSONObject r = JSON.parseObject(message);
    if (r.containsKey(EVENT)) {
        switch (r.getString(EVENT)) {
            case "subscribe":
                this.log.info("{} subscribe success: {}", super.symbol, message);
                return;
            case "unsubscribe":
                this.log.info("{} unsubscribe success: {}", super.symbol, message);
                return;
            case "login":
                if (r.containsKey(SUCCESS) && r.getBoolean(SUCCESS)) {
                    this.log.info("{} {} login success: {}", Seal.seal(super.access), super.symbol, message);
                    Account account = ExchangeManager.getHttpExchange(ExchangeName.OKEXV3, this.log)
                            .getAccount(ExchangeInfo.ticker(super.symbol, super.access, super.secret));
                    if (null != account) {
                        this.base = account.getBase();
                        this.count = account.getQuote();
                    }
                    this.login = true;
                    this.loginCommands.forEach(this::send);
                }
                return;
            case "error":
                if (r.containsKey(ERROR_CODE)) {
                    switch (r.getInteger(ERROR_CODE)) {
                        case ERROR_CODE_LOGGED_OUT:
                            this.login = false;
                            this.login();
                            break;
                        case ERROR_CODE_LOGGED_IN:
                            this.login = true;
                            return;
                        case ERROR_CODE_ERROR_COMMAND:
                            if (r.getString(MESSAGE).endsWith(ALIVE)) {
                                this.limit.update();
                                return;
                            }
                            default:
                    }
                }
            default:
        }
    }
    if (r.containsKey(TABLE)) {
        String table = r.getString(TABLE);
        switch (table) {
            case "spot/ticker":
                // 解析Ticker
                this.transformTicker(r);
                return;
            case "spot/depth":
                // 解析Depth
                if (this.transformDepth(r)) {
                    return;
                }
                super.limit.update();
                break;
            case "spot/trade":
                // 解析Trades
                this.transformTrades(r);
                return;
            case "spot/account":
                // 解析account
                log.info("account: {}", message);
                this.transformAccount(r);
                return;
            case "spot/order":
                // 解析Trades
                this.transformOrders(r);
                return;
            default:
        }
        if (table.startsWith(KLINE_START)) {
            this.transformKlines(table, r);
            return;
        }
    }
    this.log.error("can not transform: {}", message);
}
 
Example 19
Source File: BulkParseHandler.java    From EserKnife with Apache License 2.0 4 votes vote down vote up
@Override
public Object checkError(JSONObject json) {
    return json.getBoolean(ParseHandler.ERRORS_NAME);
}
 
Example 20
Source File: GeneratorBindingComponent.java    From MicroCommunity with Apache License 2.0 4 votes vote down vote up
/**
 * 生成 html js java 类
 *
 * @param data
 */
private void generatorComponentJs(JSONObject data) {

    StringBuffer sb = readFile(GeneratorStart.class.getResource("/relationship/binding/binding.js").getFile());
    String fileContext = sb.toString();

    fileContext = super.replaceBindingTemplateContext(fileContext, data);

    //替换 变量@@templateCodeColumns@@
    JSONArray columns = data.getJSONArray("columns");

    StringBuffer variable = new StringBuffer();
    String defaultValue = "";

    StringBuffer validateInfo = new StringBuffer();
    StringBuffer allStep = new StringBuffer("[");
    JSONArray flows = data.getJSONArray("flows");
    for (int flowIndex = 0; flowIndex < flows.size(); flowIndex++) {
        JSONObject flow = flows.getJSONObject(flowIndex);
        allStep.append("\"" + flow.getString("cnCode") + "\"");
        if (flowIndex < flows.size() - 1) {
            allStep.append(",");
        }


        validateInfo.append("vc.emit('" + flow.getString("vcName") + "', 'onIndex', vc.component."+data.getString("templateCode")+"Info.index);\n");

        //如果相应组件不存在,则根据组件配置自动生成
        if (!flow.getBoolean("existsComponent")) {
            generatorAddJs(data, flow.getString("vcName"));
        }

    }
    String showAffirmPage = data.getBoolean("needAffirm") ? "确认信息" : "";
    allStep.append(showAffirmPage);
    allStep.append("]");
    fileContext = fileContext.replace("@@stepTitle@@", allStep.toString());
    fileContext = fileContext.replace("@@notifyOnIndex@@", validateInfo.toString());
    fileContext = fileContext.replace("@@jumpUrl@@", data.getString("successUrl"));

    // 替换 数据校验部分代码

    String needCheckCurrentData = "var _currentData = vc.component."+data.getString("templateCode")+"Info.infos[vc.component."+data.getString("templateCode")+"Info.index];\n" +
            "                if( _currentData == null || _currentData == undefined){\n" +
            "                    vc.message(\"请选择或填写必选信息\");\n" +
            "                    return ;\n" +
            "                }";

    if(data.getBoolean("needAffirm")){
        fileContext = fileContext.replace("@@needCheckCurrentData@@", "");
    }else{
        fileContext = fileContext.replace("@@needCheckCurrentData@@", needCheckCurrentData);
    }


    String writePath = this.getClass().getResource("/").getPath()
            + "out/relationship/component/" + data.getString("package") + "/" + data.getString("templateCode") + "/" + data.getString("templateCode") + ".js";
    System.out.printf("writePath: " + writePath);
    writeFile(writePath,
            fileContext);


}