Java Code Examples for org.apache.commons.lang.math.NumberUtils#isNumber()

The following examples show how to use org.apache.commons.lang.math.NumberUtils#isNumber() . 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: DefaultExpressionEvaluator.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Evaluate server side variables and add them to a map with the key being the original var or call evaluated
 * to be replaced later by the evaluated value.
 *
 * @param exp the expression to evaluate known server variables and methods
 * @param context the expression evaluation context
 * @return map of keys that are the original expression/variable, and the replacement value
 */
private Map<String, String> evaluateServerSideVariables(String exp, Map<String, Object> context) {
    Map<String, String> serverEvaluations = new HashMap<String, String>();
    Matcher matcher = SERVER_EVALUATION_PATTERN.matcher(exp);
    while (matcher.find()) {
        String spelMethodCall = matcher.group(1);

        Object value = this.evaluateExpression(context, spelMethodCall);

        // Convert the value to expected js equivalent
        if (value == null) {
            serverEvaluations.put(spelMethodCall, "null");
        } else if (value instanceof String) {
            serverEvaluations.put(spelMethodCall, "\"" + value + "\"");
        } else if (value instanceof Boolean || NumberUtils.isNumber(value.toString())) {
            serverEvaluations.put(spelMethodCall, value.toString());
        } else {
            // Corner case, assume the object gives us something meaningful from toString, wrap in quotes
            serverEvaluations.put(spelMethodCall, "\"" + value.toString() + "\"");
        }
    }

    return serverEvaluations;
}
 
Example 2
Source File: ShareController.java    From FlyCms with MIT License 6 votes vote down vote up
@GetMapping(value = "/ucenter/share/edit-{id}")
public String editShare(@PathVariable(value = "id", required = false) String id,ModelMap modelMap){
    if (!NumberUtils.isNumber(id)) {
        return theme.getPcTemplate("404");
    }
    Share share=shareService.findShareById(Long.parseLong(id),0);
    if(share==null){
        return theme.getPcTemplate("404");
    }
    if (getUser().getUserId() != share.getUserId()) {
        modelMap.addAttribute("message", "只能修改属于自己的文章!");
        return theme.getPcTemplate("message_tip");
    }
    modelMap.addAttribute("share", share);
    modelMap.addAttribute("user", getUser());
    return theme.getPcTemplate("share/edit_share");
}
 
Example 3
Source File: ConfigurationCommands.java    From mobycraft with Apache License 2.0 6 votes vote down vote up
public void setPollRate() {
	if (Utils.checkIfArgIsNull(args, 0)) {
		sendErrorMessage("Poll rate is not specified! Command is used as /docker poll_rate <rate> .");
		return;
	}
	
	if (!NumberUtils.isNumber(arg1)) {
		sendErrorMessage("The argument \"" + arg1 + "\" is invalid (must be a positive integer)! Command is used as /docker poll_rate <rate> .");
		return;
	}

	configProperties.getPollRateProperty().setValue(arg1);
	Mobycraft.config.save();
	int intArg1 = Integer.parseInt(arg1);
	if (intArg1 < 1) {
		if (intArg1 == 0) {
			sendErrorMessage("The argument \"" + arg1 + "\" is invalid (can't be zero)! Command is used as /docker poll_rate <rate> .");
		} else {
			sendErrorMessage("The argument \"" + arg1 + "\" is invalid (can't be negative)! Command is used as /docker poll_rate <rate> .");
		}
	} else if (intArg1 == 1) {
		sendConfirmMessage("Poll rate set to 1 second");
	} else {
		sendConfirmMessage("Poll rate set to " + arg1 + " seconds");
	}
}
 
Example 4
Source File: ArticleController.java    From FlyCms with MIT License 6 votes vote down vote up
@GetMapping(value = "/ucenter/article/edit-{id}")
public String getEditArticle(@PathVariable(value = "id", required = false) String id,ModelMap modelMap){
    if (!NumberUtils.isNumber(id)) {
        return theme.getPcTemplate("404");
    }
    Article article=articleService.findArticleById(Long.parseLong(id), 0);
    if(article==null){
        return theme.getPcTemplate("404");
    }
    if (!getUser().getUserId().equals(article.getUserId())) {
        modelMap.addAttribute("message", "只能修改属于自己的文章!");
        return theme.getPcTemplate("message_tip");
    }
    //article.setContent(StringEscapeUtils.escapeHtml4(article.getContent()));
    modelMap.addAttribute("article", article);
    modelMap.addAttribute("user", getUser());
    return theme.getPcTemplate("article/edit_article");
}
 
