Java Code Examples for org.apache.commons.lang3.StringUtils.isNumeric()

The following are Jave code examples for showing how to use isNumeric() of the org.apache.commons.lang3.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: sentry   File: DayOfWeekDescriptionBuilder.java   View Source Code Vote up 7 votes
@Override
protected String getSingleItemDescription(String expression) {
    String exp = expression;
    if (expression.contains("#")) {
        exp = expression.substring(0, expression.indexOf("#"));
    } else if (expression.contains("L")) {
        exp = exp.replace("L", "");
    }
    if (StringUtils.isNumeric(exp)) {
        int dayOfWeekNum = Integer.parseInt(exp);
        boolean isZeroBasedDayOfWeek = (options == null || options.isZeroBasedDayOfWeek());
        boolean isInvalidDayOfWeekForSetting = (options != null && !options.isZeroBasedDayOfWeek() && dayOfWeekNum <= 1);
        if (isInvalidDayOfWeekForSetting || (isZeroBasedDayOfWeek && dayOfWeekNum == 0)) {
            return DateAndTimeUtils.getDayOfWeekName(7);
        } else if (options != null && !options.isZeroBasedDayOfWeek()) {
            dayOfWeekNum -= 1;
        }
        return DateAndTimeUtils.getDayOfWeekName(dayOfWeekNum);
    } else {
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("EEE").withLocale(Locale.ENGLISH);
        return dateTimeFormatter.parseDateTime(WordUtils.capitalizeFully(exp)).dayOfWeek().getAsText(I18nMessages.getCurrentLocale());
    }
}
 
Example 2
Project: hygene   File: GfaFile.java   View Source Code Vote up 6 votes
/**
 * Iterates over all genomes, and checks for each one in the genome mapping if they are present if they are numeric.
 * If none are numeric, it simply checks if the passed genome is present in the list.
 *
 * @param genomes genomes
 * @param genome  genome
 * @return true iff it is found
 */
public boolean containsGenomeMapping(final List<String> genomes, final String genome) {
    for (final String criteria : genomes) {
        if (StringUtils.isNumeric(criteria) && genome.equals(genomeMapping.get(criteria))) {
            return true;
        }
    }
    return genomes.contains(genome);
}
 
Example 3
Project: pathological-reports   File: OwnerController.java   View Source Code Vote up 6 votes
@RequestMapping("list-owners")
public ModelAndView findUsers(@ModelAttribute("owner") FindOwnerDTO owner,
		                      @RequestParam(name = "initialPage", value = "", required = false) String initialPage) {

	ModelAndView mv = new ModelAndView("users/list-owners");
	mv.addObject("navActive", NavIds.getInstance().getOwners());

	int page = 0;
	int size = 5;

	if (StringUtils.isNumeric(initialPage)) {
		page = Integer.valueOf(initialPage);
	}

	mv.addObject("owners", ownerService.findBy(owner, page, size));

	return mv;
}
 
Example 4
Project: nan   File: FDateJsonDeserializer.java   View Source Code Vote up 6 votes
@Override
public Date deserialize(JsonParser gen, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    String date = gen.getText();

    if (StringUtils.isEmpty(date)) {
        return null;
    }

    if (StringUtils.isNumeric(date)) {
        return new Date(Long.valueOf(date));
    }
    try {
        DateTime dt = fmt.parseDateTime(date);
        return dt.toDate();
    } catch (Exception e) {
        throw new IOException(e);
    }
}
 
Example 5
Project: McrmbCore_Sponge   File: GiveCommand.java   View Source Code Vote up 6 votes
@Override
public boolean execute(CommandSource source, String[] args) {
    if ((args.length != 2 && args.length != 3) || !StringUtils.isNumeric(args[1])) {
        source.sendMessage(TextUtil.of("§c/" + McrmbPluginInfo.config.command + " give <玩家> <增加数量> [理由]"));
        return true;
    }
    if (source instanceof Player && !McrmbPluginInfo.config.opModifyWhiteList.contains(source.getName())) {
        source.sendMessage(TextUtil.of("§c你无法执行该操作,你可以在后台输入/" + McrmbPluginInfo.config.command + " adminwhite add <你的ID> 来添加你到操作点券白名单"));
        return true;
    }
    Task.builder().name("manual-give")
            .execute(() -> {
                ManualResult result = McrmbCoreAPI.manual(args[0], ManualType.ADD, Integer.parseInt(args[1]), args.length == 3 ? args[2] : source.getName() + "加款");
                if (result == null) {
                    source.sendMessage(TextUtil.of("§c加款失败"));
                    return;
                }
                source.sendMessage(TextUtil.of("§2加款成功,返回信息: §a" + result.getMsg()));
            }).submit(McrmbCoreMain.instance());
    return true;
}
 
