下面列出了org.apache.commons.lang3.math.NumberUtils#isCreatable ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@ServiceMethodAuthority(type={ServiceMethodType.SELECT})
@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=true)
@Override
public String findForMaxObjId(String date) throws ServiceException, Exception {
if (super.isBlank(date) || !NumberUtils.isCreatable(date) || date.length()!=8 ) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
}
String maxVisionId = this.objectiveService.findForMaxObjId(BscConstants.HEAD_FOR_OBJ_ID+date);
if (StringUtils.isBlank(maxVisionId)) {
return BscConstants.HEAD_FOR_OBJ_ID + date + "001";
}
int maxSeq = Integer.parseInt( maxVisionId.substring(11, 14) ) + 1;
if ( maxSeq > 999 ) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_ERRORS) + " over max seq 999!");
}
return BscConstants.HEAD_FOR_OBJ_ID + date + StringUtils.leftPad(String.valueOf(maxSeq), 3, "0");
}
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() );
}
private static void integerListValue(Data data, String path, JpaObject jpaObject, String property)
throws Exception {
List<Integer> os = new ArrayList<>();
Object obj = data.find(path);
if (null != obj) {
if (ListTools.isList(obj)) {
for (Object o : (List<?>) obj) {
if (NumberUtils.isCreatable(o.toString())) {
os.add(NumberUtils.createInteger(o.toString()));
}
}
} else {
if (NumberUtils.isCreatable(obj.toString())) {
os.add(NumberUtils.createInteger(obj.toString()));
}
}
}
PropertyUtils.setProperty(jpaObject, property, os);
}
private static void doubleListValue(Data data, String path, JpaObject jpaObject, String property) throws Exception {
List<Double> os = new ArrayList<>();
Object obj = data.find(path);
if (null != obj) {
if (ListTools.isList(obj)) {
for (Object o : (List<?>) obj) {
if (NumberUtils.isCreatable(o.toString())) {
os.add(NumberUtils.createDouble(o.toString()));
}
}
} else {
if (NumberUtils.isCreatable(obj.toString())) {
os.add(NumberUtils.createDouble(obj.toString()));
}
}
}
PropertyUtils.setProperty(jpaObject, property, os);
}
/**
* 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());
}
/** 统计计算时用于转换值,不可转换的值默认为0 */
public Double getAsDouble(String key) {
Object o = this.data.get(key);
String val = Objects.toString(o, "");
if (NumberUtils.isCreatable(val)) {
return NumberUtils.toDouble(val);
} else {
return 0d;
}
}
public void parseCSV(String csv) {
try {
Reader in = new StringReader(csv);
CSVFormat format = CSVFormat.EXCEL.withHeader();
CSVParser parser = format.parse(in);
Set<String> colNames = parser.getHeaderMap().keySet();
this.colNames.addAll(colNames);
this.firstColIsIndex = true;
for (CSVRecord record : parser) {
List<String> row = new ArrayList<>();
for (int i = 0; i<record.size(); i++) {
String v = record.get(i);
boolean isInt = false;
try {
Integer.parseInt(v);
isInt = true;
}
catch (NumberFormatException nfe) {
isInt = false;
}
if ( !isInt && !NumberUtils.isDigits(v) && NumberUtils.isCreatable(v) ) {
v = String.format("%.4f",Precision.round(Double.valueOf(v), 4));
}
else {
v = abbrevString(v, 25);
}
row.add(v);
}
rows.add(row);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void applySettings(Element element) {
if (!isSettingsEnabled()) {
return;
}
String verticalSplitPos = element.attributeValue("splitPosition");
if (StringUtils.isNotEmpty(verticalSplitPos)
&& NumberUtils.isCreatable(verticalSplitPos)) {
component.setVerticalSplitPosition(Float.parseFloat(verticalSplitPos));
}
}
@Override
public String getAssignmentScoreStringByNameOrId(final String gradebookUid, final String assignmentName, final String studentUid)
throws GradebookNotFoundException, AssessmentNotFoundException {
String score = null;
try {
score = getAssignmentScoreString(gradebookUid, assignmentName, studentUid);
} catch (final AssessmentNotFoundException e) {
// Don't fail on this exception
log.debug("Assessment not found by name", e);
} catch (final GradebookSecurityException gse) {
log.warn("User {} does not have permission to retrieve score for assignment {}", studentUid, assignmentName, gse);
return null;
}
if (score == null) {
// Try to get the assignment by id
if (NumberUtils.isCreatable(assignmentName)) {
final Long assignmentId = NumberUtils.toLong(assignmentName, -1L);
try {
score = getAssignmentScoreString(gradebookUid, assignmentId, studentUid);
} catch (AssessmentNotFoundException anfe) {
log.debug("Assessment could not be found for gradebook id {} and assignment id {} and student id {}", gradebookUid, assignmentName, studentUid);
}
}
}
return score;
}
private boolean isDoubleArray(String[] array) {
for (String val : array) {
if (!NumberUtils.isCreatable(val)) {
return false;
}
}
return true;
}
public float max(KpiVO kpi) throws Exception {
List<BbMeasureData> measureDatas = kpi.getMeasureDatas();
float score = 0.0f; // init
int size = 0;
float nowScore = 0.0f;
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;
}
nowScore = NumberUtils.toFloat(String.valueOf(value), 0.0f);
if ( size < 1 ) {
score = nowScore;
} else { // Max
if ( score < nowScore ) {
score = nowScore;
}
}
size++;
} catch (Exception e) {
e.printStackTrace();
}
}
return score;
}
private static void longValue(Data data, String path, JpaObject jpaObject, String property) throws Exception {
Object obj = data.find(path);
if (null == obj) {
PropertyUtils.setProperty(jpaObject, property, null);
} else {
if (Number.class.isAssignableFrom(obj.getClass())) {
PropertyUtils.setProperty(jpaObject, property, ((Number) obj).longValue());
} else {
String str = Objects.toString(obj);
if (NumberUtils.isCreatable(str)) {
PropertyUtils.setProperty(jpaObject, property, NumberUtils.createLong(str));
}
}
}
}
public float average(KpiVO kpi) throws Exception {
List<BbMeasureData> measureDatas = kpi.getMeasureDatas();
float score = 0.0f; // init zero
int size = 0;
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;
}
score += NumberUtils.toFloat(String.valueOf(value), 0.0f);
size++;
} catch (Exception e) {
e.printStackTrace();
}
}
if ( score != 0.0f && size > 0 ) {
score = score / size;
}
return score;
}
public float sumDistinct(KpiVO kpi) throws Exception {
List<BbMeasureData> measureDatas = kpi.getMeasureDatas();
List<Float> scores = new ArrayList<Float>();
float score = 0.0f; // init
//int size = 0;
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 );
//size++;
score += nowScore;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return score;
}
private boolean isApplicable(String valueToCheck)
{
return valueToCheck != null && !valueToCheck.isEmpty() && NumberUtils.isCreatable(valueToCheck);
}
public void minDateRange(KpiVO kpi, String frequency) throws Exception {
BscReportSupportUtils.loadExpression();
for (DateRangeScoreVO dateScore : kpi.getDateRangeScores()) {
float score = 0.0f;
float nowScore = 0.0f;
int size = 0;
for (BbMeasureData measureData : kpi.getMeasureDatas()) {
String date = dateScore.getDate().replaceAll("/", "");
if (!this.isDateRange(date, frequency, measureData)) {
continue;
}
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;
}
nowScore = NumberUtils.toFloat(String.valueOf(value), 0.0f);
if ( size < 1 ) {
score = nowScore;
} else { // Min
if ( score > nowScore ) {
score = nowScore;
}
}
size++;
} catch (Exception e) {
e.printStackTrace();
}
}
dateScore.setScore(score);
dateScore.setFontColor( BscScoreColorUtils.getFontColor(score) );
dateScore.setBgColor( BscScoreColorUtils.getBackgroundColor(score) );
dateScore.setImgIcon( BscReportSupportUtils.getHtmlIcon(kpi, score) );
}
}
@Override
public void handleCommand(Entity entity, String message, String[] args) {
// :credits Patrick 300
if (entity.getType() != EntityType.PLAYER) {
return;
}
Player player = (Player) entity;
if (player.getRoomUser().getRoom() == null) {
return;
}
Player targetUser = PlayerManager.getInstance().getPlayerByName(args[0]);
if (targetUser == null) {
player.send(new CHAT_MESSAGE(ChatMessageType.WHISPER, player.getRoomUser().getInstanceId(), "Could not find user: " + args[0]));
return;
}
if (args.length == 1) {
player.send(new CHAT_MESSAGE(ChatMessageType.WHISPER, player.getRoomUser().getInstanceId(), "Credit amount not provided"));
return;
}
String credits = args[1];
// credits should be numeric
if (!NumberUtils.isCreatable(credits)) {
player.send(new CHAT_MESSAGE(ChatMessageType.WHISPER, player.getRoomUser().getInstanceId(), "Credit amount is not a number."));
return;
}
PlayerDetails targetDetails = targetUser.getDetails();
Map<PlayerDetails, Integer> playerDetailsToSave = new LinkedHashMap<>() {{
put(targetDetails, Integer.parseInt(credits));
}};
CurrencyDao.increaseCredits(playerDetailsToSave);
targetUser.send(new CREDIT_BALANCE(targetUser.getDetails()));
player.send(new CHAT_MESSAGE(ChatMessageType.WHISPER, player.getRoomUser().getInstanceId(), credits + " has been added to user " + targetDetails.getName()));
}
private ArchivaRepositoryMetadata read( XMLReader xml, Instant modTime, long fileSize) throws RepositoryMetadataException
{
// invoke this to remove namespaces, see MRM-1136
xml.removeNamespaces();
ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
try
{
metadata.setGroupId( xml.getElementText( "//metadata/groupId" ) );
metadata.setArtifactId( xml.getElementText( "//metadata/artifactId" ) );
metadata.setVersion( xml.getElementText( "//metadata/version" ) );
metadata.setFileLastModified( Date.from(modTime) );
metadata.setFileSize( fileSize );
metadata.setLastUpdated( xml.getElementText( "//metadata/versioning/lastUpdated" ) );
metadata.setLatestVersion( xml.getElementText( "//metadata/versioning/latest" ) );
metadata.setReleasedVersion( xml.getElementText( "//metadata/versioning/release" ) );
metadata.setAvailableVersions( xml.getElementListText( "//metadata/versioning/versions/version" ) );
Element snapshotElem = xml.getElement( "//metadata/versioning/snapshot" );
if ( snapshotElem != null )
{
SnapshotVersion snapshot = new SnapshotVersion( );
snapshot.setTimestamp( XmlUtil.getChildText( snapshotElem, "timestamp" ) );
String buildNumber = XmlUtil.getChildText( snapshotElem, "buildNumber" );
if ( NumberUtils.isCreatable( buildNumber ) )
{
snapshot.setBuildNumber( NumberUtils.toInt( buildNumber ) );
}
metadata.setSnapshotVersion( snapshot );
}
for ( Node node : xml.getElementList( "//metadata/plugins/plugin" ) )
{
if ( node instanceof Element )
{
Element plugin = (Element) node;
Plugin p = new Plugin( );
String prefix = plugin.getElementsByTagName( "prefix" ).item( 0 ).getTextContent( ).trim( );
p.setPrefix( prefix );
String artifactId = plugin.getElementsByTagName( "artifactId" ).item( 0 ).getTextContent( ).trim( );
p.setArtifactId( artifactId );
String name = plugin.getElementsByTagName( "name" ).item( 0 ).getTextContent( ).trim( );
p.setName( name );
metadata.addPlugin( p );
}
}
} catch ( XMLException e) {
throw new RepositoryMetadataException( "XML Error while reading metadata file : " + e.getMessage( ), e );
}
return metadata;
}
@ServiceMethodAuthority(type={ServiceMethodType.INSERT, ServiceMethodType.UPDATE})
@Transactional(
propagation=Propagation.REQUIRED,
readOnly=false,
rollbackFor={RuntimeException.class, IOException.class, Exception.class} )
@Override
public DefaultResult<Boolean> importPerspectivesCsv(String uploadOid) throws ServiceException, Exception {
List<Map<String, String>> csvResults = UploadSupportUtils.getTransformSegmentData(uploadOid, "TRAN002");
if (csvResults.size()<1) {
throw new ServiceException( SysMessageUtil.get(GreenStepSysMsgConstants.DATA_NO_EXIST) );
}
boolean success = false;
DefaultResult<Boolean> result = new DefaultResult<Boolean>();
StringBuilder msg = new StringBuilder();
Map<String, Object> paramMap = new HashMap<String, Object>();
for (int i=0; i<csvResults.size(); i++) {
int row = i+1;
Map<String, String> data = csvResults.get(i);
String perId = data.get("PER_ID");
String visId = data.get("VIS_ID");
String name = data.get("NAME");
String weight = data.get("WEIGHT");
String target = data.get("TARGET");
String min = data.get("MIN");
String description = data.get("DESCRIPTION");
if ( super.isBlank(perId) ) {
msg.append("row: " + row + " perspective-id is blank." + Constants.HTML_BR);
continue;
}
if ( super.isBlank(visId) ) {
msg.append("row: " + row + " vision-id is blank." + Constants.HTML_BR);
continue;
}
if ( super.isBlank(name) ) {
msg.append("row: " + row + " name is blank." + Constants.HTML_BR);
continue;
}
if ( super.isBlank(weight) ) {
msg.append("row: " + row + " weight is blank." + Constants.HTML_BR);
continue;
}
if ( super.isBlank(target) ) {
msg.append("row: " + row + " target is blank." + Constants.HTML_BR);
continue;
}
if ( super.isBlank(min) ) {
msg.append("row: " + row + " min is blank." + Constants.HTML_BR);
continue;
}
if ( !NumberUtils.isCreatable(weight) ) {
msg.append("row: " + row + " weight is not number." + Constants.HTML_BR);
continue;
}
if ( !NumberUtils.isCreatable(target) ) {
msg.append("row: " + row + " target is not number." + Constants.HTML_BR);
continue;
}
if ( !NumberUtils.isCreatable(min) ) {
msg.append("row: " + row + " min is not number." + Constants.HTML_BR);
continue;
}
paramMap.clear();
paramMap.put("visId", visId);
if ( this.visionService.countByParams(paramMap) < 1 ) {
throw new ServiceException( "row: " + row + " vision is not found " + visId );
}
DefaultResult<VisionVO> visionResult = this.visionService.findForSimpleByVisId(visId);
if ( visionResult.getValue()==null) {
throw new ServiceException( visionResult.getSystemMessage().getValue() );
}
PerspectiveVO perspective = new PerspectiveVO();
perspective.setPerId(perId);
perspective.setVisId(visId);
perspective.setName(name);
perspective.setWeight( new BigDecimal(weight) );
perspective.setTarget( Float.valueOf(target) );
perspective.setMin( Float.valueOf(min) );
perspective.setDescription(description);
paramMap.clear();
paramMap.put("perId", perId);
if ( this.perspectiveService.countByParams(paramMap) > 0 ) { // update
DefaultResult<PerspectiveVO> oldResult = this.perspectiveService.findByUK(perspective);
perspective.setOid( oldResult.getValue().getOid() );
this.perspectiveLogicService.update(perspective, visionResult.getValue().getOid() );
} else { // insert
this.perspectiveLogicService.create(perspective, visionResult.getValue().getOid() );
}
success = true;
}
if ( msg.length() > 0 ) {
result.setSystemMessage( new SystemMessage(msg.toString()) );
} else {
result.setSystemMessage( new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.UPDATE_SUCCESS)) );
}
result.setValue(success);
return result;
}
private static boolean isChartsValue(Object value) {
return NumberUtils.isCreatable( String.valueOf(value) );
}