下面列出了org.apache.commons.lang.math.NumberUtils#toLong ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static <A> Long firstLong( List<A> list ) {
A a = first( list );
if ( a == null ) {
return null;
}
if ( a instanceof Long ) {
return ( Long ) a;
}
try {
return NumberUtils.toLong( ( String ) a );
}
catch ( Exception e ) {
logger.warn( "Could not convert list item {} to long", a, e );
}
return null;
}
public static long getLong( Object obj ) {
if ( obj instanceof Long ) {
return ( Long ) obj;
}
if ( obj instanceof Number ) {
return ( ( Number ) obj ).longValue();
}
if ( obj instanceof String ) {
return NumberUtils.toLong( ( String ) obj );
}
if ( obj instanceof Date ) {
return ( ( Date ) obj ).getTime();
}
if ( obj instanceof byte[] ) {
return getLong( ( byte[] ) obj );
}
if ( obj instanceof ByteBuffer ) {
return getLong( ( ByteBuffer ) obj );
}
return 0;
}
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {
Object totalNetOutputBytesObject = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.total_net_output_bytes.getValue());
if (totalNetOutputBytesObject == null) {
return null;
}
// 关系比对
long totalNetOutputBytes = NumberUtils.toLong(totalNetOutputBytesObject.toString());
totalNetOutputBytes = changeByteToMB(totalNetOutputBytes);
boolean compareRight = isCompareLongRight(instanceAlertConfig, totalNetOutputBytes);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(totalNetOutputBytes),
instanceInfo.getAppId(), MB_STRING));
}
@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));
}
/**
* {@inheritDoc}
*/
@Override
public List<Object> getResult(final String lang, final Map<String, Object> currentSelection) {
final String warehouse = (String) currentSelection.get("warehouse");
final String skuCode = (String) currentSelection.get("skuCode");
final long warehouseId = NumberUtils.toLong(warehouse);
if (warehouseId > 0L) {
try {
final VoSearchContext ctx = new VoSearchContext();
final Map<String, List> params = new HashMap<>();
ctx.setParameters(params);
if (StringUtils.isNotBlank(skuCode)) {
params.put("filter", Collections.singletonList(skuCode));
}
params.put("centreId", Collections.singletonList(warehouseId));
ctx.setSize(Integer.MAX_VALUE);
return (List) fulfilmentService.getFilteredInventory(ctx).getItems();
} catch (Exception e) {
// do nothing
}
}
return Collections.emptyList();
}
/**
* 应用重要性级别
*/
@RequestMapping(value = "/updateAppImportantLevel")
public ModelAndView doUpdateAppImportantLevel(HttpServletRequest request, HttpServletResponse response, Model model) {
long appId = NumberUtils.toLong(request.getParameter("appId"));
int importantLevel = NumberUtils.toInt(request.getParameter("importantLevel"));
SuccessEnum successEnum = SuccessEnum.FAIL;
if (appId > 0 && importantLevel >= 0) {
try {
AppDesc appDesc = appService.getByAppId(appId);
appDesc.setImportantLevel(importantLevel);
appService.update(appDesc);
successEnum = SuccessEnum.SUCCESS;
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
model.addAttribute("status", successEnum.value());
return new ModelAndView("");
}
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {
Object totalNetInputBytesObject = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.total_net_input_bytes.getValue());
if (totalNetInputBytesObject == null) {
return null;
}
// 关系比对
long totalNetInputBytes = NumberUtils.toLong(totalNetInputBytesObject.toString()) ;
totalNetInputBytes = changeByteToMB(totalNetInputBytes);
boolean compareRight = isCompareLongRight(instanceAlertConfig, totalNetInputBytes);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(totalNetInputBytes),
instanceInfo.getAppId(), MB_STRING));
}
/**
* 开始迁移
* @return
*/
@RequestMapping(value = "/start")
public ModelAndView start(HttpServletRequest request, HttpServletResponse response, Model model) {
//相关参数
String migrateMachineIp = request.getParameter("migrateMachineIp");
String sourceRedisMigrateIndex = request.getParameter("sourceRedisMigrateIndex");
AppDataMigrateEnum sourceRedisMigrateEnum = AppDataMigrateEnum.getByIndex(NumberUtils.toInt(sourceRedisMigrateIndex, -1));
String sourceServers = request.getParameter("sourceServers");
String targetRedisMigrateIndex = request.getParameter("targetRedisMigrateIndex");
AppDataMigrateEnum targetRedisMigrateEnum = AppDataMigrateEnum.getByIndex(NumberUtils.toInt(targetRedisMigrateIndex, -1));
String targetServers = request.getParameter("targetServers");
long sourceAppId = NumberUtils.toLong(request.getParameter("sourceAppId"));
long targetAppId = NumberUtils.toLong(request.getParameter("targetAppId"));
String redisSourcePass = request.getParameter("redisSourcePass");
String redisTargetPass = request.getParameter("redisTargetPass");
AppUser appUser = getUserInfo(request);
long userId = appUser == null ? 0 : appUser.getId();
// 不需要对格式进行检验,check已经做过了,开始迁移
boolean isSuccess = appDataMigrateCenter.migrate(migrateMachineIp, sourceRedisMigrateEnum, sourceServers,
targetRedisMigrateEnum, targetServers, sourceAppId, targetAppId, redisSourcePass, redisTargetPass, userId);
model.addAttribute("status", isSuccess ? 1 : 0);
return new ModelAndView("");
}
/**
* Register a consumer to the queue
*
* @throws IOException
*/
private void initConsumer() throws IOException, RabbitMQException {
if (connection == null) {
connection = rabbitMQConnectionFactory.createConnection();
}
channel = connection.createChannel();
((Recoverable) this.channel).addRecoveryListener(new RabbitMQRecoveryListener());
// set the qos value
int qos = NumberUtils.toInt(rabbitMQProperties.get(RabbitMQConstants.CONSUMER_QOS),
RabbitMQConstants.DEFAULT_CONSUMER_QOS);
channel.basicQos(qos);
// declaring queue, exchange and binding
queueName = rabbitMQProperties.get(RabbitMQConstants.QUEUE_NAME);
String exchangeName = rabbitMQProperties.get(RabbitMQConstants.EXCHANGE_NAME);
RabbitMQUtils.declareQueuesExchangesAndBindings(channel, queueName, exchangeName, rabbitMQProperties);
// get max dead-lettered count
maxDeadLetteredCount =
NumberUtils.toLong(rabbitMQProperties.get(RabbitMQConstants.MESSAGE_MAX_DEAD_LETTERED_COUNT));
// get consumer tag if given
String consumerTag = rabbitMQProperties.get(RabbitMQConstants.CONSUMER_TAG);
autoAck = BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBooleanObject(rabbitMQProperties
.get(RabbitMQConstants.QUEUE_AUTO_ACK)), true);
if (StringUtils.isNotEmpty(consumerTag)) {
channel.basicConsume(queueName, autoAck, consumerTag, this);
} else {
channel.basicConsume(queueName, autoAck, this);
}
}
@Override
public long queryServerId() throws IOException {
ResultSetPacket resultSetPacket = query("show variables like 'server_id'");
List<String> fieldValues = resultSetPacket.getFieldValues();
if (fieldValues == null || fieldValues.size() != 2) {
return 0;
}
return NumberUtils.toLong(fieldValues.get(1));
}
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {
Object object = getValueFromDiffInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.rejected_connections.getValue());
if (object == null) {
return null;
}
long minuteRejectedConnections = NumberUtils.toLong(object.toString());
boolean compareRight = isCompareLongRight(instanceAlertConfig, minuteRejectedConnections);
if (compareRight) {
return null;
}
InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
return Arrays.asList(new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(minuteRejectedConnections),
instanceInfo.getAppId(), EMPTY));
}
/**
* 获取客户端连接数统计
*
* @param appId
* @param startDate
* @param endDate
* @return
*/
private Map<String, Object> getAppMinuteStat(long appId, Date startDate, Date endDate) {
try {
String COLLECT_TIME_FORMAT = "yyyyMMddHHmm";
long startTime = NumberUtils.toLong(DateUtil.formatDate(startDate, COLLECT_TIME_FORMAT));
long endTime = NumberUtils.toLong(DateUtil.formatDate(endDate, COLLECT_TIME_FORMAT));
return appStatsDao.getAppMinuteStat(appId, startTime, endTime);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return Collections.emptyMap();
}
}
/**
* 值分布日期格式
*/
private TimeBetween fillWithValueDistriTime(HttpServletRequest request, Model model) throws ParseException {
final String valueDistriDateFormat = "yyyy-MM-dd";
String valueDistriStartDateParam = request.getParameter("valueDistriStartDate");
String valueDistriEndDateParam = request.getParameter("valueDistriEndDate");
Date startDate;
Date endDate;
if (StringUtils.isBlank(valueDistriStartDateParam) || StringUtils.isBlank(valueDistriEndDateParam)) {
// 如果为空默认取昨天和今天
SimpleDateFormat sdf = new SimpleDateFormat(valueDistriDateFormat);
startDate = sdf.parse(sdf.format(new Date()));
endDate = DateUtils.addDays(startDate, 1);
valueDistriStartDateParam = DateUtil.formatDate(startDate, valueDistriDateFormat);
valueDistriEndDateParam = DateUtil.formatDate(endDate, valueDistriDateFormat);
} else {
endDate = DateUtil.parse(valueDistriEndDateParam, valueDistriDateFormat);
startDate = DateUtil.parse(valueDistriStartDateParam, valueDistriDateFormat);
//限制不能超过1天
if (endDate.getTime() - startDate.getTime() > TimeUnit.DAYS.toMillis(1)) {
startDate = DateUtils.addDays(endDate, -1);
}
}
// 前端需要
model.addAttribute("valueDistriStartDate", valueDistriStartDateParam);
model.addAttribute("valueDistriEndDate", valueDistriEndDateParam);
// 查询后台需要
long startTime = NumberUtils.toLong(DateUtil.formatDate(startDate, COLLECT_TIME_FORMAT));
long endTime = NumberUtils.toLong(DateUtil.formatDate(endDate, COLLECT_TIME_FORMAT));
return new TimeBetween(startTime, endTime, startDate, endDate);
}
/**
* 停掉迁移任务
* @return
*/
@RequestMapping(value = "/stop")
public ModelAndView stop(HttpServletRequest request, HttpServletResponse response, Model model) {
//任务id:查到任务相关信息
long id = NumberUtils.toLong(request.getParameter("id"));
AppDataMigrateResult stopMigrateResult = appDataMigrateCenter.stopMigrate(id);
model.addAttribute("status", stopMigrateResult.getStatus());
model.addAttribute("message", stopMigrateResult.getMessage());
return new ModelAndView("");
}
private List<Long> determineBranchIds(final @RequestParam(value = "expand", required = false) String expand) {
List<Long> expandIds = new ArrayList<>(50);
if (StringUtils.isNotBlank(expand)) {
for (final String expandItem : StringUtils.split(expand, '|')) {
final long id = NumberUtils.toLong(expandItem);
if (id > 0L) {
expandIds.add(id);
}
}
}
return expandIds;
}
/**
* /manage/client/version
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping(value = "/version")
public ModelAndView doVersionStat(HttpServletRequest request, HttpServletResponse response, Model model) {
long appId = NumberUtils.toLong(request.getParameter("appId"),-1);
List<AppClientVersion> appClientVersionList = clientVersionService.getAll(appId);
// 应用相关map
fillAppInfoMap(model);
model.addAttribute("appClientVersionList", appClientVersionList);
model.addAttribute("clientVersionActive", SuccessEnum.SUCCESS.value());
model.addAttribute("appId", request.getParameter("appId"));
return new ModelAndView("manage/client/version/list");
}
/**
* 获取字段默认值,可指定表达式
*
* @param field
* @param valueExpr
* @return
*/
public static Object exprDefaultValue(Field field, String valueExpr) {
final DisplayType dt = EasyMeta.getDisplayType(field);
if (dt == DisplayType.PICKLIST) {
return PickListManager.instance.getDefaultItem(field);
} else if (dt == DisplayType.STATE) {
Class<?> stateClass;
try {
stateClass = StateHelper.getSatetClass(field);
} catch (IllegalArgumentException ex) {
LOG.error("Bad field of state: " + field);
return null;
}
for (Object c : stateClass.getEnumConstants()) {
if (((StateSpec) c).isDefault()) {
return ((StateSpec) c).getState();
}
}
} else if (dt == DisplayType.MULTISELECT) {
return MultiSelectManager.instance.getDefaultValue(field);
}
if (StringUtils.isBlank(valueExpr)) {
return null;
}
if (dt == DisplayType.DATE || dt == DisplayType.DATETIME) {
Date date;
if (valueExpr.contains("NOW")) {
date = parseDateExpr(valueExpr, null);
}
// 具体的日期值
else {
String format = "yyyy-MM-dd HH:mm:ss".substring(0, valueExpr.length());
date = CalendarUtils.parse(valueExpr, format);
}
return date;
} else if (dt == DisplayType.DECIMAL) {
return BigDecimal.valueOf(NumberUtils.toDouble(valueExpr));
} else if (dt == DisplayType.NUMBER) {
return NumberUtils.toLong(valueExpr);
}
else {
return valueExpr;
}
}
@RequestMapping(value = "/list")
public ModelAndView doTotalList(HttpServletRequest request,
HttpServletResponse response, Model model) {
AppUser currentUser = getUserInfo(request);
List<AppDesc> apps = appService.getAppDescList(currentUser, new AppSearch());
List<AppDetailVO> appDetailList = new ArrayList<AppDetailVO>();
long totalApplyMem = 0;
long totalUsedMem = 0;
long totalApps = 0;
long totalRunningApps = 0;
if (apps != null && apps.size() > 0) {
for (AppDesc appDesc : apps) {
AppDetailVO appDetail = appStatsCenter.getAppDetail(appDesc.getAppId());
appDetailList.add(appDetail);
totalApplyMem += appDetail.getMem();
totalUsedMem += appDetail.getMemUsePercent() * appDetail.getMem() / 100.0;
if (appDesc.getStatus() == AppStatusEnum.STATUS_PUBLISHED.getStatus()) {
totalRunningApps++;
}
totalApps++;
}
}
long totalMachineMem = 0;
long totalFreeMachineMem = 0;
List<MachineStats> allMachineStats = machineCenter.getAllMachineStats();
for (MachineStats machineStats : allMachineStats) {
totalMachineMem += NumberUtils.toLong(machineStats.getMemoryTotal(), 0l);
totalFreeMachineMem += NumberUtils.toLong(machineStats.getMemoryFree(), 0l);
}
long totalInstanceMem = 0;
long totalUseInstanceMem = 0;
List<InstanceStats> instanceStats = instanceStatsCenter.getInstanceStats();
for (InstanceStats instanceStat : instanceStats) {
totalInstanceMem += instanceStat.getMaxMemory();
totalUseInstanceMem += instanceStat.getUsedMemory();
}
model.addAttribute("totalApps", totalApps);
model.addAttribute("totalApplyMem", totalApplyMem);
model.addAttribute("totalUsedMem", totalUsedMem);
model.addAttribute("totalRunningApps", totalRunningApps);
model.addAttribute("totalMachineMem", totalMachineMem);
model.addAttribute("totalFreeMachineMem", totalFreeMachineMem);
model.addAttribute("totalInstanceMem", totalInstanceMem);
model.addAttribute("totalUseInstanceMem", totalUseInstanceMem);
model.addAttribute("apps", apps);
model.addAttribute("appDetailList", appDetailList);
model.addAttribute("list", apps);
model.addAttribute("totalActive", SuccessEnum.SUCCESS.value());
return new ModelAndView("manage/total/list");
}
/**
* Resolve category view if applicable.
* <p>
* Rules:<p>
* 1. If there is no {@link WebParametersKeys#CATEGORY_ID} then this resolver is not applicable, return null<p>
* 2. If category has template then use template.<p>
* 3. If category search yields at least one product hit then use category product type search template
* {@link org.yes.cart.domain.entity.ProductType#getUisearchtemplate()} or {@link CentralViewLabel#PRODUCTS_LIST}
* if not search template is set<p>
* 4. If category has children use {@link CentralViewLabel#SUBCATEGORIES_LIST}<p>
* 5. Otherwise use {@link CentralViewLabel#CATEGORY}<p>
*
* @param parameters request parameters map
*
* @return category view label or null (if not applicable)
*/
@Override
public Pair<String, String> resolveMainPanelRendererLabel(final Map parameters) {
if (parameters.containsKey(WebParametersKeys.CATEGORY_ID)) {
final long categoryId = NumberUtils.toLong(HttpUtil.getSingleValue(parameters.get(WebParametersKeys.CATEGORY_ID)));
if (categoryId > 0L) {
final ShoppingCart cart = ApplicationDirector.getShoppingCart();
final long shopId = cart.getShoppingContext().getShopId();
final long browsingShopId = cart.getShoppingContext().getCustomerShopId();
final String lang = cart.getCurrentLocale();
// If we have template just use it without any checks (saves us 1 FT query for each request)
final String template = shopService.getShopCategoryTemplate(browsingShopId, categoryId);
if (StringUtils.isNotBlank(template)) {
if (CentralViewLabel.PRODUCTS_LIST.equals(template)) {
return DEFAULT_PL;
} else if (CentralViewLabel.SUBCATEGORIES_LIST.equals(template)) {
return DEFAULT_SC;
}
return new Pair<>(template, CentralViewLabel.CATEGORY);
}
final Pair<List<Long>, Boolean> catIds = determineSearchCategories(categoryId, browsingShopId);
if (CollectionUtils.isEmpty(catIds.getFirst())) {
return DEFAULT; // Must never be empty, as we should have at least current category
}
// shopId will be used for inStock check, because we have category IDs will always look in those
final NavigationContext hasProducts = searchQueryFactory.getFilteredNavigationQueryChain(shopId, browsingShopId, lang, catIds.getFirst(), catIds.getSecond(), null);
if (productService.getProductQty(hasProducts) > 0) {
final String searchTemplate = shopService.getShopCategorySearchTemplate(browsingShopId, categoryId);
if (StringUtils.isNotBlank(searchTemplate)) {
return new Pair<>(searchTemplate, CentralViewLabel.PRODUCTS_LIST);
}
return DEFAULT_PL;
} else if (categoryService.isCategoryHasChildren(categoryId)) {
return DEFAULT_SC;
} else {
return DEFAULT;
}
}
}
return null;
}
private Long toNumber(final Object value) {
if (value instanceof Number) {
return ((Number) value).longValue();
}
return NumberUtils.toLong(String.valueOf(value));
}