Example 5
Source File: UserAdminController.java    From FlyCms with MIT License 6 votes vote down vote up
@PostMapping("/groupsort_update")
@ResponseBody
public DataVo updateGroupSort(@RequestParam(value = "id", required = false) String id,@RequestParam(value = "sort", required = false) String sort){
    DataVo data = DataVo.failure("操作失败");
    try {
        if (!NumberUtils.isNumber(id)) {
            return data=DataVo.failure("话题参数错误");
        }
        if (!NumberUtils.isNumber(sort)) {
            return data=DataVo.failure("话题参数错误");
        }
        data = userGroupService.updateGroupSort(Long.parseLong(id),Integer.valueOf(sort));
    } catch (Exception e) {
        data = DataVo.failure(e.getMessage());
    }
    return data;
}
 
Example 6
Source File: SubProcessParser.java    From snakerflow with Apache License 2.0 6 votes vote down vote up
/**
 * 解析decisition节点的特有属性expr
 */
protected void parseNode(NodeModel node, Element element) {
	SubProcessModel model = (SubProcessModel)node;
	model.setProcessName(element.getAttribute(ATTR_PROCESSNAME));
	String version = element.getAttribute(ATTR_VERSION);
	int ver = 0;
       if(NumberUtils.isNumber(version)) {
       	ver = Integer.parseInt(version);
       }
	model.setVersion(ver);
	String form = element.getAttribute(ATTR_FORM);
	if(StringHelper.isNotEmpty(form)) {
		model.setForm(form);
	} else {
		model.setForm(ConfigHelper.getProperty("subprocessurl"));
	}
}
 
Example 7
Source File: ElaborationManagerImpl.java    From zstack with Apache License 2.0 6 votes vote down vote up
private List<ElaborationVO> getMissedElatorations(Long repeats, String from) {
    Long times = repeats != null ? repeats : 1L;
    if (from == null) {
        return Q.New(ElaborationVO.class).eq(ElaborationVO_.matched, false).gte(ElaborationVO_.repeats, times).list();
    } else {
        if (TimeUtils.isValidTimestampFormat(from)) {
            long start = TimeUtils.parseFormatStringToTimeStamp(from);
            return Q.New(ElaborationVO.class).eq(ElaborationVO_.matched, false).gte(ElaborationVO_.repeats, times).
                    gte(ElaborationVO_.lastOpDate, new Timestamp(start)).list();
        } else if (NumberUtils.isNumber(from)) {
            try {
                return Q.New(ElaborationVO.class).eq(ElaborationVO_.matched, false).gte(ElaborationVO_.repeats, times).
                        gte(ElaborationVO_.lastOpDate, new Timestamp(Long.parseLong(from))).list();
            } catch (NumberFormatException e) {
                throw new OperationFailureException(argerr("%s is not a Long value Number", from));
            }
        } else {
            throw new OperationFailureException(argerr("arg 'startTime' should format like 'yyyy-MM-dd HH:mm:ss' or '1545380003000'"));
        }
    }
}
 
Example 8
Source File: QuestionController.java    From FlyCms with MIT License 6 votes vote down vote up
@ResponseBody
@PostMapping(value = "/ucenter/answer/add")
public DataVo addAnswer(@RequestParam(value = "questionId", required = false) String questionId,
                        @RequestParam(value = "content", required = false) String content,
                          ModelMap modelMap) {
    DataVo data = DataVo.failure("操作失败");
    try {
        if (!NumberUtils.isNumber(questionId)) {
            return data=DataVo.failure("话题参数错误");
        }
        Question question=questionService.findQuestionById(Long.parseLong(questionId),2);
        if(question==null){
            return data=DataVo.failure("该话题不存在或已删除");
        }
        //content=StringHelperUtil.htmlReplace(content);
        if (StringUtils.isBlank(content)) {
            return DataVo.failure("答案内容不能为空");
        }
        data=answerService.addAnswer(Long.parseLong(questionId),getUser().getUserId(),content);
    } catch (Exception e) {
        data = DataVo.failure(e.getMessage());
    }
    return data;
}
 