Example 6
Project: server-extension-java   File: JSONGeometryMapper.java   View Source Code Vote up 6 votes
public ISpatialReference readSpatialReference(String spatialReference) {
    try {
        if (StringUtils.isNumeric(spatialReference)) {
            SpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceFactory();
            try {
                int wkid = Integer.parseInt(spatialReference);
                return spatialReferenceFactory.create(wkid);
            } catch (NumberFormatException ignored) {
            }
        }
        IJSONConverterGeometry converterGeometry = new JSONConverterGeometry();
        IJSONReader jsonReader = createJSONReader(spatialReference);
        ISpatialReference sr = converterGeometry
                .readSpatialReference(jsonReader);
        Cleaner.release(jsonReader);
        Cleaner.release(converterGeometry);
        return sr;
    } catch (IOException e) {
        throw new JSONException(String.format(
                "Cannot map JSON string '%1$s' to %2$s", spatialReference,
                "ISpatialReference"), e);
    }
}
 
Example 7
Project: Biliomi   File: XmlElementPathBeanComparator.java   View Source Code Vote up 6 votes
@Override
public int compare(T o1, T o2) {
  Comparable obj1 = null;
  Comparable obj2 = null;

  try {
    obj1 = (Comparable) PropertyUtils.getProperty(o1, this.propertyPath);
    obj2 = (Comparable) PropertyUtils.getProperty(o2, this.propertyPath);
  } catch (NestedNullException ignored) {
    // Ignored, als het property NULL is, dan vergelijken met NULL
  } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new IllegalArgumentException("Could not retrieve property " + this.propertyPath, e);
  }

  Comparator<Comparable<Object>> objectComparator = null;
  if ((obj1 != null && obj2 != null) && obj1 instanceof String) {
    obj1 = ((String) obj1).toLowerCase().trim();
    obj2 = ((String) obj2).toLowerCase().trim();

    if (!StringUtils.isEmpty((String) obj1) && !StringUtils.isEmpty((String) obj2)) {
      if (StringUtils.isNumeric((String) obj1) && StringUtils.isNumeric((String) obj2)) {
        objectComparator = Comparator.comparingDouble(o -> new Double(String.valueOf(o)));
      }
    }
  }

  if (objectComparator == null) {
    objectComparator = Comparator.naturalOrder();
  }

  //noinspection unchecked
  return Comparator.nullsLast(objectComparator).compare(obj1, obj2);
}
 
Example 8
Project: datax   File: Configuration.java   View Source Code Vote up 6 votes
@SuppressWarnings({ "unchecked" })
private Object findObjectInList(final Object target, final String each) {
	boolean isList = (target instanceof List);
	if (!isList) {
		throw new IllegalArgumentException(String.format(
				"您提供的配置文件有误. 路径[%s]需要配置Json格式的Map对象,但该节点发现实际类型是[%s]. 请检查您的配置并作出修改.",
				each, target.getClass().toString()));
	}

	String index = each.replace("[", "").replace("]", "");
	if (!StringUtils.isNumeric(index)) {
		throw new IllegalArgumentException(
				String.format(
						"系统编程错误,列表下标必须为数字类型,但该节点发现实际类型是[%s] ,该异常代表系统编程错误, 请联系DataX开发团队 !",
						index));
	}

	return ((List<Object>) target).get(Integer.valueOf(index));
}
 
