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

The following examples show how to use com.alibaba.fastjson.JSONArray#toJavaList() . 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: RpcClient.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * @description 查询地址token余额
 * 
 * @param addresses 地址列表
 * @param execer    token 查询可用的余额 ,trade 查询正在交易合约里的token,如果是查询平行链上余额,则需要指定具体平行链的执行器execer,例如:user.p.xxx.token .
 * @param tokenSymbol   token符号名称
 * @return  账号余额列表
 */
public List<AccountAccResult> getTokenBalance(List<String> addresses, String execer, String tokenSymbol) {
    RpcRequest postData = getPostData(RpcMethod.GET_TOKEN_BALANCE);
    JSONObject requestParam = new JSONObject();
    requestParam.put("addresses", addresses);
    requestParam.put("execer", execer);
    requestParam.put("tokenSymbol", tokenSymbol);
    postData.addJsonParams(requestParam);
    String requestResult = HttpUtil.httpPostBody(getUrl(), postData.toJsonString());
    if (StringUtil.isNotEmpty(requestResult)) {
        JSONObject parseObject = JSONObject.parseObject(requestResult);
        if (messageValidate(parseObject))
            return null;
        JSONArray resultArray = parseObject.getJSONArray("result");
        List<AccountAccResult> javaList = resultArray.toJavaList(AccountAccResult.class);
        return javaList;
    }
    return null;
}
 
Example 2
Source File: PlainPermissionManager.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public AclConfig getAllAclConfig() {
    AclConfig aclConfig = new AclConfig();
    List<PlainAccessConfig> configs = new ArrayList<>();
    List<String> whiteAddrs = new ArrayList<>();
    JSONObject plainAclConfData = AclUtils.getYamlDataObject(fileHome + File.separator + fileName,
            JSONObject.class);
    if (plainAclConfData == null || plainAclConfData.isEmpty()) {
        throw new AclException(String.format("%s file  is not data", fileHome + File.separator + fileName));
    }
    JSONArray globalWhiteAddrs = plainAclConfData.getJSONArray(AclConstants.CONFIG_GLOBAL_WHITE_ADDRS);
    if (globalWhiteAddrs != null && !globalWhiteAddrs.isEmpty()) {
        whiteAddrs = globalWhiteAddrs.toJavaList(String.class);
    }
    JSONArray accounts = plainAclConfData.getJSONArray(AclConstants.CONFIG_ACCOUNTS);
    if (accounts != null && !accounts.isEmpty()) {
        configs = accounts.toJavaList(PlainAccessConfig.class);
    }
    aclConfig.setGlobalWhiteAddrs(whiteAddrs);
    aclConfig.setPlainAccessConfigs(configs);
    return aclConfig;
}
 
Example 3
Source File: CheckTopologyHandler.java    From DBus with Apache License 2.0 6 votes vote down vote up
@Override
public void check(BufferedWriter bw) throws Exception {
    AutoCheckConfigBean conf = AutoCheckConfigContainer.getInstance().getAutoCheckConf();
    String stormUIAPI = conf.getStormUIApi() + "/topology/summary";
    bw.newLine();
    bw.write("check topology start: ");
    bw.newLine();
    bw.write("============================================");
    bw.newLine();
    bw.write("api: " + stormUIAPI);
    bw.newLine();

    String strData = httpGet(stormUIAPI);

    JSONObject data = JSON.parseObject(strData);
    JSONArray topologies = data.getJSONArray("topologies");
    for (JSONObject topology : topologies.toJavaList(JSONObject.class)) {
        String name = topology.getString("name");
        String status = topology.getString("status");
        bw.write(MsgUtil.format("topology {0} status is {1}", name, status));
        bw.newLine();
    }
}
 
Example 4
Source File: RpcClient.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public List<DecodeRawTransaction> decodeRawTransaction(String rawTx) {
    RpcRequest postData = getPostData(RpcMethod.DECODE_RAW_TX);
    JSONObject requestParam = new JSONObject();
    requestParam.put("txHex", rawTx);
    postData.addJsonParams(requestParam);
    String requestResult = HttpUtil.httpPostBody(getUrl(), postData.toJsonString());
    if (StringUtil.isNotEmpty(requestResult)) {
        JSONObject parseObject = JSONObject.parseObject(requestResult);
        if (messageValidate(parseObject))
            return null;
        JSONObject resultObj = parseObject.getJSONObject("result");
        JSONArray jsonArray = resultObj.getJSONArray("txs");
        List<DecodeRawTransaction> javaList = jsonArray.toJavaList(DecodeRawTransaction.class);
        return javaList;
    }
    return null;
}
 
