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

The following are Jave code examples for showing how to use isNumeric() of the org.apache.commons.lang.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: osc-core   File: VirtualizationConnectorDtoValidator.java   Source Code and License Vote up 9 votes
public static void checkFieldFormat(VirtualizationConnectorDto dto) throws VmidcBrokerInvalidEntryException {
    ValidateUtil.checkForValidIpAddressFormat(dto.getProviderIP());

    if (dto.getType().isOpenstack() && dto.getProviderAttributes() != null) {
        String rabbitMqPort = dto.getProviderAttributes().get(ATTRIBUTE_KEY_RABBITMQ_PORT);
        if (!StringUtils.isNumeric(rabbitMqPort)) {
            throw new VmidcBrokerInvalidEntryException(
                    ATTRIBUTE_KEY_RABBITMQ_PORT + " expected to be an Integer. Value is: " + rabbitMqPort);
        }

        String rabbitMQIP = dto.getProviderAttributes().get(ATTRIBUTE_KEY_RABBITMQ_IP);
        if (!StringUtils.isBlank(rabbitMQIP)) {
            ValidateUtil.checkForValidIpAddressFormat(rabbitMQIP);
        }
    }
}
 
Example 2
Project: Dragonfly   File: UrlUtil.java   Source Code and License Vote up 6 votes
public static boolean isValidIp(String ip) {
    try {
        if (StringUtils.isNotBlank(ip)) {
            String[] fieldArr = ip.split("\\.");
            if (fieldArr.length == 4) {
                for (String field : fieldArr) {
                    if (!StringUtils.isNumeric(field)) {
                        return false;
                    }
                }
                return true;
            }
        }
    } catch (Exception e) {
        logger.error("ip:{} is illegal", ip);
    }

    return false;
}
 
Example 3
Project: easycms   File: ManageServlet.java   Source Code and License Vote up 6 votes
private void toDataForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
	String modelId= request.getParameter("modelId");
	Model model = modelService.get(Integer.parseInt(modelId));
	Column column = new Column();
	column.setModelId(model.getId());
	List<Column> columns = columnService.findList(column);

	request.setAttribute("columns", columns);
	request.setAttribute("model", model);
	
	Data entity = new Data();
	String id =  request.getParameter("id");
	if (StringUtils.isNotEmpty(id) && StringUtils.isNumeric(id)) {
		entity.setTableName(model.getTableName());
		entity.setId(Integer.parseInt(id));
		entity = dataService.get(entity);
	}
	request.setAttribute("entity", entity);
	request.getRequestDispatcher(prefix + "manage/dataForm.jsp").forward(request, response);
}
 
Example 4
Project: easycms   File: TableServlet.java   Source Code and License Vote up 6 votes
private void formColumn(HttpServletRequest request, HttpServletResponse response) throws Exception {
	Column column = new Column();
	String modelId  = request.getParameter("modelId");
	column.setModelId(Integer.parseInt(modelId));
	
	Cfg tableCfg = new Cfg();
	tableCfg.setC(3);
	List<Cfg> types = cfgService.findList(tableCfg);
	request.setAttribute("types", types);
	tableCfg.setC(1);
	List<Cfg> maps = cfgService.findList(tableCfg);
	request.setAttribute("maps", maps);
	String id = request.getParameter("id");
	
	if (StringUtils.isNumeric(id)) {
		column = columnService.get(Integer.parseInt(id));
	}
	request.setAttribute("entity", column);
	request.getRequestDispatcher(prefix + "model/formColumn.jsp").forward(request, response);
}
 
Example 5
Project: easycms   File: TableServlet.java   Source Code and License Vote up 6 votes
private void formModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
	Model model = new Model();
	String id = request.getParameter("id");
	
	if (StringUtils.isNumeric(id)) {
		model = modelService.get(Integer.parseInt(id));
	} else {
		//新增时的父节点
		String parentId = request.getParameter("parentId");
		model.setParentId(Integer.parseInt(parentId));
	}
	request.setAttribute("entity", model);
	
	
	request.getRequestDispatcher(prefix + "model/formModel.jsp").forward(request, response);
}
 