Example 9
Project: openrasp   File: SSRFChecker.java   View Source Code Vote up 5 votes
@Override
public List<EventInfo> checkParam(CheckParameter checkParameter) {
    List<EventInfo> result = new LinkedList<EventInfo>();
    String hostName = (String) checkParameter.getParam("hostname");
    JsonObject config = Config.getConfig().getAlgorithmConfig();

    if (!isModuleIgnore(config, CONFIG_KEY_SSRF_INTRANET)
            && (hostName.endsWith(".xip.io") || hostName.endsWith(".burpcollaborator.net") || hostName.endsWith(".xip.name"))) {
        result.add(AttackInfo.createLocalAttackInfo(checkParameter,
                getActionElement(config, CONFIG_KEY_SSRF_INTRANET), "访问已知的内网探测域名"));
    } else if (!isModuleIgnore(config, CONFIG_KEY_SSRF_AWS)
            && hostName.equals("169.254.169.254")) {
        result.add(AttackInfo.createLocalAttackInfo(checkParameter,
                getActionElement(config, CONFIG_KEY_SSRF_AWS), "尝试读取 AWS metadata"));
    } else if (!isModuleIgnore(config, CONFIG_KEY_SSRF_COMMON)
            && StringUtils.isNumeric(hostName)) {
        result.add(AttackInfo.createLocalAttackInfo(checkParameter,
                getActionElement(config, CONFIG_KEY_SSRF_COMMON), "尝试使用纯数字IP"));
    } else if (!isModuleIgnore(config, CONFIG_KEY_SSRF_OBFUSCATE)
            && hostName.startsWith("0x") && !hostName.contains(".")) {
        result.add(AttackInfo.createLocalAttackInfo(checkParameter,
                getActionElement(config, CONFIG_KEY_SSRF_OBFUSCATE), "尝试使用16进制IP"));
    }

    List<EventInfo> jsResults = new JsChecker().checkParam(checkParameter);
    if (jsResults != null && jsResults.size() > 0) {
        result.addAll(jsResults);
    }
    return result;
}
 
Example 10
Project: framework   File: ValidateCodeServlet.java   View Source Code Vote up 5 votes
private void createImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		/*
		 * 得到参数高,宽,都为数字时,则使用设置高宽,否则使用默认值
		 */
		String width = request.getParameter("width");
		String height = request.getParameter("height");
		if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
			w = NumberUtils.toInt(width);
			h = NumberUtils.toInt(height);
		}

		BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();

		/*
		 * 生成背景
		 */
		createBackground(g);

		/*
		 * 生成字符
		 */
		String s = createCharacter(g);
		request.getSession().setAttribute(VALIDATE_CODE, s);

		g.dispose();
		OutputStream out = response.getOutputStream();
		ImageIO.write(image, "JPEG", out);
		out.close();

	}
 
Example 11
Project: ARCLib   File: XPathUtils.java   View Source Code Vote up 5 votes
/**
 * Returns the index of the child element xpath
 * i.e. /suspension_rec[3] returns 3.  /suspension_rec defaults to 1
 *
 * @param xpath
 * @return 1, the index, or null if the provided xpath is empty
 */
public static Integer getChildElementIndex(String xpath) {
    if (StringUtils.isEmpty(xpath)) {
        return null;
    }

    if (xpath.endsWith(R_BRACKET)) {
        String value = xpath.substring(xpath.lastIndexOf(L_BRACKET) + 1, xpath.lastIndexOf(R_BRACKET));
        if (StringUtils.isNumeric(value)) {
            return Integer.valueOf(value);
        }
    }
    return 1;
}
 
Example 12
Project: happybot   File: DeleteWarnCommand.java   View Source Code Vote up 5 votes
@Override
protected void execute(CommandEvent e) {
    if (C.hasRole(e.getMember(), Roles.HELPER)) {
        if (!e.getArgs().isEmpty() && StringUtils.isNumeric(e.getArgs())) {
            int id = Integer.parseInt(e.getArgs());
            if (warningManager.isValidWarning(id)) {
                User tUser = Main.getJda().getUserById(warningManager.getWarnTargetId(id));
                Channels.LOG.getChannel().sendMessage(new EmbedBuilder()
                        .setAuthor(e.getMember().getUser().getName() + "#" + e.getMember().getUser().getDiscriminator(), null,  e.getMember().getUser().getAvatarUrl())
                        .setColor(Color.YELLOW)
                        .setThumbnail(tUser.getAvatarUrl())
                        .setDescription(":information_source: **Warning Deleted**\n" + "⚠ " + C.bold("Warned " + tUser.getName() + "#" + tUser.getDiscriminator()) + "\n:page_facing_up: " + C.bold("Reason: ") + warningManager.getWarnReason(id) + "\n:id: **Warn ID** " + String.valueOf(id))
                        .build()).queue();
                if (warningManager.deleteWarning(id)) {
                    e.reply("Deleted warning!");
                } else {
                    e.reply("Warning could not be deleted!");
                }
            } else {
                e.replyError("Invalid Warning!");
            }
        } else {
            e.replyError("**Correct Usage:** ^" + name + " <warning ID>");
        }
    } else {
        e.reply(C.permMsg(Roles.HELPER));
    }
}
 