Example 5
Source File: RpcClient.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * @description 查询地址余额
 * 
 * @param addressList 地址
 * @param execer  coins
 * @return
 */
public List<AccountAccResult> queryBalance(List<String> addressList, String execer) {
    RpcRequest postData = getPostData(RpcMethod.GET_BALANCE);
    JSONObject requestParam = new JSONObject();
    requestParam.put("execer", execer);
    requestParam.put("addresses", addressList);
    postData.addJsonParams(requestParam);
    String requestResult = HttpUtil.httpPostBody(getUrl(), postData.toJsonString());
    if (StringUtil.isNotEmpty(requestResult)) {
        JSONObject parseObject = JSONObject.parseObject(requestResult);
        if (messageValidate(parseObject))
            return null;
        JSONArray jsonArray = parseObject.getJSONArray("result");
        List<AccountAccResult> javaList = jsonArray.toJavaList(AccountAccResult.class);
        return javaList;
    }
    return null;
}
 
Example 6
Source File: RpcClient.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * @description 查询地址下的token/trace合约下的token资产
 * 
 * @param address:  查询的地址
 * @param payloadExecer:   token 或 trade
 * @return TokenBalanceResult
 */
public List<TokenBalanceResult> queryAccountBalance(String address, String payloadExecer) {
    RpcRequest postData = getPostData(RpcMethod.QUERY);
    JSONObject requestParam = new JSONObject();
    requestParam.put("execer", "token");
    requestParam.put("funcName", "GetAccountTokenAssets");
    JSONObject payloadJson = new JSONObject();
    payloadJson.put("address", address);
    payloadJson.put("execer", payloadExecer);
    requestParam.put("payload", payloadJson);
    postData.addJsonParams(requestParam);
    String requestResult = HttpUtil.httpPostBody(getUrl(), postData.toJsonString());
    if (StringUtil.isNotEmpty(requestResult)) {
        JSONObject parseObject = JSONObject.parseObject(requestResult);
        if (messageValidate(parseObject))
            return null;
        JSONObject resultJson = parseObject.getJSONObject("result");
        JSONArray resultArray = resultJson.getJSONArray("tokenAssets");
        List<TokenBalanceResult> javaList = resultArray.toJavaList(TokenBalanceResult.class);
        return javaList;
    }
    return null;
}
 
Example 7
Source File: RpcClient.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * @description 查询所有预创建的token或创建成功的token
 * 
 * @param status 0:预创建 1:创建成功 的token
 * @return  token信息列表
 */
public List<TokenResult> queryCreateTokens(Integer status,String execer) {
    RpcRequest postData = getPostData(RpcMethod.QUERY);
    JSONObject requestParam = new JSONObject();
    requestParam.put("execer", execer);
    requestParam.put("funcName", "GetTokens");
    JSONObject payloadJson = new JSONObject();
    payloadJson.put("status", status);
    payloadJson.put("queryAll", true);
    requestParam.put("payload", payloadJson);
    postData.addJsonParams(requestParam);
    String requestResult = HttpUtil.httpPostBody(getUrl(), postData.toJsonString());
    if (StringUtil.isNotEmpty(requestResult)) {
        JSONObject parseObject = JSONObject.parseObject(requestResult);
        if (messageValidate(parseObject))
            return null;
        JSONObject resultJson = parseObject.getJSONObject("result");
        JSONArray resultArray = resultJson.getJSONArray("tokens");
        List<TokenResult> javaList = resultArray.toJavaList(TokenResult.class);
        return javaList;
    }
    return null;
}
 
Example 8
Source File: RpcClient.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * @description 根据地址获取交易信息hash
 * 
 * @param flag:   0:addr 的所有交易;1:当 addr 为发送方时的交易;2:当 addr 为接收方时的交易。
 * @param height: 交易所在的block高度,-1:表示从最新的开始向后取;大于等于0的值,从具体的高度+具体index开始取。
 * @param index:  交易所在block中的索引,取值0--100000。
 * @return 交易列表
 */
