下面列出了怎么用org.apache.commons.lang.math.NumberUtils的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 执行返回数字类型的脚本
* @param script
* @return
*/
private DetectResult.Metric executeNumberScript(Script script,int step) {
if (script != null && script.isValid()){
try {
String cmd = "";
if (script.getScriptType() == ScriptType.SHELL){
cmd = "sh " + script.getPath();
}
if (script.getScriptType() == ScriptType.PYTHON){
cmd = "python " + script.getPath();
}
CommandUtilForUnix.ExecuteResult executeResult = CommandUtilForUnix.execWithReadTimeLimit(cmd,false,5);
String value = executeResult.msg.trim();
if (NumberUtils.isNumber(value)){
return new DetectResult.Metric(script.getMetric(),value, CounterType.valueOf(script.getCounterType()), script.getTags(),step);
}
} catch (Exception e) {
log.error("脚本执行异常",e);
}
}
return null;
}
/**
* Display edit page for existed taskList item.
*/
@RequestMapping(path = "/editCondition", method = RequestMethod.POST)
public String editCondition(@ModelAttribute TaskListConditionForm taskListConditionForm,
HttpServletRequest request) {
// get back sessionMAP
String sessionMapID = WebUtil.readStrParam(request, TaskListConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
.getAttribute(sessionMapID);
int sequenceId = NumberUtils.stringToInt(request.getParameter(TaskListConstants.PARAM_SEQUENCE_ID), -1);
TaskListCondition item = null;
if (sequenceId != -1) {
SortedSet<TaskListCondition> conditionList = getTaskListConditionList(sessionMap);
List<TaskListCondition> rList = new ArrayList<>(conditionList);
item = rList.get(sequenceId);
if (item != null) {
populateConditionToForm(sequenceId, item, taskListConditionForm, request);
}
}
populateFormWithPossibleItems(taskListConditionForm, request);
return item == null ? null : "pages/authoring/parts/addcondition";
}
/**
* Display edit page for an existing condition.
*/
@RequestMapping("/editCondition")
public String editCondition(@ModelAttribute ForumConditionForm forumConditionForm, HttpServletRequest request) {
String sessionMapID = forumConditionForm.getSessionMapID();
SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
int orderId = NumberUtils.stringToInt(request.getParameter(ForumConstants.PARAM_ORDER_ID), -1);
ForumCondition condition = null;
if (orderId != -1) {
SortedSet<ForumCondition> conditionSet = getForumConditionSet(sessionMap);
List<ForumCondition> conditionList = new ArrayList<>(conditionSet);
condition = conditionList.get(orderId);
if (condition != null) {
populateConditionToForm(orderId, condition, forumConditionForm, request);
}
}
populateFormWithPossibleItems(forumConditionForm, request);
return condition == null ? null : "jsps/authoring/addCondition";
}
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
if (!NumberUtils.isDigits(args[1])) {
throw new CliException("Operator ID must be a number");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_PHYSICAL_PLAN_OPERATORS).path(args[1]).path("properties");
final JSONObject request = new JSONObject();
request.put(args[2], args[3]);
JSONObject response = getResource(uriSpec, currentApp, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, request);
}
});
printJson(response);
}
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {
Object object = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.latest_fork_usec.getValue());
if (object == null) {
return null;
}
// 关系比对
long latestForkUsec = NumberUtils.toLong(object.toString());
boolean compareRight = isCompareLongRight(instanceAlertConfig, latestForkUsec);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(latestForkUsec),
instanceInfo.getAppId(), EMPTY));
}
@ResponseBody
@PostMapping(value = "/ucenter/favorite/add")
public DataVo addFavorite(@RequestParam(value = "id", required = false) String id,@RequestParam(value = "type", required = false) String type) {
DataVo data = DataVo.failure("操作失败");
try {
if (!NumberUtils.isNumber(id)) {
return data=DataVo.failure("话题id参数错误");
}
if (!NumberUtils.isNumber(type)) {
return data=DataVo.failure("话题id参数错误");
}
if(getUser()==null){
return data=DataVo.failure("请登陆后关注");
}
data=favoriteService.addFavorite(getUser().getUserId(),Integer.valueOf(type),Long.parseLong(id));
} catch (Exception e) {
data = DataVo.failure(e.getMessage());
}
return data;
}
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;
}
/** {@inheritDoc} */
@Override
public void execute(final MutableShoppingCart shoppingCart, final Map<String, Object> parameters) {
if (parameters.containsKey(getCmdKey())) {
final Long value = NumberUtils.createLong(String.valueOf(parameters.get(getCmdKey())));
if (value != null && !value.equals(shoppingCart.getShoppingContext().getShopId())) {
shoppingCart.getShoppingContext().clearContext(); // If we are setting new shop we must re-authenticate
final Shop shop = shopService.getById(value);
final MutableShoppingContext ctx = shoppingCart.getShoppingContext();
ctx.setShopId(shop.getShopId());
ctx.setShopCode(shop.getCode());
setDefaultOrderInfoOptions(shoppingCart);
setDefaultTaxOptions(shoppingCart);
markDirty(shoppingCart);
}
}
}
private int checkNumeric(Object paramValue, VNumeric vNumeric) {
boolean _matched = false;
boolean _flag = false;
try {
Number _number = NumberUtils.createNumber(BlurObject.bind(paramValue).toStringValue());
if (_number == null) {
_matched = true;
_flag = true;
} else {
if (vNumeric.min() > 0 && _number.doubleValue() < vNumeric.min()) {
_matched = true;
} else if (vNumeric.max() > 0 && _number.doubleValue() > vNumeric.max()) {
_matched = true;
}
}
} catch (Exception e) {
_matched = true;
_flag = true;
}
return _matched ? (_flag ? 2 : 1) : 0;
}
/**
* Remove imageGallery item from HttpSession list and update page display. As authoring rule, all persist only
* happen when user submit whole page. So this remove is just impact HttpSession values.
*/
@RequestMapping("/removeImage")
public String removeImage(HttpServletRequest request) {
// get back sessionMAP
String sessionMapID = WebUtil.readStrParam(request, ImageGalleryConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
.getAttribute(sessionMapID);
int itemIdx = NumberUtils.stringToInt(request.getParameter(ImageGalleryConstants.PARAM_IMAGE_INDEX), -1);
if (itemIdx != -1) {
SortedSet<ImageGalleryItem> imageGalleryList = getImageList(sessionMap);
List<ImageGalleryItem> rList = new ArrayList<>(imageGalleryList);
ImageGalleryItem item = rList.remove(itemIdx);
imageGalleryList.clear();
imageGalleryList.addAll(rList);
// add to delList
List<ImageGalleryItem> delList = getDeletedImageGalleryItemList(sessionMap);
delList.add(item);
}
request.setAttribute(ImageGalleryConstants.ATTR_SESSION_MAP_ID, sessionMapID);
return "pages/authoring/parts/itemlist";
}
@PostMapping("/question-status")
@ResponseBody
public DataVo updateQuestionStatusById(@RequestParam(value = "id", required = false) String id,
@RequestParam(value = "status", required = false) String status,
@RequestParam(value = "recommend", defaultValue = "0") String recommend) throws Exception{
DataVo data = DataVo.failure("操作失败");
if (!NumberUtils.isNumber(id)) {
return data = DataVo.failure("id参数错误");
}
if (!NumberUtils.isNumber(status)) {
return data = DataVo.failure("审核状态参数错误");
}
if (!StringUtils.isBlank(recommend)) {
if (!NumberUtils.isNumber(recommend)) {
return data = DataVo.failure("推荐参数错误");
}
}
data = questionService.updateQuestionStatusById(Long.parseLong(id),Integer.valueOf(status),Integer.valueOf(recommend));
return data;
}
private Collection<? extends FalconReportObject> getGlobalVariables() throws SQLException, ClassNotFoundException {
Set<FalconReportObject> reportObjectSet = new HashSet<>();
String sql = "SHOW /*!50001 GLOBAL */ VARIABLES";
PreparedStatement pstmt = connection.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
String metric = rs.getString(1);
String value = rs.getString(2);
if (NumberUtils.isNumber(value)){
//收集值为数字的结果
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;
}
/**
* 添加扩容配置
*
* @param appScaleText 扩容配置
* @param appAuditId 审批id
*/
@RequestMapping(value = "/addAppScaleApply")
public ModelAndView doAddAppScaleApply(HttpServletRequest request,
HttpServletResponse response, Model model, String appScaleText,
Long appAuditId, Long appId) {
AppUser appUser = getUserInfo(request);
logger.error("user {} appScaleApplay : appScaleText={},appAuditId:{}", appUser.getName(), appScaleText, appAuditId);
boolean isSuccess = false;
if (appAuditId != null && StringUtils.isNotBlank(appScaleText)) {
int mem = NumberUtils.toInt(appScaleText, 0);
try {
isSuccess = appDeployCenter.verticalExpansion(appId, appAuditId, mem);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
} else {
logger.error("appScaleApplay error param: appScaleText={},appAuditId:{}", appScaleText, appAuditId);
}
logger.error("user {} appScaleApplay: appScaleText={},appAuditId:{}, result is {}", appUser.getName(), appScaleText, appAuditId, isSuccess);
return new ModelAndView("redirect:/manage/app/auditList");
}
/**
* Display edit page for existed taskList item.
*/
@RequestMapping("editItemInit")
public String editItemInit(@ModelAttribute TaskListItemForm taskListItemForm, HttpServletRequest request) {
// get back sessionMAP
String sessionMapID = WebUtil.readStrParam(request, TaskListConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
.getAttribute(sessionMapID);
int itemIdx = NumberUtils.stringToInt(request.getParameter(TaskListConstants.PARAM_ITEM_INDEX), -1);
TaskListItem item = null;
if (itemIdx != -1) {
SortedSet<TaskListItem> taskListList = getTaskListItemList(sessionMap);
List<TaskListItem> rList = new ArrayList<>(taskListList);
item = rList.get(itemIdx);
if (item != null) {
populateItemToForm(itemIdx, item, taskListItemForm, request);
}
}
return item == null ? null : "pages/authoring/parts/addtask";
}
public static int getInt( Object obj ) {
if ( obj instanceof Integer ) {
return ( Integer ) obj;
}
if ( obj instanceof Number ) {
return ( ( Number ) obj ).intValue();
}
if ( obj instanceof String ) {
return NumberUtils.toInt( ( String ) obj );
}
if ( obj instanceof Date ) {
return ( int ) ( ( Date ) obj ).getTime();
}
if ( obj instanceof byte[] ) {
return getInt( ( byte[] ) obj );
}
if ( obj instanceof ByteBuffer ) {
return getInt( ( ByteBuffer ) obj );
}
return 0;
}
/**
* Ajax call, remove the given line of instruction of survey item.
*
* @param mapping
* @param form
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/removeInstruction")
public String removeInstruction(HttpServletRequest request) {
int count = NumberUtils.stringToInt(request.getParameter(AuthoringController.INSTRUCTION_ITEM_COUNT), 0);
int removeIdx = NumberUtils.stringToInt(request.getParameter("removeIdx"), -1);
List instructionList = new ArrayList(count - 1);
for (int idx = 0; idx < count; idx++) {
String item = request.getParameter(AuthoringController.INSTRUCTION_ITEM_DESC_PREFIX + idx);
if (idx == removeIdx) {
continue;
}
if (item == null) {
instructionList.add("");
} else {
instructionList.add(item);
}
}
request.setAttribute(SurveyConstants.ATTR_INSTRUCTION_LIST, instructionList);
return "pages/authoring/parts/instructions";
}
@Transactional
public DataVo editShareCategory(ShareCategory shareCategory){
DataVo data = DataVo.failure("操作失败");
if(this.checkShareCategoryByName(shareCategory.getName(),shareCategory.getId())){
return data = DataVo.failure("分类名称不得重复");
}
if (StringUtils.isBlank(shareCategory.getId().toString())) {
return data = DataVo.failure("分类id不能为空");
}
if (!NumberUtils.isNumber(shareCategory.getId().toString())) {
return data = DataVo.failure("分类id错误!");
}
//转换为数组
String[] str = shareCategory.getCategoryId().split(",");
if((Integer.valueOf(str[str.length - 1])).equals(shareCategory.getId())){
return data = DataVo.failure("不能选自己为父级目录");
}
shareCategory.setFatherId(Long.parseLong(str[str.length - 1]));
shareCategoryDao.editShareCategoryById(shareCategory);
if(shareCategory.getId()>0){
data = DataVo.success("更新成功");
}else{
data = DataVo.failure("添加失败!");
}
return data;
}
public static Object parseValue( String value )
{
if ( value == null || StringUtils.isEmpty( value ) )
{
return null;
}
else if ( NumberUtils.isNumber( value ) )
{
return value;
}
else
{
return "'" + value + "'";
}
}
/**
* Update image's title and description set by monitor
*/
@RequestMapping(path = "/updateImage", method = RequestMethod.POST)
public String updateImage(@ModelAttribute ImageGalleryItemForm imageGalleryItemForm, HttpServletRequest request) {
// get back sessionMAP
String sessionMapID = imageGalleryItemForm.getSessionMapID();
request.setAttribute(ImageGalleryConstants.ATTR_SESSION_MAP_ID, sessionMapID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
.getAttribute(imageGalleryItemForm.getSessionMapID());
Long contentId = (Long) sessionMap.get(ImageGalleryConstants.ATTR_TOOL_CONTENT_ID);
ImageGallery imageGallery = igService.getImageGalleryByContentId(contentId);
int imageUid = NumberUtils.stringToInt(imageGalleryItemForm.getImageUid(), -1);
ImageGalleryItem image = igService.getImageGalleryItemByUid(new Long(imageUid));
String title = imageGalleryItemForm.getTitle();
if (StringUtils.isBlank(title)) {
Long nextImageTitleNumber = imageGallery.getNextImageTitle();
imageGallery.setNextImageTitle(nextImageTitleNumber + 1);
igService.saveOrUpdateImageGallery(imageGallery);
title = igService.generateNextImageTitle(nextImageTitleNumber);
}
image.setTitle(title);
image.setDescription(imageGalleryItemForm.getDescription());
image.setHide(false);
igService.saveOrUpdateImageGalleryItem(image);
String redirect = "redirect:/monitoring/summary.do";
redirect = WebUtil.appendParameterToURL(redirect, ImageGalleryConstants.ATTR_TOOL_CONTENT_ID,
contentId.toString());
String contentFolderID = (String) sessionMap.get(AttributeNames.PARAM_CONTENT_FOLDER_ID);
redirect = WebUtil.appendParameterToURL(redirect, AttributeNames.PARAM_CONTENT_FOLDER_ID, contentFolderID);
return redirect;
}
@Override
public float getPropertyAsFloat(final String name, final float defaultValue) {
checkArgument(StringUtils.isNotBlank(name));
return Optional.ofNullable(SYSTEM_PROPERTY_UTILS.getProperty(name))
.map(String::toLowerCase)
.map(String::trim)
.map(NumberUtils::toFloat)
.orElse(defaultValue);
}
/** {@inheritDoc} */
@Override
public SearchResult<Customer> getCustomers(final SearchContext searchContext) {
final long shopId = NumberUtils.toLong(HttpUtil.getSingleValue(searchContext.getParameters().get("shopId")));
Map<String, List> filter = searchContext.expandParameter("any", "email", "firstname", "lastname", "companyName1", "companyName2", "tag");
if (filter.isEmpty()) {
filter = searchContext.reduceParameters("email", "firstname", "lastname", "companyName1", "companyName2", "tag");
}
filter.put("shopIds", Collections.singletonList(shopId));
final int pageSize = Math.min(searchContext.getSize(), 50);
final int startIndex = searchContext.getStart() * pageSize;
final Shop shop = shopService.getById(shopId);
if (shop != null) {
applyBlacklistingFilter(shop, filter);
final int count = customerService.findCustomerCount(filter);
if (count > startIndex) {
final List<Customer> customer = customerService.findCustomers(startIndex, pageSize, searchContext.getSortBy(), searchContext.isSortDesc(), filter);
return new SearchResult<>(searchContext, customer, count);
}
}
return new SearchResult<>(searchContext, Collections.emptyList(), 0);
}
/**
* @param name
* @param defaultValue
* @return
*/
public int getParameterAsInt(String name, int defaultValue) {
String value = getParameterMap().get(name);
if (NumberUtils.isNumber(value)) {
return NumberUtils.toInt(value);
}
return defaultValue;
}
private Instant determineExpiryTime(final Shop shop) {
int secondsTimeout = Constants.DEFAULT_CUSTOMER_TOKEN_EXPIRY_SECONDS;
final String attrVal = shop.getAttributeValueByCode(AttributeNamesKeys.Shop.SHOP_CUSTOMER_TOKEN_EXPIRY_SECONDS);
if (attrVal != null) {
secondsTimeout = NumberUtils.toInt(attrVal, secondsTimeout);
}
return now().plus(secondsTimeout, ChronoUnit.HOURS);
}
public void setToAmount(String toAmount) {
if(StringUtils.isNotEmpty(toAmount) && NumberUtils.isNumber( toAmount ) ) {
this.toAmount = new KualiDecimal(toAmount);
}
else {
this.toAmount = null;
}
}
protected DnsStrategy createDnsStrategy() {
DnsStrategy dnsStrategy = new DnsStrategy();
// dnsServer
String dnsServer = Config.getProperty("dns.server");
dnsStrategy.setDnsServer(dnsServer);
// timeToLive
String timeToLive = Config.getProperty("dns.timeToLive");
dnsStrategy.setTimeToLive(NumberUtils.toInt(timeToLive, 3600));
return dnsStrategy;
}
public static String deleteHistory( String history ) {
if ( history != null && history.length() > 0 ) {
int lastIndexOfContinue = history.lastIndexOf( "continue" );
int lastIndexOfAbort = history.lastIndexOf( "abort" );
int lastIndexOfAborted = history.lastIndexOf( "aborted" );
int maxIndex = NumberUtils.max( lastIndexOfContinue, lastIndexOfAbort, lastIndexOfAborted );
return maxIndex > 0 ? "..." + history.substring( maxIndex - 1 ) : history;
}
return history;
}
/**
* @param name
* @param defaultValue
* @return
*/
public long getParameterAsLong(String name, long defaultValue) {
String value = getParameterMap().get(name);
if (NumberUtils.isNumber(value)) {
return NumberUtils.toLong(value);
}
return defaultValue;
}
@RequestMapping(value = "systems", method = RequestMethod.POST)
public void postSystems(HttpServletRequest request, HttpServletResponse response) throws IOException {
JSONObject data = (JSONObject) ServletUtils.getRequestJson(request);
String dHomeURL = defaultIfBlank(data, ConfigurableItem.HomeURL);
if (!RegexUtils.isUrl(dHomeURL)) {
writeFailure(response, "无效主页地址/域名");
return;
}
// 验证数字参数
ConfigurableItem[] validNumbers = new ConfigurableItem[] {
ConfigurableItem.RecycleBinKeepingDays,
ConfigurableItem.RevisionHistoryKeepingDays,
ConfigurableItem.DBBackupsKeepingDays
};
for (ConfigurableItem item : validNumbers) {
String number = defaultIfBlank(data, item);
if (!NumberUtils.isNumber(number)) {
data.put(item.name(), item.getDefaultValue());
}
}
setValues(data);
// @see ServerListener
ServerListener.updateGlobalContextAttributes(request.getServletContext());
writeSuccess(response);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!sender.hasPermission("factionstop.use")) {
sender.sendMessage(plugin.getSettings().getPermissionMessage());
return true;
}
if (args.length == 0) {
sendTop(sender, 0);
} else {
sendTop(sender, NumberUtils.toInt(args[0]));
}
return true;
}
/** {@inheritDoc} */
@Override
public Address getAddress(final Customer customer, final Shop customerShop, final String addrId, final String addressType) {
long pk;
try {
pk = NumberUtils.toLong(addrId);
} catch (NumberFormatException nfe) {
pk = 0;
}
Address rez = null;
for (Address addr : getAddressbook(customerShop, customer)) {
if (addr.getAddressId() == pk) {
rez = addr;
break;
}
}
if (rez == null) {
rez = customerService.getGenericDao().getEntityFactory().getByIface(Address.class);
rez.setCustomer(customer);
rez.setAddressType(Address.ADDR_TYPE_BILLING.equals(addressType) ? Address.ADDR_TYPE_BILLING : Address.ADDR_TYPE_SHIPPING);
// customer.getAddress().add(rez); Must do this when we create address only!
final AttrValueCustomer attrValue = customer.getAttributeByCode(AttributeNamesKeys.Customer.CUSTOMER_PHONE);
rez.setSalutation(customer.getSalutation());
rez.setFirstname(customer.getFirstname());
rez.setMiddlename(customer.getMiddlename());
rez.setLastname(customer.getLastname());
rez.setCompanyName1(customer.getCompanyName1());
rez.setCompanyName2(customer.getCompanyName2());
rez.setCompanyDepartment(customer.getCompanyDepartment());
rez.setEmail1(customer.getContactEmail());
rez.setPhone1(attrValue == null ? StringUtils.EMPTY : attrValue.getVal());
}
return rez;
}