Example 13
Project: cyberduck   File: InfoController.java   View Source Code Vote up 5 votes
/**
 * Permission value from input field.
 *
 * @return Null if invalid string has been entered entered,
 */
private Permission getPermissionFromOctalField() {
    if(StringUtils.isNotBlank(octalField.stringValue())) {
        if(StringUtils.length(octalField.stringValue()) >= 3) {
            if(StringUtils.isNumeric(octalField.stringValue())) {
                return new Permission(Integer.valueOf(octalField.stringValue()).intValue());
            }
        }
    }
    log.warn(String.format("Invalid octal field input %s", octalField.stringValue()));
    return null;
}
 
Example 14
Project: tianti   File: WebHelper.java   View Source Code Vote up 5 votes
/**
 * 
 * @param request
 * @return
 */
public static Integer getPageSize(HttpServletRequest request) {

	String pageSize = request.getParameter("pageSize");
	if (StringUtils.isNotBlank(pageSize) && StringUtils.isNumeric(pageSize)) {
		return Integer.parseInt(pageSize);
	}

	return null;
}
 
Example 15
Project: SECP   File: GroupController.java   View Source Code Vote up 5 votes
public Response getGroupGivenId(String id) {
    if (StringUtils.isEmpty(id) || !StringUtils.isNumeric(id)) {
        return Response.status(Response.Status.NO_CONTENT).build();
    }

    long groupID = Long.parseLong(id);
    Group group = getGroup(groupID);

    return Response.status(Response.Status.OK).entity(getGroupResponse(group)).build();
}
 
Example 16
Project: SECP   File: AdminController.java   View Source Code Vote up 5 votes
private void validateInput(String userID, String type) {
    if(StringUtils.isBlank(userID) || !StringUtils.isNumeric(userID)) {
        String error = String.format(AdminErrorMessage.INVALID_ID, type);
        throw new WebApplicationException(error, Response.Status.BAD_REQUEST);
    }
}
 
Example 17
Project: mqttserver   File: HttpJsonpTransport.java   View Source Code Vote up 4 votes
private void handleSubscrible(ChannelHandlerContext ctx, HttpRequest req) {
	if (!HttpSessionStore.checkJSessionId(req)) {
		sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
				UNAUTHORIZED));
		return;
	}

	String topic = HttpSessionStore.getParameter(req, "topic");
	String qosStr = HttpSessionStore.getParameter(req, "qos");
	if (StringUtils.isEmpty(topic)) {
		sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
				BAD_REQUEST));
		return;
	}

	int qos = 0;
	if (StringUtils.isNumeric(qosStr)) {
		try {
			qos = Integer.parseInt(qosStr);
		} catch (Exception e) {
		}
	}
	if (qos > 2 || qos < 0) {
		sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
				BAD_REQUEST));
		return;
	}

	String sessionId = HttpSessionStore.getClientSessionId(req);

	HttpChannelEntity httpChannelEntity = (HttpChannelEntity) MemoryMetaPool
			.getChannelEntryByClientId(sessionId);

	if (httpChannelEntity.isBlank()) {
		httpChannelEntity.setBlank(false);
		MemoryMetaPool.registerClienId(sessionId, httpChannelEntity);
	}

	MemoryMetaPool.registerTopic(httpChannelEntity, topic);
	logger.debug("topic = " + topic + " qos = " + qos);

	sendFullHttpOKResponse(ctx, req, "{status:true}");
}
 
Example 18
Project: sentry   File: ExpressionParser.java   View Source Code Vote up 4 votes
/**
 * @param expressionParts
 */