public List<TxResult> getTxByAddr(String addr, Integer flag, Integer count, Integer direction, Long height,
        Integer index) {
    RpcRequest postData = getPostData(RpcMethod.GET_TX_BY_ADDR);
    JSONObject requestParam = new JSONObject();
    requestParam.put("addr", addr);
    requestParam.put("flag", flag);
    requestParam.put("count", count);
    requestParam.put("direction", direction);
    requestParam.put("height", height);
    requestParam.put("index", index);
    postData.addJsonParams(requestParam);
    String requestResult = HttpUtil.httpPostBody(getUrl(), postData.toJsonString());
    if (StringUtil.isNotEmpty(requestResult)) {
        JSONObject parseObject = JSONObject.parseObject(requestResult);
        if (messageValidate(parseObject))
            return null;
        JSONObject resultObj = parseObject.getJSONObject("result");
        JSONArray jsonArray = resultObj.getJSONArray("txInfos");
        List<TxResult> javaList = jsonArray.toJavaList(TxResult.class);
        return javaList;
    }
    return null;
}
 
Example 9
Source File: RpcClient.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * @description 查询主代币余额
 * 
 * @param addresses  地址列表
 * @param execer    coins
 * @return  余额列表
 */
public List<AccountAccResult> getCoinsBalance(List<String> addresses, String execer) {
    RpcRequest postJsonData = new RpcRequest();
    postJsonData.setMethod(RpcMethod.GET_BALANCE);
    JSONObject requestParam = new JSONObject();
    requestParam.put("addresses", addresses);
    requestParam.put("execer", execer);
    postJsonData.addJsonParams(requestParam);
    String requestResult = HttpUtil.httpPostBody(getUrl(), postJsonData.toJsonString());
    if (StringUtil.isNotEmpty(requestResult)) {
        JSONObject parseObject = JSONObject.parseObject(requestResult);
        if (messageValidate(parseObject))
            return null;
        JSONArray resultArray = parseObject.getJSONArray("result");
        List<AccountAccResult> javaList = resultArray.toJavaList(AccountAccResult.class);
        return javaList;
    }
    return null;
}
 
Example 10
Source File: NodeInfo.java    From litchi with Apache License 2.0 6 votes vote down vote up
public static Map<String, List<NodeInfo>> getNodeMaps(JSONObject jsonObject, String nodeId) {
    Map<String, List<NodeInfo>> maps = new HashMap<>();

    for (String nodeType : jsonObject.keySet()) {
        JSONArray itemArrays = jsonObject.getJSONArray(nodeType);
        if (itemArrays.isEmpty()) {
            continue;
        }

        List<NodeInfo> list = itemArrays.toJavaList(NodeInfo.class);
        for (NodeInfo si : list) {
            si.setNodeType(nodeType);
            if (si.getNodeId().equals(nodeId)) {
                si.setPid(RuntimeUtils.pid());
            }
        }

        List<NodeInfo> serverInfoList = maps.getOrDefault(nodeType, new ArrayList<>());
        if (serverInfoList.isEmpty()) {
            maps.put(nodeType, serverInfoList);
        }
        serverInfoList.addAll(list);
    }
    return maps;
}
 
Example 11
Source File: RpcClient.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @description 获取账户列表 GetAccounts
 * 
 * @return 账号列表
 */
public List<AccountResult> getAccountList() {
    RpcRequest postData = getPostData(RpcMethod.GET_ACCOUNT_LIST);
    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("wallets");
        List<AccountResult> accountList = jsonArray.toJavaList(AccountResult.class);
        return accountList;
    }
    return null;
}
 
Example 12
Source File: TaskManager.java    From pe-protector-moe with GNU General Public License v3.0 5 votes vote down vote up
private void readFile() {
    SharedPreferences preferences = App.getContext().getSharedPreferences("task", Context.MODE_PRIVATE);
    String data = preferences.getString("list", "[]");
    Log.d(TAG, data);
    try {
        Log.d(TAG, "用户任务:" + data);
        JSONArray array = JSON.parseArray(data);
        taskBeanList = array.toJavaList(TaskBean.class);
    } catch (Exception e) {
        Log.e(TAG, "读取用户任务出错!");
        e.printStackTrace();
    }
}
 