Example 9
Source File: Parser.java    From CardinalPGM with MIT License 6 votes vote down vote up
public static KitItem getKitItem(Element element) {
    ItemStack itemStack = getItem(element);
    int slot = -1;
    String slotString = element.getAttributeValue("slot", "-1");
    if (NumberUtils.isNumber(slotString)) {
        slot = Integer.parseInt(slotString);
    } else {
        if (!slotString.startsWith("slot.")) slotString = "slot." + slotString;
        try {
            CommandReplaceItem replaceItem = new CommandReplaceItem();
            Method m = CommandReplaceItem.class.getDeclaredMethod("e", String.class); // Returns inventory slot (int)
            m.setAccessible(true);                                                    // from a mojang string inventory
            slot = (int)m.invoke(replaceItem, slotString);                            // like "slot.weapon.offhand"
        } catch (NoSuchMethodException|IllegalAccessException|InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    return new KitItem(itemStack, slot);
}
 
Example 10
Source File: TopicsController.java    From FlyCms with MIT License 6 votes vote down vote up
@ResponseBody
@PostMapping(value = "/topics/follow")
public DataVo topicsFollow(@RequestParam(value = "id", required = false) String id) {
    DataVo data = DataVo.failure("操作失败");
    try {
        if (!NumberUtils.isNumber(id)) {
            return data=DataVo.failure("话题id参数错误");
        }
        if(getUser()==null){
            return data=DataVo.failure("请登陆后关注");
        }
        data=topicService.addTopicAndUser(getUser().getUserId(),Long.parseLong(id));
    } catch (Exception e) {
        data = DataVo.failure(e.getMessage());
    }
    return data;
}
 
Example 11
Source File: Metrics.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
private Collection<? extends FalconReportObject> getGlobalStatus() throws SQLException, ClassNotFoundException {
        Set<FalconReportObject> reportObjectSet = new HashSet<>();
        String sql = "SHOW /*!50001 GLOBAL */ STATUS";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()){
            String value = rs.getString(2);
            if (NumberUtils.isNumber(value)){
                String metric = rs.getString(1);
                FalconReportObject falconReportObject = new FalconReportObject();
                MetricsCommon.setReportCommonValue(falconReportObject,plugin.step());
                falconReportObject.setCounterType(CounterType.GAUGE);
                //时间戳会统一上报
//                falconReportObject.setTimestamp(System.currentTimeMillis() / 1000);
                falconReportObject.setMetric(metric);
                falconReportObject.setValue(value);
                falconReportObject.appendTags(MetricsCommon.getTags(plugin.agentSignName(),plugin,plugin.serverName()));
                reportObjectSet.add(falconReportObject);
            }
        }
        rs.close();
        pstmt.close();
        return reportObjectSet;
    }
 
Example 12
Source File: UserController.java    From FlyCms with MIT License 6 votes vote down vote up
@ResponseBody
@PostMapping(value = "/ucenter/user/follow")
public DataVo userFollow(@RequestParam(value = "id", required = false) String id) {
    DataVo data = DataVo.failure("操作失败");
    try {
        if (!NumberUtils.isNumber(id)) {
            return data=DataVo.failure("问题参数错误");
        }
        if(getUser()==null){
            return data=DataVo.failure("请登陆后关注");
        }
        if((getUser().getUserId().equals(Long.parseLong(id)))){
            return data=DataVo.failure("无法关注自己!");
        }
        data=userService.addUserFans(Long.parseLong(id),getUser().getUserId());
    } catch (Exception e) {
        data = DataVo.failure(e.getMessage());
    }
    return data;
}
 
Example 13
Source File: ArticleAdminController.java    From FlyCms with MIT License 6 votes vote down vote up
@PostMapping("/category_drags")
@ResponseBody
public DataVo editCategoryDrags(@RequestParam(value = "id", required = false) String id,@RequestParam(value = "pId", required = false) String pId){
    DataVo data = DataVo.failure("操作失败");
    try {
        if (StringUtils.isBlank(id)) {
            return data = DataVo.failure("分类id不能为空");
        }
        if (!NumberUtils.isNumber(id)) {
            data = DataVo.failure("分类id错误!");
        }
        if (StringUtils.isBlank(pId)) {
            return DataVo.failure("未获取到父级id");
        }
        if (!NumberUtils.isNumber(pId)) {
            data = DataVo.failure("父级id错误!");
        }
        data = articleCategoryService.editCategoryDragsById(Long.parseLong(id),Long.parseLong(pId));
    } catch (Exception e) {
        data = DataVo.failure(e.getMessage());
    }
    return data;
}
 
Example 14
Source File: Parser.java    From CardinalPGM with MIT License 5 votes vote down vote up
public static AttributeModifier.Operation getOperation(String operation) {
    if (NumberUtils.isNumber(operation)) {
        return AttributeModifier.Operation.fromOpcode(Integer.parseInt(operation));
    } else {
        switch (operation.toLowerCase()) {
            case("add"):
                return AttributeModifier.Operation.ADD_NUMBER;
            case("base"):
                return AttributeModifier.Operation.ADD_SCALAR;
            case("multiply"):
                return AttributeModifier.Operation.MULTIPLY_SCALAR_1;
        }
    }
    return AttributeModifier.Operation.ADD_NUMBER;
}
 
Example 15
Source File: ScoreAdminController.java    From FlyCms with MIT License 5 votes vote down vote up
@PostMapping("/rule_status")
@ResponseBody
public DataVo updateRuleStatus(@RequestParam(value = "id", required = false) String id){
    if (!NumberUtils.isNumber(id)) {
        return DataVo.failure("参数传递错误");
    }
    return scoreRuleService.updateRuleStatus(Long.parseLong(id));
}
 
Example 16
Source File: ConfigAdminController.java    From FlyCms with MIT License 5 votes vote down vote up
/**u
 * 修改用户信息设置配置
 */
@ResponseBody
@PostMapping(value = "/userconfig_updagte")
public DataVo updagteUserConfig(
        @RequestParam(value = "user_reg") String user_reg,
        @RequestParam(value = "user_reg_verify") String user_reg_verify,
        @RequestParam(value = "user_activation_role") String user_activation_role,
        @RequestParam(value = "user_role") String user_role,
        @RequestParam(value = "user_question_verify") String user_question_verify,
        @RequestParam(value = "user_answer_verify") String user_answer_verify
) {
    DataVo data = DataVo.failure("操作失败");
    try {
        if (!NumberUtils.isNumber(user_role)) {
            return data=DataVo.failure("权限参数错误");
        }
        if (!NumberUtils.isNumber(user_question_verify)) {
            return data=DataVo.failure("问答审核参数错误");
        }
        if (!NumberUtils.isNumber(user_answer_verify)) {
            return data=DataVo.failure("回答审核参数错误");
        }
        configService.updagteConfigByKey("user_reg", user_reg);
        configService.updagteConfigByKey("user_reg_verify", user_reg_verify);
        configService.updagteConfigByKey("user_activation_role", user_activation_role);
        configService.updagteConfigByKey("user_role", user_role);
        configService.updagteConfigByKey("user_question_verify", user_question_verify);
        configService.updagteConfigByKey("user_answer_verify", user_answer_verify);
        return DataVo.success("操作成功", DataVo.NOOP);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        DataVo.failure("未知错误!");
    }
    return data;
}
 
Example 17
Source File: ArticleController.java    From FlyCms with MIT License 5 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/findArticleById/{id}")
public DataVo findArticleById(@PathVariable(value = "id", required = false) String id,ModelMap modelMap){
    DataVo data = DataVo.failure("操作失败");
    if (!NumberUtils.isNumber(id)) {
        return data = DataVo.failure("id参数错误");
    }
    Article article=articleService.findArticleById(Long.parseLong(id), 2);
    if(article==null){
        return data = DataVo.failure("该内容不存在或者未审核!");
    }
    Map<String, Object> map = new HashMap<>();
    map.put("content",article.getContent());
    return DataVo.success(map);
}
 
Example 18
Source File: FalconReportObject.java    From SuitAgent with Apache License 2.0 5 votes vote down vote up
public void setValue(String value) {
    if (NumberUtils.isNumber(value) && value.contains("E")) {
        this.value = String.format("%.3f",NumberUtils.toDouble(value)).replace(".000","");
    }else {
        this.value = value;
    }
}
 
Example 19
Source File: Params.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public Params build() {
  Params params = new Params();
  params.uuid = uuid;
  params.blockRepoConns = blockRepoConns;
  params.repoName = repoName;
  params.repoUsername = repoUsername;
  params.trustRepoUser = trustRepoUser;
  params.repoPassword = repoPassword;
  params.inputDir = inputDir;
  params.inputFile = inputFile;
  params.listRepoFiles = listRepoFiles;
  params.listRepoDirs = listRepoDirs;
  params.exportRepo = exportRepo;
  params.localFile = localFile;
  params.localJarFile = localJarFile;
  params.localInitialDir = localInitialDir;
  params.listRepos = listRepos;
  params.safeMode = safeMode;
  params.metrics = metrics;
  params.listFileParams = listFileParams;
  params.logLevel = logLevel;
  params.maxLogLines = maxLogLines;
  params.maxLogTimeout = maxLogTimeout;
  params.logFile = logFile;
  params.oldLogFile = oldLogFile;
  params.version = version;
  params.resultSetStepName = resultSetStepName;
  params.resultSetCopyNumber = NumberUtils.isNumber( resultSetCopyNumber ) ? resultSetCopyNumber : "0" /* default */;
  params.base64Zip = base64Zip;
  params.namedParams = namedParams;
  params.customNamedParams = customNamedParams;

  return params;
}
 
Example 20
Source File: JMXMetricsValue.java    From OpenFalcon-SuitAgent with Apache License 2.0 4 votes vote down vote up
/**
 * 生成监控报告的辅助方法
 *
 * @param kitObjectNameMetricses
 * @param metricsValueInfo
 * @return
 */
private Set<FalconReportObject> generatorReportObject(Collection<KitObjectNameMetrics> kitObjectNameMetricses, JMXMetricsValueInfo metricsValueInfo) {
    Set<FalconReportObject> result = new HashSet<>();

    //用于判断监控值是否重复添加,若出现重复添加,进行监控值比较
    Map<String, FalconReportObject> repeat = new HashMap<>();

    for (KitObjectNameMetrics kitObjectNameMetrics : kitObjectNameMetricses) {
        JMXObjectNameInfo jmxObjectNameInfo = kitObjectNameMetrics.jmxObjectNameInfo;
        JMXMetricsConfiguration jmxMetricsConfiguration = kitObjectNameMetrics.jmxMetricsConfiguration;
        Object metricsValue = jmxObjectNameInfo.getMetricsValue().get(jmxMetricsConfiguration.getMetrics());
        if (metricsValue != null) {
            //服务的标识后缀名
            String name = metricsValueInfo.getJmxConnectionInfo().getName();

            FalconReportObject requestObject = new FalconReportObject();
            setReportCommonValue(requestObject, jmxPlugin.step());
            requestObject.setMetric(getMetricsName(jmxMetricsConfiguration.getAlias()));//设置push obj 的 metrics
            try {
                //设置push obj 的 Counter
                requestObject.setCounterType(CounterType.valueOf(jmxMetricsConfiguration.getCounterType()));
            } catch (IllegalArgumentException e) {
                log.error("错误的{} counterType配置:{},只能是 {} 或 {},未修正前,将忽略此监控值", jmxMetricsConfiguration.getAlias(), jmxMetricsConfiguration.getCounterType(), CounterType.COUNTER, CounterType.GAUGE, e);
                continue;
            }
            requestObject.setTimestamp(metricsValueInfo.getTimestamp());
            requestObject.setObjectName(jmxObjectNameInfo.getObjectName());
            Object newValue = executeJsExpress(kitObjectNameMetrics.jmxMetricsConfiguration.getValueExpress(), metricsValue.toString());
            if (NumberUtils.isNumber(String.valueOf(newValue).trim())) {
                requestObject.setValue(String.valueOf(newValue).trim());
            } else {
                log.error("异常:监控指标值{} - {} : {}不能转换为数字,将忽略此监控值", jmxMetricsConfiguration.getObjectName(), jmxMetricsConfiguration.getMetrics(), metricsValue);
                continue;
            }

            requestObject.appendTags(getTags(name, jmxPlugin, jmxPlugin.serverName(), MetricsType.JMX_OBJECT_CONF)).appendTags(jmxMetricsConfiguration.getTag());

            //监控值重复性判断
            FalconReportObject reportInRepeat = repeat.get(jmxMetricsConfiguration.getMetrics());
            if (reportInRepeat == null) {
                //第一次添加
                result.add(requestObject);
                repeat.put(jmxMetricsConfiguration.getMetrics(), requestObject);
            } else {
                if (!reportInRepeat.equals(requestObject)) {
                    // 若已有记录而且不相同,进行区分保存
                    result.remove(reportInRepeat);
                    reportInRepeat.appendTags(requestObject.getObjectName().toString());//JMX 的ObjectName名称符合tag格式
                    result.add(reportInRepeat);

                    requestObject.appendTags(requestObject.getObjectName().toString());
                    if (!result.contains(requestObject)) {
                        result.add(requestObject);
                    }
                }
            }
        }
    }
    return result;
}