类org.apache.commons.lang3.math.NumberUtils源码实例Demo

下面列出了怎么用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;
		}
	}
}
 
源代码2 项目: astor   文件: ConstructorUtilsTest.java
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());
}
 
源代码3 项目: MicroCommunity   文件: CenterServiceSMOImpl.java
/**
 * 解密
 * @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);
          }
      }
  }
 
源代码5 项目: cuba   文件: WebSplitPanel.java
@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());
        }
    }
}
 
源代码6 项目: incubator-pinot   文件: StringSeries.java
/**
 * 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;
}
 
源代码7 项目: sakai   文件: GradebookNgEntityProvider.java
@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);
}
 
源代码8 项目: sakai   文件: UserPrefsTool.java
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;
	}
}
 
源代码9 项目: para   文件: OXRCurrencyConverter.java
@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;
}
 
源代码10 项目: bamboobsc   文件: AggregationMethod.java
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() );
}
 
源代码11 项目: metrics-cloudwatch   文件: CloudWatchReporter.java
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());
            }
        }));
    }
}
 
源代码12 项目: jinjava   文件: IndentFilter.java
@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);
}
 
源代码13 项目: o2oa   文件: ActionListWithCurrentPerson.java
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;
	}
}
 
源代码14 项目: vividus   文件: BddVariableSteps.java
/**
 * 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());
}
 
源代码15 项目: o2oa   文件: LanguageProcessingHelper.java
private boolean label_skip_m(Item item) {
	if (!StringUtils.startsWithIgnoreCase(item.getLabel(), "m")) {
		return false;
	} else {
		return NumberUtils.isParsable(item.getValue());
	}
}
 
源代码16 项目: flink   文件: ParameterTool.java
/**
 * 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;
}
 
源代码18 项目: o2oa   文件: LanguageProcessingHelper.java
private boolean label_skip_m(Item item) {
	if (!StringUtils.startsWithIgnoreCase(item.getLabel(), "m")) {
		return false;
	} else {
		return NumberUtils.isParsable(item.getValue());
	}
}
 
源代码19 项目: o2oa   文件: ActionControl.java
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;
}
 
源代码20 项目: conductor   文件: Query.java
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());
}
 
源代码21 项目: MicroCommunity   文件: ApiServiceSMOImpl.java
/**
 * 加密
 *
 * @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;
}
 
源代码22 项目: gyro   文件: NodeEvaluator.java
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());
    }
}
 
源代码23 项目: PneumaticCraft   文件: ProgWidgetEmitRedstone.java
@Override
public int getEmittingRedstone(){
    if(getConnectedParameters()[0] != null) {
        return NumberUtils.toInt(((ProgWidgetString)getConnectedParameters()[0]).string);
    } else {
        return 0;
    }
}
 
源代码24 项目: jinjava   文件: CenterFilter.java
@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);
}
 
源代码25 项目: openemm   文件: ComMailingContentForm.java
public int getTargetID(String index) {
    DynamicTagContent tag = getContent().get(NumberUtils.toInt(index));
    if (tag == null) {
        return -1;
    }
    return tag.getTargetID();
}
 
源代码26 项目: conductor   文件: Query.java
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;
}
 
源代码28 项目: openemm   文件: ComMailingContentForm.java
public int getDynContentId(String index) {
    DynamicTagContent tag = getContent().get(NumberUtils.toInt(index));
    if (tag == null) {
        return -1;
    }
    return tag.getId();
}
 
源代码29 项目: flink   文件: MultipleParameterTool.java
/**
 * 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);
}
 
源代码30 项目: openemm   文件: ComMailingBaseForm.java
@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;
}
 
 类所在包
 同包方法