Example 13
Source File: RecordServiceImpl.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<RecordModel> getRecordModelsByRemote() {
	// TODO Auto-generated method stub
	String getRecodeUrl = config.getRemoteBaseL10Url() + L10NAPIV1.API_L10N + "/records";
	Map<String, String> params = null;
	if (config.getAccessModel().equalsIgnoreCase("remote")) {
		params = new HashMap<String, String>();
		params.put("AccessToken", tokenStr);
	}
       logger.info("getRecordUrl:>>>"+getRecodeUrl);
	String result = HttpRequester.sendGet(getRecodeUrl, params, null);
	if(result == null) {
		refreshToken();
		result = HttpRequester.sendGet(getRecodeUrl, params, null);
	}
	logger.info(result);
	if(result == null || result.trim().equals("")) {
		return null;
	}
	JSONObject resultJsonObj = JSONObject.parseObject(result);
	int responseCode = resultJsonObj.getJSONObject("response").getInteger("code");

	if (responseCode == 204) {
		return null;
	} else {
		JSONArray recorJsonArr = resultJsonObj.getJSONArray("data");
		return recorJsonArr.toJavaList(RecordModel.class);
	}

}
 
Example 14
Source File: BevTreeConfig.java    From behavior3java with Apache License 2.0 5 votes vote down vote up
/**
 * 加载项目工程,将整个行为树都加载了
 *
 * @param path
 * @return
 */
public static List<BTTreeCfg> LoadTreesCfg(String path) {
    String text = FileUtil.readFile(path);
    JSONObject jsonObj = JSON.parseObject(text);
    JSONArray trees = jsonObj.getJSONArray("trees");
    List<BTTreeCfg> list = trees.toJavaList(BTTreeCfg.class);
    return list;
}
 
Example 15
Source File: GatewayUtils.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
/**
 *  redis中的信息需要处理下 转成RouteDefinition对象
 *         - id: login
 *           uri: lb://cloud-jeecg-system
 *           predicates:
 *             - Path=/jeecg-boot/sys/**,
 * @param array
 * @return
 */

public static List<RouteDefinition> getRoutesByJson(JSONArray array) throws URISyntaxException {
    List<RouteDefinition> ls = new ArrayList<>();
    for(int i=0;i<array.size();i++) {
        JSONObject obj = array.getJSONObject(i);
        RouteDefinition route = new RouteDefinition();
        route.setId(obj.getString("id"));
        Object uri = obj.get("uri");
        if(uri==null){
            route.setUri(new URI("lb://"+obj.getString("name")));
        }else{
            route.setUri(new URI(obj.getString("uri")));
        }
        Object predicates = obj.get("predicates");
        if (predicates != null) {
            JSONArray predicatesArray = JSONArray.parseArray(predicates.toString());
            List<PredicateDefinition> predicateDefinitionList =
                    predicatesArray.toJavaList(PredicateDefinition.class);
            route.setPredicates(predicateDefinitionList);
        }

        Object filters = obj.get("filters");
        if (filters != null) {
            JSONArray filtersArray = JSONArray.parseArray(filters.toString());
            List<FilterDefinition> filterDefinitionList
                    = filtersArray.toJavaList(FilterDefinition.class);
            route.setFilters(filterDefinitionList);
        }
        ls.add(route);
    }
    return ls;
}
 
Example 16
Source File: BaseOperService.java    From Jpom with MIT License 5 votes vote down vote up
public <E> List<E> list(Class<E> cls) {
    JSONObject jsonObject = getJSONObject();
    if (jsonObject == null) {
        return new ArrayList<>();
    }
    JSONArray jsonArray = formatToArray(jsonObject);
    return jsonArray.toJavaList(cls);
}
 