Example 6
Project: easycms   File: TableServlet.java   Source Code and License Vote up 6 votes
private void saveModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
	
	Model model = new Model();
	String id = request.getParameter("id");
	if (StringUtils.isNotEmpty(id)) {
		model.setId(Integer.parseInt(id));
	}
	String parentId = request.getParameter("parentId");
	if (StringUtils.isNumeric(parentId)) {
		model.setParentId(Integer.parseInt(parentId));
	}
	String name = request.getParameter("name");
	model.setName(name);
	String tableName = request.getParameter("tableName");
	model.setTableName(tableName);
	String seq = request.getParameter("seq");
	if (StringUtils.isNumeric(seq)) {
		model.setSeq(Integer.parseInt(seq));
	}
	String remark = request.getParameter("remark");
	model.setRemark(remark);
	
	modelService.save(model);
	this.write(new Ajax(true, "保存成功"), response);
}
 
Example 7
Project: FSTestTools   File: FirstSpiritConnectionRule.java   Source Code and License Vote up 6 votes
/**
 * Instantiates a new First spirit connection rule.
 *
 * @param host     the host, e.g. localhost
 * @param port     the port, e.g. 1088
 * @param mode     the mode
 * @param login    the login, e.g. Admin
 * @param password the password, e.g. Admin
 */
public FirstSpiritConnectionRule(final String host, final String port, final ConnectionMode mode, final String login, final String password) {
    if (StringUtils.isBlank(host)) {
        throw new IllegalArgumentException("host can not be null or empty");
    }
    if (StringUtils.isBlank(port)) {
        throw new IllegalArgumentException("port can not be null or empty");
    }
    if (!StringUtils.isNumeric(port)) {
        throw new IllegalArgumentException("port must be numeric");
    }
    if (StringUtils.isBlank(login)) {
        throw new IllegalArgumentException("login can not be null or empty");
    }
    if (StringUtils.isBlank(password)) {
        throw new IllegalArgumentException("password can not be null or empty");
    }
    this.host = host;
    this.port = Integer.parseInt(port);
    this.mode = Objects.requireNonNull(mode, "mode can not be null");
    this.login = login;
    this.password = password;
    commands = new ConcurrentHashMap<>();
    populateMap(commands);
}
 
Example 8
Project: osc-core   File: VirtualizationConnectorDtoValidatorParameterizedTest.java   Source Code and License Vote up 6 votes
static List<Object[]> getInvalidMqPortTestData() {
    String[] invalidNames = new String[] { null, "",
            StringUtils.rightPad("dtoName", ValidateUtil.DEFAULT_MAX_LEN + 10, 'e') };

    List<Object[]> result = new ArrayList<>();

    for (String invalidName : invalidNames) {
        VirtualizationConnectorDto vcDto = VirtualizationConnectorDtoValidatorTestData.generateOpenStackVCWithoutSDN();
        vcDto.getProviderAttributes().put(ATTRIBUTE_KEY_RABBITMQ_PORT, invalidName);

        String errorMessage;
        if (invalidName == null || invalidName.equals("")) {
            errorMessage = Server.PRODUCT_NAME + ": " + "Rabbit MQ Port " + EMPTY_VALUE_ERROR_MESSAGE;
        } else if (!StringUtils.isNumeric(invalidName)) {
            errorMessage = ATTRIBUTE_KEY_RABBITMQ_PORT
                    + " expected to be an Integer. Value is: " + invalidName;
        } else {
            errorMessage = Server.PRODUCT_NAME + ": " + ATTRIBUTE_KEY_RABBITMQ_PORT
                    + " length should not exceed " + ValidateUtil.DEFAULT_MAX_LEN
                    + " characters. The provided field exceeds this limit by "
                    + (invalidName.length() - ValidateUtil.DEFAULT_MAX_LEN) + " characters.";
        }

        Class<?> expectedException = VmidcBrokerInvalidEntryException.class;

        result.add(new Object[] { vcDto, expectedException, errorMessage });
    }

    return result;
}
 