private static void normaliseExpression(String[] expressionParts, Options options) {
    // Convert ? to * only for day of month and day of week
    expressionParts[3] = expressionParts[3].replace('?', '*');
    expressionParts[5] = expressionParts[5].replace('?', '*');

    // Convert 0/, 1/ to */
    expressionParts[0] = expressionParts[0].startsWith("0/") ? expressionParts[0].replace("0/", "*/") : expressionParts[0]; // seconds
    expressionParts[1] = expressionParts[1].startsWith("0/") ? expressionParts[1].replace("0/", "*/") : expressionParts[1]; // minutes
    expressionParts[2] = expressionParts[2].startsWith("0/") ? expressionParts[2].replace("0/", "*/") : expressionParts[2]; // hours
    expressionParts[3] = expressionParts[3].startsWith("1/") ? expressionParts[3].replace("1/", "*/") : expressionParts[3]; // DOM
    expressionParts[4] = expressionParts[4].startsWith("1/") ? expressionParts[4].replace("1/", "*/") : expressionParts[4]; // Month
    expressionParts[5] = expressionParts[5].startsWith("1/") ? expressionParts[5].replace("1/", "*/") : expressionParts[5]; // DOW

    // convert */1 to *
    for (int i = 0; i < expressionParts.length; i++) {
        if ("*/1".equals(expressionParts[i])) {
            expressionParts[i] = "*";
        }
    }

    // convert SUN-SAT format to 0-6 format
    if (!StringUtils.isNumeric(expressionParts[5])) {
        for (int i = 0; i <= 6; i++) {
            expressionParts[5] = expressionParts[5].replace(DateAndTimeUtils.getDayOfWeekName(i + 1), String.valueOf(i));
        }
    }

    // convert JAN-DEC format to 1-12 format
    if (!StringUtils.isNumeric(expressionParts[4])) {
        for (int i = 1; i <= 12; i++) {
            DateTime currentMonth = new DateTime().withDayOfMonth(1).withMonthOfYear(i);
            String currentMonthDescription = currentMonth.toString("MMM", Locale.ENGLISH).toUpperCase();
            expressionParts[4] = expressionParts[4].replace(currentMonthDescription, String.valueOf(i));
        }
    }

    // convert 0 second to (empty)
    if ("0".equals(expressionParts[0])) {
        expressionParts[0] = StringUtils.EMPTY;
    }

    // convert 0 DOW to 7 so that 0 for Sunday in zeroBasedDayOfWeek is valid
    if ((options == null || options.isZeroBasedDayOfWeek()) && "0".equals(expressionParts[5])) {
        expressionParts[5] = "7";
    }
}
 
Example 19
Project: happybot   File: EditReportCommand.java   View Source Code Vote up 4 votes
@Override
protected void execute(CommandEvent e) {
    if (C.hasRole(e.getMember(), Roles.HELPER)) {
        if (e.getArgs().isEmpty()) {
            e.replyError("**Correct Usage:** ^" + name + " " + arguments);
            return;
        }

        String[] args = e.getArgs().split("[ ]");

        if (args.length < 1) {
            e.replyError("**Correct Usage:** ^" + name + " " + arguments);
            return;
        }

        String reason =  e.getArgs().replaceFirst(args[0] + " ", "");

        if (!StringUtils.isNumeric(args[0]) || reason.isEmpty()) {
            e.replyError("**Correct Usage:** ^" + name + " " + arguments);
            return;
        }

        int targetReport = Integer.parseInt(args[0]);

        if (!reportManager.isValidReport(targetReport)) {
            e.replyError("Invalid Report ID!");
            return;
        }

        ReportToken token = reportManager.getReportAsToken(targetReport);

        if (token == null) {
            e.replyError("Could not fetch the report data!");
            return;
        }

        if (token.getStatus() == 0) {
            e.replyError("This report is currently still pending, please handle the report first!");
            return;
        }

        if (!token.getHandler().getId().equals(e.getMember().getUser().getId()) && !C.hasRole(e.getMember(), Roles.DEVELOPER)) {
            e.replyError("You may not edit another user's report handle reasons! (Dev+)");
            return;
        }

        reportManager.setHandleReason(targetReport, reason);

        e.replySuccess("Updated the handle reason!");

    } else {
        e.replyError(C.permMsg(Roles.HELPER));
    }
}
 
Example 20
Project: vscrawler   File: IsNumeric.java   View Source Code Vote up 4 votes
@Override
protected boolean handle(CharSequence str) {
    return StringUtils.isNumeric(str);
}