Example 17
Source File: PlainPermissionManager.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public void load() {

        Map<String, PlainAccessResource> plainAccessResourceMap = new HashMap<>();
        List<RemoteAddressStrategy> globalWhiteRemoteAddressStrategy = new ArrayList<>();

        JSONObject plainAclConfData = AclUtils.getYamlDataObject(fileHome + File.separator + fileName,
            JSONObject.class);
        if (plainAclConfData == null || plainAclConfData.isEmpty()) {
            throw new AclException(String.format("%s file  is not data", fileHome + File.separator + fileName));
        }
        log.info("Broker plain acl conf data is : ", plainAclConfData.toString());
        JSONArray globalWhiteRemoteAddressesList = plainAclConfData.getJSONArray("globalWhiteRemoteAddresses");
        if (globalWhiteRemoteAddressesList != null && !globalWhiteRemoteAddressesList.isEmpty()) {
            for (int i = 0; i < globalWhiteRemoteAddressesList.size(); i++) {
                globalWhiteRemoteAddressStrategy.add(remoteAddressStrategyFactory.
                        getRemoteAddressStrategy(globalWhiteRemoteAddressesList.getString(i)));
            }
        }

        JSONArray accounts = plainAclConfData.getJSONArray(AclConstants.CONFIG_ACCOUNTS);
        if (accounts != null && !accounts.isEmpty()) {
            List<PlainAccessConfig> plainAccessConfigList = accounts.toJavaList(PlainAccessConfig.class);
            for (PlainAccessConfig plainAccessConfig : plainAccessConfigList) {
                PlainAccessResource plainAccessResource = buildPlainAccessResource(plainAccessConfig);
                plainAccessResourceMap.put(plainAccessResource.getAccessKey(),plainAccessResource);
            }
        }

        // For loading dataversion part just
        JSONArray tempDataVersion = plainAclConfData.getJSONArray(AclConstants.CONFIG_DATA_VERSION);
        if (tempDataVersion != null && !tempDataVersion.isEmpty()) {
            List<DataVersion> dataVersion = tempDataVersion.toJavaList(DataVersion.class);
            DataVersion firstElement = dataVersion.get(0);
            this.dataVersion.assignNewOne(firstElement);
        }

        this.globalWhiteRemoteAddressStrategy = globalWhiteRemoteAddressStrategy;
        this.plainAccessResourceMap = plainAccessResourceMap;
    }
 