Example 9
Project: renren-msg   File: IHUYI_SendService.java   Source Code and License Vote up 5 votes
@Override
public int getBalance(MsgChannelEntity channel) {
	if(channel==null){
		return 0;
	}
	NameValuePair[] data = {
			new NameValuePair("account", channel.getUsername()),
			new NameValuePair("password", channel.getPassword()), 
			new NameValuePair("format", "json")
	};
	String submitResult=null;
	int count=0;
	//三次尝试
	do{
		count++;
		submitResult= Sendsms.send(data, channel.getUrl4query());
	}while(StringUtils.isEmpty(submitResult)&&count<RESENDCOUNT);
	//确认服务器没有相应
	if(StringUtils.isEmpty(submitResult)){
		throw new RRException("服务器没有响应");
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	Map<String, Object> maps = (Map)JSON.parse(submitResult);
	String code =String.valueOf(maps.get("code")).trim();
	String num =String.valueOf(maps.get("num")).trim();
	if(!"2".equals(code)){
		throw new RRException("channelId:"+channel.getChannelId()+"查询异常,code:"+maps.get("code")+"异常描述:"+maps.get("msg"));
	}
	if(StringUtils.isEmpty(num)||!StringUtils.isNumeric(num)){
		throw new RRException("channelId:"+channel.getChannelId()+"查询异常,换回num值为"+maps.get("num"));
	}
	return Integer.parseInt(num);
}
 
Example 10
Project: easycms   File: TableServlet.java   Source Code and License Vote up 5 votes
private void saveColumn(HttpServletRequest request, HttpServletResponse response) throws Exception {
	
	Column column = new Column();
	String id = request.getParameter("id");
	if (StringUtils.isNotEmpty(id)) {
		column.setId(Integer.parseInt(id));
	}
	String modelId = request.getParameter("modelId");
	column.setModelId(Integer.parseInt(modelId));
	
	String name = request.getParameter("name");
	column.setName(name);
	String type = request.getParameter("type");
	column.setType(type);
	String mappingData = request.getParameter("mappingData");
	column.setMappingData(mappingData);
	
	String sql = request.getParameter("sql");
	column.setSql(sql);
	
	String seq = request.getParameter("seq");
	if (StringUtils.isNumeric(seq)) {
		column.setSeq(Integer.parseInt(seq));
	}
	String width = request.getParameter("width");
	if (StringUtils.isNumeric(width)) {
		column.setWidth(Integer.parseInt(width));
	}
	String allowBlank = request.getParameter("allowBlank");
	column.setAllowBlank(allowBlank);
	String listShow = request.getParameter("listShow");
	column.setListShow(listShow);
	String remark = request.getParameter("remark");
	column.setRemark(remark);
	
	columnService.save(column);
	this.write(new Ajax(true, "保存成功"), response);
}
 
Example 11
Project: airsonic   File: SubsonicRESTController.java   Source Code and License Vote up 5 votes
private String mapId(String id) {
    if (id == null || id.startsWith(CoverArtController.ALBUM_COVERART_PREFIX) ||
            id.startsWith(CoverArtController.ARTIST_COVERART_PREFIX) || StringUtils.isNumeric(id)) {
        return id;
    }

    try {
        String path = StringUtil.utf8HexDecode(id);
        MediaFile mediaFile = mediaFileService.getMediaFile(path);
        return String.valueOf(mediaFile.getId());
    } catch (Exception x) {
        return id;
    }
}
 
Example 12
Project: airsonic   File: SonosService.java   Source Code and License Vote up 5 votes
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);
}
 
Example 13
Project: maven-release-yearly-policy   File: YearlyVersionPolicy.java   Source Code and License Vote up 5 votes
private String incrementSubVersion(final String subVersion) {
    if (StringUtils.isNumeric(subVersion)) {
        return Integer.toString(Integer.parseInt(subVersion) + 1);
    }

    final String headVersionPart = StringUtils.substringBeforeLast(subVersion, ".");
    final String tailVersionPart = StringUtils.substringAfterLast(subVersion, ".");
    final Integer newSubVersion = Integer.parseInt(tailVersionPart) + 1;

    return headVersionPart + "." + newSubVersion.toString();
}
 
Example 14
Project: Hydrograph   File: Converter.java   Source Code and License Vote up 5 votes
/**
 * Converts the String to {@link BigInteger}
 * @param propertyName
 * @param nameOfFeild
 * @param fieldKey
 * @return
 */
public BigInteger getDBAdditionalParamValue(String propertyName , String nameOfField, String fieldKey){
	Map<String,String> propertyValue = (Map<String, String>) properties.get(propertyName);
	if (StringUtils.isNotBlank(propertyValue.get(nameOfField)) && StringUtils.isNumeric(propertyValue.get(nameOfField))) {
		BigInteger bigInteger = new BigInteger(String.valueOf(propertyValue.get(nameOfField)));
		return bigInteger;
	} else if (ParameterUtil.isParameter(propertyValue.get(nameOfField))) {
		ComponentXpath.INSTANCE.getXpathMap()
				.put((ComponentXpathConstants.COMPONENT_XPATH_BOOLEAN.value().replace(ID, component.getComponentId()))
						.replace(Constants.PARAM_PROPERTY_NAME, fieldKey),
						new ComponentsAttributeAndValue(null, propertyValue.get(nameOfField)));
		return null;
	}
	return null;
}
 
