下面列出了怎么用org.apache.commons.lang3.math.NumberUtils的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Verifies that the element is placed in the DOM within a certain amount of time. Note that the element
* does not have to be visible, just present in the HTML.
* You can use this step to verify that the page is in the correct state before proceeding with the script.
*
* @param waitDuration The maximum amount of time to wait for
* @param alias If this word is found in the step, it means the selectorValue is found from the
* data set.
* @param selectorValue The value used in conjunction with the selector to match the element. If alias
* was set, this value is found from the data set. Otherwise it is a literal
* value.
* @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be
* present
*/
@Then("^(?:I verify(?: that)? )?(?:a|an|the)(?: element found by)?( alias)? \"([^\"]*)\"(?: \\w+)*? "
+ "is present(?: within \"(\\d+)\" seconds?)?(,? ignoring timeouts?)?")
public void presentSimpleWaitStep(
final String alias,
final String selectorValue,
final String waitDuration,
final String ignoringTimeout) {
try {
simpleWebElementInteraction.getPresenceElementFoundBy(
StringUtils.isNotBlank(alias),
selectorValue,
State.getFeatureStateForThread(),
NumberUtils.toLong(waitDuration, State.getFeatureStateForThread().getDefaultWait()));
} catch (final WebElementException ex) {
/*
Rethrow if we have not ignored errors
*/
if (StringUtils.isBlank(ignoringTimeout)) {
throw ex;
}
}
}
public void testInvokeConstructor() throws Exception {
assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class,
ArrayUtils.EMPTY_CLASS_ARRAY).toString());
assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class,
(Class[]) null).toString());
assertEquals("(String)", ConstructorUtils.invokeConstructor(
TestBean.class, "").toString());
assertEquals("(Object)", ConstructorUtils.invokeConstructor(
TestBean.class, new Object()).toString());
assertEquals("(Object)", ConstructorUtils.invokeConstructor(
TestBean.class, Boolean.TRUE).toString());
assertEquals("(Integer)", ConstructorUtils.invokeConstructor(
TestBean.class, NumberUtils.INTEGER_ONE).toString());
assertEquals("(int)", ConstructorUtils.invokeConstructor(
TestBean.class, NumberUtils.BYTE_ONE).toString());
assertEquals("(double)", ConstructorUtils.invokeConstructor(
TestBean.class, NumberUtils.LONG_ONE).toString());
assertEquals("(double)", ConstructorUtils.invokeConstructor(
TestBean.class, NumberUtils.DOUBLE_ONE).toString());
}
/**
* 解密
* @param reqJson
* @return
*/
private String decrypt(String reqJson,Map<String,String> headers) throws DecryptException{
try {
if (MappingConstant.VALUE_ON.equals(headers.get(CommonConstant.ENCRYPT))) {
logger.debug("解密前字符:" + reqJson);
reqJson = new String(AuthenticationFactory.decrypt(reqJson.getBytes("UTF-8"), AuthenticationFactory.loadPrivateKey(MappingConstant.KEY_PRIVATE_STRING)
, NumberUtils.isNumber(headers.get(CommonConstant.ENCRYPT_KEY_SIZE)) ? Integer.parseInt(headers.get(CommonConstant.ENCRYPT_KEY_SIZE)) :
Integer.parseInt(MappingCache.getValue(MappingConstant.KEY_DEFAULT_DECRYPT_KEY_SIZE))),"UTF-8");
logger.debug("解密后字符:" + reqJson);
}
}catch (Exception e){
throw new DecryptException(ResponseConstant.RESULT_CODE_NO_AUTHORITY_ERROR,"解密失败");
}
return reqJson;
}
/**
* Get Data for Recipient Report
* message key "report.recipient.statistics.recipientDevelopmentDetailed.label"
* en: "Recipient development detailed (Opt-ins, Opt-outs, Bounces)"
* de: "Empfängerentwicklung detailliert (Anmeldungen, Abmeldungen, Bounces)"
*/
public void initRecipientsStatistic(@VelocityCheck int companyId, String selectedMailingLists, String selectedTargetsAsString, String startDate, String stopDate) throws Exception {
List<Integer> mailingListIds = new ArrayList<>();
for (String mailingListIdString : selectedMailingLists.split(",")) {
mailingListIds.add(NumberUtils.toInt(mailingListIdString));
}
Date dateStart = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
Date dateStop = new SimpleDateFormat("yyyy-MM-dd").parse(stopDate);
int mailinglistIndex = 0;
for (LightMailingList mailinglist : getMailingLists(mailingListIds, companyId)) {
int mailinglistID = mailinglist.getMailingListId();
mailinglistIndex++;
int targetGroupIndex = CommonKeys.ALL_SUBSCRIBERS_INDEX;
insertStatistic(companyId, mailinglistID, mailinglistIndex, null, targetGroupIndex, dateStart, dateStop);
for (LightTarget target : getTargets(selectedTargetsAsString, companyId)) {
targetGroupIndex++;
insertStatistic(companyId, mailinglistID, mailinglistIndex, target, targetGroupIndex, dateStart, dateStop);
}
}
}
@Override
public void applySettings(Element element) {
if (!isSettingsEnabled()) {
return;
}
Element e = element.element("position");
if (e != null) {
String value = e.attributeValue("value");
String unit = e.attributeValue("unit");
if (!StringUtils.isBlank(value) && !StringUtils.isBlank(unit)) {
Unit convertedUnit;
if (NumberUtils.isNumber(unit)) {
convertedUnit = convertLegacyUnit(Integer.parseInt(unit));
} else {
convertedUnit = Unit.getUnitFromSymbol(unit);
}
component.setSplitPosition(Float.parseFloat(value), convertedUnit, component.isSplitPositionReversed());
}
}
}
/**
* Attempts to infer a tighter native series type based on pattern matching
* against individual values in the series.
*
* @return inferred series type
*/
public SeriesType inferType() {
if(this.isEmpty())
return SeriesType.STRING;
boolean isBoolean = true;
boolean isLong = true;
boolean isDouble = true;
for(String s : this.values) {
isBoolean &= (s == null) || (s.length() <= 0) || (s.compareToIgnoreCase("true") == 0 || s.compareToIgnoreCase("false") == 0);
isLong &= (s == null) || (s.length() <= 0) || (NumberUtils.isNumber(s) && !s.contains(".") && !s.contains("e"));
isDouble &= (s == null) || (s.length() <= 0) || NumberUtils.isNumber(s);
}
if(isBoolean)
return SeriesType.BOOLEAN;
if(isLong)
return SeriesType.LONG;
if(isDouble)
return SeriesType.DOUBLE;
return SeriesType.STRING;
}
@SuppressWarnings("unused")
@EntityCustomAction(action = "comments", viewKey = EntityView.VIEW_LIST)
public String getComments(final EntityView view, final Map<String, Object> params) {
// get params
final String siteId = (String) params.get("siteId");
final long assignmentId = NumberUtils.toLong((String) params.get("assignmentId"));
final String studentUuid = (String) params.get("studentUuid");
// check params supplied are valid
if (StringUtils.isBlank(siteId) || assignmentId == 0 || StringUtils.isBlank(studentUuid)) {
throw new IllegalArgumentException(
"Request data was missing / invalid");
}
checkValidSite(siteId);
checkInstructorOrTA(siteId);
return this.businessService.getAssignmentGradeComment(siteId, assignmentId, studentUuid);
}
public int compareTo(Term other) {
if (termOrder != null && (termOrder.contains(this.label) || termOrder.contains(other.label))) {
return(NumberUtils.compare(termOrder.indexOf(this.label), termOrder.indexOf(other.label)));
}
String myType = this.getType();
String theirType = other.getType();
// Otherwise if not found in a term course sites win out over non-course-sites
if (myType == null) {
return 1;
} else if (theirType == null) {
return -1;
} else if (myType.equals(theirType)) {
return 0;
} else if ("course".equals(myType)) {
return -1;
} else {
return 1;
}
}
@Override
public Double convertCurrency(Number amount, String from, String to) {
if (amount == null || StringUtils.isBlank(from) || StringUtils.isBlank(to)) {
return 0.0;
}
Sysprop s = dao.read(FXRATES_KEY);
if (s == null) {
s = fetchFxRatesJSON();
} else if ((Utils.timestamp() - s.getTimestamp()) > REFRESH_AFTER) {
// lazy refresh fx rates
Para.asyncExecute(new Runnable() {
public void run() {
fetchFxRatesJSON();
}
});
}
double ratio = 1.0;
if (s.hasProperty(from) && s.hasProperty(to)) {
Double f = NumberUtils.toDouble(s.getProperty(from).toString(), 1.0);
Double t = NumberUtils.toDouble(s.getProperty(to).toString(), 1.0);
ratio = t / f;
}
return amount.doubleValue() * ratio;
}
public float countDistinct(KpiVO kpi) throws Exception {
List<BbMeasureData> measureDatas = kpi.getMeasureDatas();
List<Float> scores = new ArrayList<Float>();
for (BbMeasureData measureData : measureDatas) {
BscMeasureData data = new BscMeasureData();
data.setActual( measureData.getActual() );
data.setTarget( measureData.getTarget() );
data.setKpi(kpi); // 2018-12-02
try {
Object value = BscFormulaUtils.parse(kpi.getFormula(), data);
if (value == null) {
continue;
}
if ( !NumberUtils.isCreatable( String.valueOf(value) ) ) {
continue;
}
float nowScore = NumberUtils.toFloat(String.valueOf(value), 0.0f);
if ( !scores.contains(nowScore) ) {
scores.add( nowScore );
}
} catch (Exception e) {
e.printStackTrace();
}
}
return Float.valueOf( scores.size() );
}
void reportGauge(Map.Entry<String, Gauge> gaugeEntry, String typeDimValue, List<MetricDatum> data) {
Gauge gauge = gaugeEntry.getValue();
Object valueObj = gauge.getValue();
if (valueObj == null) {
return;
}
String valueStr = valueObj.toString();
if (NumberUtils.isNumber(valueStr)) {
final Number value = NumberUtils.createNumber(valueStr);
DemuxedKey key = new DemuxedKey(appendGlobalDimensions(gaugeEntry.getKey()));
Iterables.addAll(data, key.newDatums(typeDimName, typeDimValue, new Function<MetricDatum, MetricDatum>() {
@Override
public MetricDatum apply(MetricDatum datum) {
return datum.withValue(value.doubleValue());
}
}));
}
}
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
int width = 4;
if (args.length > 0) {
width = NumberUtils.toInt(args[0], 4);
}
boolean indentFirst = false;
if (args.length > 1) {
indentFirst = BooleanUtils.toBoolean(args[1]);
}
List<String> indentedLines = new ArrayList<>();
for (String line : NEWLINE_SPLITTER.split(Objects.toString(var, ""))) {
int thisWidth = indentedLines.size() == 0 && !indentFirst ? 0 : width;
indentedLines.add(StringUtils.repeat(' ', thisWidth) + line);
}
return NEWLINE_JOINER.join(indentedLines);
}
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, String consume, Integer count) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Business business = new Business(emc);
ActionResult<List<Wo>> result = new ActionResult<>();
List<Wo> wos = this.list(business, consume, NumberUtils.min(200, NumberUtils.max(1, count)),
effectivePerson.getDistinguishedName());
result.setData(wos);
return result;
}
}
/**
* Compare the value from the first <b>variable</b> with the value from the second <b>variable</b>
* in accordance with the <b>condition</b>
* Could compare Maps and Lists of maps using EQUAL_TO comparison rule.
* Other rules will fallback to strings comparison
* <p>
* The values of the variables should be logically comparable.
* @param variable1 The <b>name</b> of the variable in witch the value was set
* @param condition The rule to compare values<br>
* (<i>Possible values:<b> less than, less than or equal to, greater than, greater than or equal to,
* equal to</b></i>)
* @param variable2 The <b>name</b> of the different variable in witch the value was set
* @return true if assertion is passed, otherwise false
*/
@Then("`$variable1` is $comparisonRule `$variable2`")
public boolean compareVariables(Object variable1, ComparisonRule condition, Object variable2)
{
if (variable1 instanceof String && variable2 instanceof String)
{
String variable1AsString = (String) variable1;
String variable2AsString = (String) variable2;
if (NumberUtils.isCreatable(variable1AsString) && NumberUtils.isCreatable(variable2AsString))
{
BigDecimal number1 = NumberUtils.createBigDecimal(variable1AsString);
BigDecimal number2 = NumberUtils.createBigDecimal(variable2AsString);
return compare(number1, condition, number2);
}
}
else if (ComparisonRule.EQUAL_TO.equals(condition))
{
if (isEmptyOrListOfMaps(variable1) && isEmptyOrListOfMaps(variable2))
{
return compareListsOfMaps(variable1, variable2);
}
else if (instanceOfMap(variable1) && instanceOfMap(variable2))
{
return compareListsOfMaps(List.of(variable1), List.of(variable2));
}
}
return compare(variable1.toString(), condition, variable2.toString());
}
private boolean label_skip_m(Item item) {
if (!StringUtils.startsWithIgnoreCase(item.getLabel(), "m")) {
return false;
} else {
return NumberUtils.isParsable(item.getValue());
}
}
/**
* Returns {@link ParameterTool} for the given arguments. The arguments are keys followed by values.
* Keys have to start with '-' or '--'
*
* <p><strong>Example arguments:</strong>
* --key1 value1 --key2 value2 -key3 value3
*
* @param args Input array arguments
* @return A {@link ParameterTool}
*/
public static ParameterTool fromArgs(String[] args) {
final Map<String, String> map = new HashMap<>(args.length / 2);
int i = 0;
while (i < args.length) {
final String key = Utils.getKeyFromArgs(args, i);
if (key.isEmpty()) {
throw new IllegalArgumentException(
"The input " + Arrays.toString(args) + " contains an empty argument");
}
i += 1; // try to find the value
if (i >= args.length) {
map.put(key, NO_VALUE_KEY);
} else if (NumberUtils.isNumber(args[i])) {
map.put(key, args[i]);
i += 1;
} else if (args[i].startsWith("--") || args[i].startsWith("-")) {
// the argument cannot be a negative number because we checked earlier
// -> the next argument is a parameter name
map.put(key, NO_VALUE_KEY);
} else {
map.put(key, args[i]);
i += 1;
}
}
return fromMap(map);
}
private boolean isDoubleArray(String[] array) {
for (String val : array) {
if (!NumberUtils.isCreatable(val)) {
return false;
}
}
return true;
}
private boolean label_skip_m(Item item) {
if (!StringUtils.startsWithIgnoreCase(item.getLabel(), "m")) {
return false;
} else {
return NumberUtils.isParsable(item.getValue());
}
}
private Integer getArgInteger(CommandLine cmd, String opt, Integer defaultValue) {
Integer repeat = defaultValue;
String r = cmd.getOptionValue(opt);
if (NumberUtils.isParsable(r)) {
repeat = NumberUtils.toInt(r);
}
if (repeat < REPEAT_MIN || repeat > REPEAT_MAX) {
repeat = REPEAT_MIN;
}
return repeat;
}
protected Integer convertInt(Object value) {
if (null == value) {
return null;
}
if (value instanceof Integer) {
return (Integer) value;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
return NumberUtils.toInt(value.toString());
}
/**
* 加密
*
* @param resJson
* @param headers
* @return
*/
private String encrypt(String resJson, Map<String, String> headers) {
try {
if (MappingConstant.VALUE_ON.equals(headers.get(CommonConstant.ENCRYPT))) {
logger.debug("加密前字符:" + resJson);
resJson = new String(AuthenticationFactory.encrypt(resJson.getBytes("UTF-8"), AuthenticationFactory.loadPubKey(MappingConstant.KEY_PUBLIC_STRING)
, NumberUtils.isNumber(headers.get(CommonConstant.ENCRYPT_KEY_SIZE)) ? Integer.parseInt(headers.get(CommonConstant.ENCRYPT_KEY_SIZE)) :
Integer.parseInt(MappingCache.getValue(MappingConstant.KEY_DEFAULT_DECRYPT_KEY_SIZE))), "UTF-8");
logger.debug("加密后字符:" + resJson);
}
} catch (Exception e) {
logger.error("加密失败:", e);
}
return resJson;
}
private static Object doArithmetic(
Object left,
Object right,
DoubleBinaryOperator doubleOperator,
LongBinaryOperator longOperator) {
if (left == null || right == null) {
throw new GyroException("Can't do arithmetic with a null!");
}
Number leftNumber = NumberUtils.createNumber(left.toString());
if (leftNumber == null) {
throw new GyroException(String.format(
"Can't do arithmetic on @|bold %s|@, an instance of @|bold %s|@, because it's not a number!",
left,
left.getClass().getName()));
}
Number rightNumber = NumberUtils.createNumber(right.toString());
if (rightNumber == null) {
throw new GyroException(String.format(
"Can't do arithmetic on @|bold %s|@, an instance of @|bold %s|@, because it's not a number!",
right,
right.getClass().getName()));
}
if (leftNumber instanceof Float
|| leftNumber instanceof Double
|| rightNumber instanceof Float
|| rightNumber instanceof Double) {
return doubleOperator.applyAsDouble(leftNumber.doubleValue(), rightNumber.doubleValue());
} else {
return longOperator.applyAsLong(leftNumber.longValue(), rightNumber.longValue());
}
}
@Override
public int getEmittingRedstone(){
if(getConnectedParameters()[0] != null) {
return NumberUtils.toInt(((ProgWidgetString)getConnectedParameters()[0]).string);
} else {
return 0;
}
}
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
if (var == null) {
return null;
}
int size = 80;
if (args.length > 0) {
size = NumberUtils.toInt(args[0], 80);
}
return StringUtils.center(var.toString(), size);
}
public int getTargetID(String index) {
DynamicTagContent tag = getContent().get(NumberUtils.toInt(index));
if (tag == null) {
return -1;
}
return tag.getTargetID();
}
protected Long convertLong(Object value) {
if (null == value) {
return null;
}
if (value instanceof Long) {
return (Long) value;
}
if (value instanceof Number) {
return ((Number) value).longValue();
}
return NumberUtils.toLong(value.toString());
}
private boolean isLongArray(String[] array) {
for (String val : array) {
if (!NumberUtils.isDigits(val)) {
return false;
}
}
return true;
}
public int getDynContentId(String index) {
DynamicTagContent tag = getContent().get(NumberUtils.toInt(index));
if (tag == null) {
return -1;
}
return tag.getId();
}
/**
* Returns {@link MultipleParameterTool} for the given arguments. The arguments are keys followed by values.
* Keys have to start with '-' or '--'
*
* <p><strong>Example arguments:</strong>
* --key1 value1 --key2 value2 -key3 value3
* --multi multiValue1 --multi multiValue2
*
* @param args Input array arguments
* @return A {@link MultipleParameterTool}
*/
public static MultipleParameterTool fromArgs(String[] args) {
final Map<String, Collection<String>> map = new HashMap<>(args.length / 2);
int i = 0;
while (i < args.length) {
final String key = Utils.getKeyFromArgs(args, i);
i += 1; // try to find the value
map.putIfAbsent(key, new ArrayList<>());
if (i >= args.length) {
map.get(key).add(NO_VALUE_KEY);
} else if (NumberUtils.isNumber(args[i])) {
map.get(key).add(args[i]);
i += 1;
} else if (args[i].startsWith("--") || args[i].startsWith("-")) {
// the argument cannot be a negative number because we checked earlier
// -> the next argument is a parameter name
map.get(key).add(NO_VALUE_KEY);
} else {
map.get(key).add(args[i]);
i += 1;
}
}
return fromMultiMap(map);
}
@Override
public void reset(ActionMapping map, HttpServletRequest request) {
setAction(ComMailingBaseAction.ACTION_LIST);
dynamicTemplate = false;
archived = false;
super.reset(map, request);
clearBulkIds();
int actionID = NumberUtils.toInt(request.getParameter("action"));
if (actionID == ComMailingBaseAction.ACTION_SAVE
|| actionID == ComMailingBaseAction.ACTION_SAVE_MAILING_GRID) {
parameterMap.clear();
addParameter = false;
}
intervalType = ComMailingParameterDao.IntervalType.None;
intervalDays = new boolean[7];
setNumberOfRows(-1);
selectedFields = ArrayUtils.EMPTY_STRING_ARRAY;
uploadFile = null;
setTargetGroups(Collections.emptyList());
setTargetExpression(StringUtils.EMPTY);
assignTargetGroups = false;
}