下面列出了org.apache.commons.lang3.StringUtils#isNumeric ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public boolean isAssignmentDefined(String externalAppName, String id) {
// SAM-3068 avoid looking up another tool's id
if (!StringUtils.isNumeric(id)) {
return false;
}
GradebookServiceHelper gbsHelper = IntegrationContextFactory.getInstance().getGradebookServiceHelper();
String toolName = gbsHelper.getAppName();
if (!StringUtils.equals(externalAppName, getAppKey()) && !StringUtils.equals(externalAppName, toolName)) {
return false;
}
if (log.isDebugEnabled()) {
log.debug("Samigo provider isAssignmentDefined: " + id);
}
Long longId = Long.parseLong(id);
return PersistenceService.getInstance().getPublishedAssessmentFacadeQueries().isPublishedAssessmentIdValid(longId);
}
/**
* Return an EVR string representation in the format "[epoch:]version-release",
* stripping away any dummy release strings (e.g. "-X"). The universal string is
* meant to be recognized in the whole linux ecosystem.
*
* @return string representation of epoch, version and release
*/
public String toUniversalEvrString() {
StringBuilder builder = new StringBuilder();
if (StringUtils.isNumeric(getEpoch())) {
builder.append(getEpoch()).append(':');
}
builder.append(getVersion());
// Strip dummy release string
if (!getRelease().equals("X")) {
builder.append('-').append(getRelease());
}
return builder.toString();
}
protected List<Integer> getInvolvedTargetIdsFromTargetExpression(String targetExpression) {
List<Integer> returnList = new ArrayList<>();
if (StringUtils.isNotBlank(targetExpression)) {
// the regex will find all numbers, spaces and symbols "(", ")", "&", "|", "!"
String targetExpressionRegex = "[&|()! ]|[\\d]+";
// iterate through the tokens of target expression
Pattern pattern = Pattern.compile(targetExpressionRegex);
Matcher matcher = pattern.matcher(targetExpression);
while (matcher.find()) {
String token = matcher.group();
if (StringUtils.isNumeric(token)) {
int targetID = Integer.parseInt(token);
if (targetID > 0) {
returnList.add(targetID);
}
}
}
}
return returnList;
}
/**
* Gets a storage attribute value by name. The value must be a valid integer, otherwise a validation error is thrown.
*
* @param attributeName the attribute name (case insensitive)
* @param storageEntity the storage entity
* @param attributeRequired specifies whether the attribute is mandatory (i.e. whether it has a value or not).
* @param attributeValueRequiredIfExists specifies whether the attribute value is mandatory (i.e. the attribute must exist and its value must also contain a
* value).
*
* @return the attribute value from the attribute with the attribute name.
* @throws IllegalStateException if the attribute is mandatory and this storage contains no attribute with this attribute name or the value is blank. This
* will produce a 500 HTTP status code error. If storage attributes are able to be updated by a REST invocation in the future, we might want to consider
* making this a 400 instead since the user has the ability to fix the issue on their own. Also throws when the value exists, but is not a valid integer.
*/
public Integer getStorageAttributeIntegerValueByName(String attributeName, StorageEntity storageEntity, boolean attributeRequired,
boolean attributeValueRequiredIfExists) throws IllegalStateException
{
Integer intValue = null;
String value = getStorageAttributeValueByName(attributeName, storageEntity, attributeRequired, attributeValueRequiredIfExists);
if (value != null)
{
if (!StringUtils.isNumeric(value))
{
throw new IllegalStateException("Storage attribute \"" + attributeName + "\" must be a valid integer. Actual value is \"" + value + "\"");
}
intValue = Integer.parseInt(value.trim());
}
return intValue;
}
/**
* Based on the partial dimensional ID, return a title for this panel's tab
* @return
*/
private String generateTabName() {
String[] dimArray = partialDeclensionIds.split(",");
dimArray = Arrays.copyOfRange(dimArray, 1, dimArray.length); // first value always empty
String ret = "";
for (int i = 0; i < dimArray.length; i++) {
String curId = dimArray[i];
DeclensionNode node = decMan.getDimensionalDeclensionTemplateByIndex(typeId, i);
// skips X and Y elements
if (StringUtils.isNumeric(curId) && !node.isDimensionless()) {
ret += node.getDeclensionDimensionById(Integer.parseInt(curId)).getValue() + " ";
}
}
return ret;
}
private static boolean isUcBrowserVersionAtLeast(int major, int minor, int build, String userAgent) {
Matcher matcher = ucBrowserVersion.matcher(userAgent);
if (matcher.find() && matcher.groupCount() == 3) {
String majorVersion = matcher.group(1);
String minorVersion = matcher.group(2);
String buildVersion = matcher.group(3);
if (StringUtils.isNumeric(majorVersion)) {
int majorVer = Integer.parseInt(majorVersion);
if (majorVer != major) return majorVer > major;
}
if (StringUtils.isNumeric(minorVersion)) {
int minorVer = Integer.parseInt(minorVersion);
if (minorVer != minor) return minorVer > minor;
}
if (StringUtils.isNumeric(buildVersion)) {
int buildVer = Integer.parseInt(buildVersion);
return buildVer >= build;
}
}
return false;
}
/**
* @param s 0 or 1
* @return 0 = false, 1 = true
*/
public static Boolean getBooleanValueFromIntWithDefaultFalse(String s) {
Boolean i = false;
String s2 = s.trim();
if (StringUtils.isNotBlank(s2) && StringUtils.isNumeric(s2)) {
Integer number = Integer.parseInt(s);
if (number.equals(0)) {
return Boolean.FALSE;
} else if (number.equals(1)) {
return Boolean.TRUE;
}
}
return i;
}
private FrameSketch buildFrameSketch(Element frameElement) {
Element frameSketchElement = frameElement.getChild(TAB_SKETCH);
if (null == frameSketchElement) {
return null;
}
String x1Val = frameSketchElement.getAttributeValue(ATTRIBUTE_X1);
String y1Val = frameSketchElement.getAttributeValue(ATTRIBUTE_Y1);
String x2Val = frameSketchElement.getAttributeValue(ATTRIBUTE_X2);
String y2Val = frameSketchElement.getAttributeValue(ATTRIBUTE_Y2);
int x1 = StringUtils.isNumeric(x1Val) ? new Integer(x1Val) : 0;
int y1 = StringUtils.isNumeric(x1Val) ? new Integer(y1Val) : 0;
int x2 = StringUtils.isNumeric(x1Val) ? new Integer(x2Val) : 0;
int y2 = StringUtils.isNumeric(x1Val) ? new Integer(y2Val) : 0;
FrameSketch frameSketch = new FrameSketch();
frameSketch.setCoords(x1, y1, x2, y2);
return frameSketch;
}
@Override
public Money getPurchasePrice(){
String priceString = getEntity().getEkPreis();
if (StringUtils.isNumeric(priceString)) {
return ModelUtil.getMoneyForCentString(priceString).orElse(null);
}
return null;
}
/**
* Validates a given field to have a minimum length
*
* @param name The field to check
* @param minLength The minimum length
* @param message A custom error message instead of the default one
*/
public void expectMin(String name, double minLength, String message) {
String value = Optional.ofNullable(get(name)).orElse("");
if (StringUtils.isNumeric(value)) {
if (Double.parseDouble(value) < minLength) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MIN_KEY.name(), name, minLength)));
}
} else {
if (value.length() < minLength) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MIN_KEY.name(), name, minLength)));
}
}
}
/**
* Checks to see if the indicated name is an anonymous name with the indicated prefix
* followed by a number.
* @param name the anonymous data type name to check.
* @param prefix the prefix string ("_struct_", "_union_", "enum_").
* @return true if the name is an anonymous data type name with the expected prefix.
*/
private static boolean hasAnonymousName(String name, String prefix) {
if (!name.startsWith(prefix)) {
return false; // doesn't have expected prefix.
}
String suffix = name.substring(prefix.length());
if (!StringUtils.isNumeric(suffix)) {
return false;
}
return true;
}
public ScreenSize(String param) {
this.code= CODE_DEFAULT;
if (StringUtils.isNotBlank(param)) {
String[] size = param.toLowerCase().trim().split(DEFAULT_SEPARATOR);
if (null != size && size.length == 2 && StringUtils.isNumeric(size[0]) && StringUtils.isNumeric(size[1])) {
this.width = Integer.valueOf(size[0]);
this.height = Integer.valueOf(size[1]);
}
}
if (this.height == 0 || this.width == 0) {
this.setWidth(WIDTH_DEFAULT);
this.setHeight(HEIGHT_DEFAULT);
_logger.warn("Invalid or null size detected. Defaulting to {}x{}", this.getWidth(), this.getHeight());
}
}
private void addItemToPlaylist(int playlistId, String id, int index) {
if (StringUtils.isBlank(id)) {
return;
}
GetMetadata parameters = new GetMetadata();
parameters.setId(id);
parameters.setIndex(0);
parameters.setCount(Integer.MAX_VALUE);
GetMetadataResponse metadata = getMetadata(parameters);
List<MediaFile> newSongs = new ArrayList<MediaFile>();
for (AbstractMedia media : metadata.getGetMetadataResult().getMediaCollectionOrMediaMetadata()) {
if (StringUtils.isNumeric(media.getId())) {
MediaFile mediaFile = mediaFileService.getMediaFile(Integer.parseInt(media.getId()));
if (mediaFile != null && mediaFile.isFile()) {
newSongs.add(mediaFile);
}
}
}
List<MediaFile> existingSongs = playlistService.getFilesInPlaylist(playlistId);
if (index == -1) {
index = existingSongs.size();
}
existingSongs.addAll(index, newSongs);
playlistService.setFilesInPlaylist(playlistId, existingSongs);
}
public PermissionOverwrite fromOctal(final String input) {
if(StringUtils.isBlank(input)) {
return null;
}
if(StringUtils.length(input) != 3) {
return null;
}
if(!StringUtils.isNumeric(input)) {
return null;
}
this.user.parse(input.charAt(0));
this.group.parse(input.charAt(1));
this.other.parse(input.charAt(2));
return this;
}
/**
* 文章/页面 入口
* 兼容老版本
*
* @param postUrl 文章路径名
* @return 模板路径/themes/{theme}/post
*/
@GetMapping(value = {"/{postUrl}.html", "post/{postUrl}"})
public String getPost(@PathVariable String postUrl) {
User loginUser = getLoginUser();
Boolean isNumeric = StringUtils.isNumeric(postUrl);
Post post;
if (isNumeric) {
post = postService.get(Long.valueOf(postUrl));
if (post == null) {
post = postService.findByPostUrl(postUrl);
}
} else {
post = postService.findByPostUrl(postUrl, PostTypeEnum.POST_TYPE_POST.getValue());
}
// 文章不存在404
if (null == post) {
return this.renderNotFound();
}
// 文章存在但是未发布只有作者可以看
if (!post.getPostStatus().equals(PostStatusEnum.PUBLISHED.getCode())) {
if (loginUser == null || !loginUser.getId().equals(post.getUserId())) {
return this.renderNotFound();
}
}
// 如果是页面
if (Objects.equals(post.getPostType(), PostTypeEnum.POST_TYPE_PAGE.getValue())) {
return "redirect:/p/" + post.getPostUrl();
}
// 如果是公告
else if (Objects.equals(post.getPostType(), PostTypeEnum.POST_TYPE_NOTICE.getValue())) {
return "redirect:/notice/" + post.getPostUrl();
}
return "forward:/article/" + post.getId();
}
protected Object parseFrameType(Map<String, Label> labels, String typeStr) throws Exception {
if(typeStr.length() == 1) //Base type
{
if(typeStr.equals("T"))
return Opcodes.TOP;
else if(typeStr.equals("I"))
return Opcodes.INTEGER;
else if(typeStr.equals("F"))
return Opcodes.FLOAT;
else if(typeStr.equals("D"))
return Opcodes.DOUBLE;
else if(typeStr.equals("J"))
return Opcodes.LONG;
else if(typeStr.equals("N"))
return Opcodes.NULL;
else if(typeStr.equals("U"))
return Opcodes.UNINITIALIZED_THIS;
else
throw new Exception(getCurrentTokenLine() + ": Error while parsing frame type, found no type for " + typeStr);
}
//Label
if(typeStr.startsWith("L") && StringUtils.isNumeric(typeStr.substring(1)))
return getLabel(labels, typeStr);
//Class name
return typeStr;
}
/**
* 恢复元数据
*/
private void recoverMetadata() throws IOException {
File root = new File(this.path);
if (!root.exists()) {
boolean ret = root.mkdir();
if (!ret) {
logger.info("Recover election metadata create dir {} fail",
root.getAbsoluteFile());
throw new IOException("Delete file " + root.getAbsoluteFile() + " fail");
}
}
File[] topicDirs = root.listFiles();
if (topicDirs == null) {
return;
}
for (File topicDir : topicDirs) {
if (!topicDir.isDirectory()) {
continue;
}
String topic = topicDir.getName().replace('@', File.separatorChar);
File[] pgsFiles = topicDir.listFiles();
if (pgsFiles == null) {
continue;
}
for (File filePg : pgsFiles) {
if (!StringUtils.isNumeric(filePg.getName())) {
logger.warn("Recover election metadata of topic {} fail, pg is {}",
topic, filePg.getName());
continue;
}
TopicPartitionGroup partitionGroup = new TopicPartitionGroup(topic, Integer.valueOf(filePg.getName()));
try (ElectionMetadata metadata = ElectionMetadata.Build.create(this.path, partitionGroup).build()) {
metadata.recover();
metadataMap.put(partitionGroup, metadata);
} catch (Exception e) {
logger.info("Create election metadata fail", e);
}
}
}
}
public static Integer getSafeInteger(final String value) {
if(StringUtils.isNumeric(value)) {
return Integer.valueOf(value);
}
return null;
}
private ReturnT<String> callback(HandleCallbackParam handleCallbackParam) {
// valid log item
XxlJobLog log = xxlJobLogDao.load(handleCallbackParam.getLogId());
if (log == null) {
return new ReturnT<String>(ResultCodeMessage.FAILURE, "log item not found.");
}
if (log.getHandleCode() > 0) {
return new ReturnT<String>(ResultCodeMessage.FAILURE, "log repeate callback."); // avoid repeat callback, trigger child job etc
}
// trigger success, to trigger child job
String callbackMsg = null;
if (IJobHandler.SUCCESS.getCode() == handleCallbackParam.getExecuteResult().getCode()) {
XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(log.getJobId());
if (xxlJobInfo!=null && StringUtils.isNotBlank(xxlJobInfo.getChildJobId())) {
callbackMsg = "<br><br><span style=\"color:#00c0ef;\" > >>>>>>>>>>>"+ I18nUtil.getString("jobconf_trigger_child_run") +"<<<<<<<<<<< </span><br>";
String[] childJobIds = xxlJobInfo.getChildJobId().split(",");
for (int i = 0; i < childJobIds.length; i++) {
int childJobId = (StringUtils.isNotBlank(childJobIds[i]) && StringUtils.isNumeric(childJobIds[i]))?Integer.valueOf(childJobIds[i]):-1;
if (childJobId > 0) {
JobTriggerPoolHelper.trigger(childJobId, TriggerTypeEnum.PARENT, 0, null, null);
ReturnT<String> triggerChildResult = ReturnT.SUCCESS;
// add msg
callbackMsg += MessageFormat.format(I18nUtil.getString("jobconf_callback_child_msg1"),
(i+1),
childJobIds.length,
childJobIds[i],
(triggerChildResult.getCode()==ResultCodeMessage.SUCCESS?I18nUtil.getString("system_success"):I18nUtil.getString("system_fail")),
triggerChildResult.getMsg());
} else {
callbackMsg += MessageFormat.format(I18nUtil.getString("jobconf_callback_child_msg2"),
(i+1),
childJobIds.length,
childJobIds[i]);
}
}
}
}
// handle msg
StringBuffer handleMsg = new StringBuffer();
if (log.getHandleMsg()!=null) {
handleMsg.append(log.getHandleMsg()).append("<br>");
}
if (handleCallbackParam.getExecuteResult().getMsg() != null) {
handleMsg.append(handleCallbackParam.getExecuteResult().getMsg());
}
if (callbackMsg != null) {
handleMsg.append(callbackMsg);
}
// success, save log
log.setHandleTime(new Date());
log.setHandleCode(handleCallbackParam.getExecuteResult().getCode());
log.setHandleMsg(handleMsg.toString());
xxlJobLogDao.updateHandleInfo(log);
return ReturnT.SUCCESS;
}
public static boolean isMessageStringNumeric(@Nullable IServerMessage m) {
if (m != null && m.toString() != null) {
return StringUtils.isNumeric(m.toString());
}
return false;
}