Example 18
Source File: InfluxHeartbeatDaoImpl.java    From sds with Apache License 2.0 4 votes vote down vote up
@Override
    public List<HeartbeatDO> queryHeartbeatList(String appGroupName, String appName, String point, Date startTime,
                                                Date endTime) {

        List<HeartbeatDO> result = Lists.newArrayList();

        if (StringUtils.isBlank(appGroupName) || StringUtils.isBlank(appName) || StringUtils.isBlank(point) || startTime == null || endTime == null) {
            return null;
        }

        /**
         * 构建influxdb的查询字符串
         */
        String queryStr = buildQueryString(appGroupName, appName, point, startTime, endTime);

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("q", queryStr);
        ResponseEntity<String> exchange = restTemplate.exchange(queryUrl, HttpMethod.POST, new HttpEntity<>(params,
                null), String.class);

        if (!exchange.getStatusCode().is2xxSuccessful() || StringUtils.isBlank(exchange.getBody())) {
            return null;
        }

//        {
//            "results": [{
//                "statement_id": 0,
//                "series": [{
//                    "name": "heartbeat",
//                    "columns": ["time", "appGroupName", "appName", "concurrentNum", "downgradeNum", "exceptionNum",
//                    "ip", "point", "timeoutNum", "visitNum"],
//                    "values": [
//                            ["2019-09-15T08:45:00.844Z", "htw", "htw-order", 15, 10, 99, "10.2.2.9", "visitPoint",
//                            23, 100000],
//                            ["2019-09-15T08:45:21.959Z", "htw", "htw-order", 15, 10, 99, "10.2.2.9", "visitPoint",
//                            23, 100000]
//                        ]
//                    }
//                ]
//            }]
//        }

        /**
         * todo 这块代码后续需要优化 manzhizhen
         */
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(INFLUXDB_DATE_FORMAT);
        JSONObject responseJsonObject = JSONObject.parseObject(exchange.getBody());
        JSONArray responseResultsJsonArray = responseJsonObject.getJSONArray("results");
        JSONObject resultJsonObject = (JSONObject) responseResultsJsonArray.get(0);
        JSONArray seriesJsonArray = resultJsonObject.getJSONArray("series");
        JSONObject heartbeatJsonObject = (JSONObject) seriesJsonArray.get(0);
        JSONArray columnsJsonArray = heartbeatJsonObject.getJSONArray("columns");
        JSONArray valuesJsonArray = heartbeatJsonObject.getJSONArray("values");

        List<Object> conlumsList = columnsJsonArray.toJavaList(Object.class);
        List<Object> valuesList = valuesJsonArray.toJavaList(Object.class);
        Map<String, Object> map = Maps.newHashMap();
        for (int i = 0; i < valuesList.size(); i++) {
            for (int j = 0; j < conlumsList.size(); j++) {
                map.put(conlumsList.get(j).toString(), ((List) valuesList.get(i)).get(j));
            }

            HeartbeatDO heartbeatDO = new HeartbeatDO();
            try {
                heartbeatDO.setAppGroupName(map.get("appGroupName").toString());
                heartbeatDO.setAppName(map.get("appName").toString());
                heartbeatDO.setPoint(map.get("point").toString());
                heartbeatDO.setDowngradeNum(Long.valueOf(map.get("downgradeNum").toString()));
                heartbeatDO.setVisitNum(Long.valueOf(map.get("visitNum").toString()));
                heartbeatDO.setExceptionNum(Long.valueOf(map.get("exceptionNum").toString()));
                heartbeatDO.setTimeoutNum(Long.valueOf(map.get("timeoutNum").toString()));
                heartbeatDO.setMaxConcurrentNum(Integer.valueOf(map.get("concurrentNum").toString()));
                heartbeatDO.setStatisticsCycleTime(simpleDateFormat.parse(map.get("time").toString()));

                result.add(heartbeatDO);

            } catch (Exception e) {
                logger.warn("InfluxHeartbeatDaoImpl#queryHeartbeatList 心跳数据转换异常:" + JSON.toJSONString(map), e);
            }
        }

        return result;
    }
 
Example 19
Source File: MonitorListController.java    From Jpom with MIT License 4 votes vote down vote up
/**
 * 增加或修改监控
 *
 * @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, "修改成功");
}
 
Example 20
Source File: UserEditController.java    From Jpom with MIT License 4 votes vote down vote up
private String parseUser(UserModel userModel, boolean create) {
    String id = getParameter("id");
    if (StrUtil.isEmpty(id) || id.length() < UserModel.USER_NAME_MIN_LEN) {
        return JsonMessage.getString(400, "登录名不能为空,并且长度必须不小于" + UserModel.USER_NAME_MIN_LEN);
    }
    if (UserModel.SYSTEM_OCCUPY_NAME.equals(id) || UserModel.SYSTEM_ADMIN.equals(id)) {
        return JsonMessage.getString(401, "当前登录名已经被系统占用");
    }
    if (!checkPathSafe(id)) {
        return JsonMessage.getString(400, "登录名不能包含特殊字符");
    }
    userModel.setId(id);

    String name = getParameter("name");
    if (StrUtil.isEmpty(name)) {
        return JsonMessage.getString(405, "请输入账户昵称");
    }
    int len = name.length();
    if (len > 10 || len < 2) {
        return JsonMessage.getString(405, "昵称长度只能是2-10");
    }
    userModel.setName(name);

    UserModel userName = getUser();
    String password = getParameter("password");
    if (create || StrUtil.isNotEmpty(password)) {
        if (StrUtil.isEmpty(password)) {
            return JsonMessage.getString(400, "密码不能为空");
        }
        // 修改用户
        if (!create && !userName.isSystemUser()) {
            return JsonMessage.getString(401, "只有系统管理员才能重置用户密码");
        }
        userModel.setPassword(password);
    }
    //
    String roles = getParameter("roles");
    JSONArray jsonArray = JSONArray.parseArray(roles);
    List<String> rolesList = jsonArray.toJavaList(String.class);
    if (rolesList == null || rolesList.isEmpty()) {
        return JsonMessage.getString(405, "请选择一个角色");
    }
    userModel.setRoles(rolesList);
    return null;
}