Example 15
Project: hadoop   File: WordListAnonymizerUtility.java   Source Code and License Vote up 5 votes
/**
 * Checks if the data needs anonymization. Typically, data types which are 
 * numeric in nature doesn't need anonymization.
 */
public static boolean needsAnonymization(String data) {
  // Numeric data doesn't need anonymization
  // Currently this doesnt support inputs like
  //   - 12.3
  //   - 12.3f
  //   - 90L
  //   - 1D
  if (StringUtils.isNumeric(data)) {
    return false;
  }
  return true; // by default return true
}
 
Example 16
Project: osc-core   File: VirtualizationConnectorDtoValidator.java   Source Code and License Vote up 5 votes
public static void checkFieldLength(VirtualizationConnectorDto dto) throws Exception {

        Map<String, String> map = new HashMap<>();

        map.put("Name", dto.getName());

        map.put("Controller User Name", dto.getControllerUser());
        map.put("Controller Password", dto.getControllerPassword());

        map.put("Provider User Name", dto.getProviderUser());
        map.put("Provider Password", dto.getProviderPassword());
        if (dto.getType().isOpenstack()) {
            map.put("Admin Project Name", dto.getAdminProjectName());
            String rabbitMqPort = dto.getProviderAttributes().get(ATTRIBUTE_KEY_RABBITMQ_PORT);
            if (!StringUtils.isNumeric(rabbitMqPort)) {
                throw new VmidcBrokerInvalidEntryException(ATTRIBUTE_KEY_RABBITMQ_PORT
                        + " expected to be an Integer. Value is: " + rabbitMqPort);
            }
            map.put("Admin Domain Id", dto.getAdminDomainId());
        }
        if (dto.getProviderAttributes() != null) {
            for (Entry<String, String> entry : dto.getProviderAttributes().entrySet()) {
                map.put("Attribute Key", entry.getKey());
                map.put("Attribute Value", entry.getValue());
            }
        }

        ValidateUtil.validateFieldLength(map, ValidateUtil.DEFAULT_MAX_LEN);
    }
 
Example 17
Project: Dragonfly   File: Assert.java   Source Code and License Vote up 5 votes
public final static void assertNumeric(String val, int errCode,
    String errorMessage) {
    boolean valid = StringUtils.isNumeric(val);
    if (!valid) {
        fail(errCode, errorMessage);
    }
}
 
Example 18
Project: Locked   File: PayCommand.java   Source Code and License Vote up 4 votes
@Override
public boolean execute(CommandSender sender, String[] args) throws CommandException {
    if (!(sender instanceof Player)) {
        throw new CommandException("Only players can use this command!");
    }
    Player player = (Player) sender;
    try {
        int playerBal = ScrapsUtil.getScraps(player);
        if (args.length != 2) {
            return false;
        }
        if (!StringUtils.isNumeric(args[1])) {
            return false;
        }
        int amount = Integer.valueOf(args[1]);
        boolean x = false;
        for (Player p : Bukkit.getOnlinePlayers()) {
            if (p.getName().equals(args[0])) {
                x = true;
                break;
            }
        }
        if (!x) {
            player.sendMessage(ChatColor.RED + "Could not find the specified player.");
            return true;
        }
        Player target = Bukkit.getPlayer(args[0]);
        if (amount > playerBal) {
            player.sendMessage(ChatColor.RED + "You do not have " + ChatColor.DARK_RED + String.valueOf(amount) + ChatColor.RED + " scraps!");
            return true;
        }
        if (amount == 0) {
            player.sendMessage(ChatColor.RED + "You can not pay " + ChatColor.DARK_RED + "0" + ChatColor.RED + " scraps to someone!");
            return true;
        }
        ScrapsUtil.payScraps(player, target, amount);
        player.sendMessage(ChatColor.GREEN + "You payed " + target.getName() + " " + ChatColor.GOLD + String.valueOf(amount) + ChatColor.GREEN + " scraps!");
        target.sendMessage(ChatColor.GREEN + "You received " + ChatColor.GOLD + String.valueOf(amount) + ChatColor.GREEN + " scraps from " + player.getName() + "!");
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return true;
}
 
Example 19
Project: NetworkCore   File: PayCommand.java   Source Code and License Vote up 4 votes
@Override
public boolean execute(CommandSender sender, String[] args) throws CommandException {
    if(!(sender instanceof Player)){
        throw new CommandException("Only players can use this command!");
    }
    Player player = (Player) sender;
    try {
        int playerBal = ValeUtil.getVale(player);
        if (args.length != 2) {
            return false;
        }
        if (!StringUtils.isNumeric(args[1])) {
            return false;
        }
        int amount = Integer.valueOf(args[1]);
        boolean x = false;
        for(Player p : Bukkit.getOnlinePlayers()){
            if(p.getName().equals(args[0])){
                x = true;
                break;
            }
        }
        if(!x){
            player.sendMessage(ChatColor.RED + "Could not find the specified player.");
            return true;
        }
        Player target = Bukkit.getPlayer(args[0]);
        if (amount > playerBal) {
            player.sendMessage(ChatColor.RED + "You do not have " + ChatColor.DARK_RED + String.valueOf(amount) + ChatColor.RED + " vales!");
            return true;
        }
        if(amount==0){
            player.sendMessage(ChatColor.RED + "You can not pay " + ChatColor.DARK_RED + "0" + ChatColor.RED + " vales to someone!");
            return true;
        }
        ValeUtil.payVale(player, target, amount);
        player.sendMessage(ChatColor.GREEN + "You payed " + target.getName() + " " +ChatColor.GOLD + String.valueOf(amount) + ChatColor.GREEN + " vales!");
        target.sendMessage(ChatColor.GREEN + "You received " + ChatColor.GOLD + String.valueOf(amount) + ChatColor.GREEN + " vales from " + player.getName() + "!");
    } catch (SQLException e){
        e.printStackTrace();
    }
    return true;
}
 
Example 20
Project: big_data   File: ActiveUserMapper.java   Source Code and License Vote up 4 votes
@Override
protected void map(ImmutableBytesWritable key, Result value, Context context)
		throws IOException, InterruptedException {
	// 获取uuid&platform&serverTime,从hbase返回的结果集Result中
	String uuid = Bytes.toString(value.getValue(family, Bytes.toBytes(EventLogConstants.LOG_COLUMN_NAME_UUID)));
	String platform = Bytes
			.toString(value.getValue(family, Bytes.toBytes(EventLogConstants.LOG_COLUMN_NAME_PLATFORM)));
	String serverTime = Bytes
			.toString(value.getValue(family, Bytes.toBytes(EventLogConstants.LOG_COLUMN_NAME_SERVER_TIME)));

	// 过滤无效数据
	if (StringUtils.isBlank(uuid) || StringUtils.isBlank(platform) || StringUtils.isBlank(serverTime)
			|| !StringUtils.isNumeric(serverTime.trim())) {
		logger.warn("uuid&platform&serverTime不能为空,而且serverTime必须为时间戳");
		return;
	}

	long longOfServerTime = Long.valueOf(serverTime.trim());
	DateDimension dateDimension = DateDimension.buildDate(longOfServerTime, DateEnum.DAY);
	this.outputValue.setId(uuid);

	// 进行platform的构建
	List<PlatformDimension> platforms = PlatformDimension.buildList(platform); // 进行platform创建
	// 获取browser name和browser version
	String browser = Bytes
			.toString(value.getValue(family, Bytes.toBytes(EventLogConstants.LOG_COLUMN_NAME_BROWSER_NAME)));
	String browserVersion = Bytes
			.toString(value.getValue(family, Bytes.toBytes(EventLogConstants.LOG_COLUMN_NAME_BROWSER_VERSION)));
	// 进行browser的维度信息构建
	List<BrowserDimension> browsers = BrowserDimension.buildList(browser, browserVersion);

	// 开始进行输出
	StatsCommonDimension statsCommonDimension = this.outputKey.getStatsCommon();
	// 设置date dimension
	statsCommonDimension.setDate(dateDimension);
	for (PlatformDimension pf : platforms) {
		this.outputKey.setBrowser(defaultBrowser); // 进行覆盖操作
		// 设置platform dimension
		statsCommonDimension.setPlatform(pf);
		// 设置kpi dimension
		statsCommonDimension.setKpi(activeUserKpi);
		context.write(this.outputKey, this.outputValue);

		// 输出browser维度统计
		statsCommonDimension.setKpi(activeUserOfBrowserKpi);
		for (BrowserDimension bw : browsers) {
			this.outputKey.setBrowser(bw); // 设置对应的browsers
			context.write(this.outputKey, this.outputValue);
		}
	}
}