Java Code Examples for org.apache.commons.lang3.math.NumberUtils.isCreatable()

The following are Jave code examples for showing how to use isCreatable() of the org.apache.commons.lang3.math.NumberUtils 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: smockin   File: RuleResolverImpl.java   View Source Code Vote up 6 votes
boolean handleEquals(RestfulMockDefinitionRuleGroupCondition condition, final String inboundValue) {

        if (inboundValue == null) {
            return false;
        }

        final RuleDataTypeEnum ruleMatchDataType = condition.getDataType();
        final String ruleMatchValue = condition.getMatchValue();

        if (RuleDataTypeEnum.TEXT.equals(ruleMatchDataType)) {

            if (condition.isCaseSensitive() != null && condition.isCaseSensitive()) {
                return ruleMatchValue.equals(inboundValue);
            }

            return ruleMatchValue.equalsIgnoreCase(inboundValue);
        } else if (RuleDataTypeEnum.NUMERIC.equals(ruleMatchDataType)
                && NumberUtils.isCreatable(inboundValue)
                && NumberUtils.toDouble(inboundValue) == NumberUtils.toDouble(ruleMatchValue)) {
            return true;
        }

        return false;
    }
 
Example 2
Project: pnc-repressurized   File: BlockHeatSensor.java   View Source Code Vote up 5 votes
@Override
public int getRedstoneValue(World world, BlockPos pos, int sensorRange, String textBoxText, Set<BlockPos> positions) {
    double temperature = Double.MIN_VALUE;
    for (BlockPos p : positions) {
        TileEntity te = world.getTileEntity(p);
        if (te instanceof IHeatExchanger) {
            IHeatExchanger exchanger = (IHeatExchanger) te;
            for (EnumFacing d : EnumFacing.VALUES) {
                IHeatExchangerLogic logic = exchanger.getHeatExchangerLogic(d);
                if (logic != null) temperature = Math.max(temperature, logic.getTemperature());
            }
        }
    }
    return NumberUtils.isCreatable(textBoxText) ?
            temperature - 273 > NumberUtils.toInt(textBoxText) ? 15 : 0 :
            TileEntityCompressedIronBlock.getComparatorOutput((int) temperature);
}
 
Example 3
Project: ClientAPI   File: NumberParser.java   View Source Code Vote up 5 votes
@Override
public final Number parse(ExecutionContext context, Type type, String raw) {
    if (NumberUtils.isCreatable(raw)) {
        return NumberUtils.createNumber(raw);
    }
    return null;
}
 
Example 4
Project: cas-5.1.0   File: GoogleAuthenticatorAuthenticationHandler.java   View Source Code Vote up 5 votes
@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final GoogleAuthenticatorTokenCredential tokenCredential = (GoogleAuthenticatorTokenCredential) credential;

    if (!NumberUtils.isCreatable(tokenCredential.getToken())) {
        throw new PreventedException("Invalid non-numeric OTP format specified.",
                new IllegalArgumentException("Invalid token " + tokenCredential.getToken()));
    }
    final int otp = Integer.parseInt(tokenCredential.getToken());
    LOGGER.debug("Received OTP [{}]", otp);

    final RequestContext context = RequestContextHolder.getRequestContext();
    if (context == null) {
        new IllegalArgumentException("No request context could be found to locate an authentication event");
    }
    final Authentication authentication = WebUtils.getAuthentication(context);
    if (authentication == null) {
        new IllegalArgumentException("Request context has no reference to an authentication event to locate a principal");
    }
    final String uid = authentication.getPrincipal().getId();

    LOGGER.debug("Received principal id [{}]", uid);
    final String secKey = this.credentialRepository.getSecret(uid);
    if (StringUtils.isBlank(secKey)) {
        throw new AccountNotFoundException(uid + " cannot be found in the registry");
    }

    if (this.tokenRepository.exists(uid, otp)) {
        throw new AccountExpiredException(uid + " cannot reuse OTP " + otp + " as it may be expired/invalid");
    }

    final boolean isCodeValid = this.googleAuthenticatorInstance.authorize(secKey, otp);
    if (isCodeValid) {
        this.tokenRepository.store(new GoogleAuthenticatorToken(otp, uid));
        return createHandlerResult(tokenCredential, this.principalFactory.createPrincipal(uid), null);
    }
    throw new FailedLoginException("Failed to authenticate code " + otp);
}
 
Example 5
Project: cas-5.1.0   File: BaseWSFederationRequestController.java   View Source Code Vote up 5 votes
/**
 * Is authentication required?
 *
 * @param fedRequest the fed request
 * @param request    the request
 * @return the boolean
 */
protected boolean shouldRenewAuthentication(final WSFederationRequest fedRequest,
                                            final HttpServletRequest request) {
    if (StringUtils.isBlank(fedRequest.getWfresh()) || NumberUtils.isCreatable(fedRequest.getWfresh())) {
        return false;
    }
    final long ttl = Long.parseLong(fedRequest.getWfresh().trim());
    if (ttl == 0) {
        return false;
    }

    final SecurityToken idpToken = getSecurityTokenFromRequest(request);
    if (idpToken == null) {
        return true;
    }

    final long ttlMs = ttl * 60L * 1000L;
    if (ttlMs > 0) {
        final Date createdDate = idpToken.getCreated();
        if (createdDate != null) {
            final Date expiryDate = new Date();
            expiryDate.setTime(createdDate.getTime() + ttlMs);
            if (expiryDate.before(new Date())) {
                return true;
            }
        }
    }
    return false;
}
 
Example 6
Project: cas-5.1.0   File: CasConfigurationJasyptDecryptor.java   View Source Code Vote up 5 votes
public CasConfigurationJasyptDecryptor(final Environment environment) {
    this.decryptor = new StandardPBEStringEncryptor();

    final String alg = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.ALGORITHM);
    if (StringUtils.isNotBlank(alg)) {
        LOGGER.debug("Configured decryptor algorithm [{}]", alg);
        decryptor.setAlgorithm(alg);
    }

    final String psw = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.PASSWORD);
    if (StringUtils.isNotBlank(psw)) {
        LOGGER.debug("Configured decryptor password");
        decryptor.setPassword(psw);
    }

    final String pName = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.PROVIDER);
    if (StringUtils.isNotBlank(pName)) {
        LOGGER.debug("Configured decryptor provider");
        if (StringUtils.equals(pName, BouncyCastleProvider.PROVIDER_NAME)) {
            Security.addProvider(new BouncyCastleProvider());
        }
        this.decryptor.setProviderName(pName);
    }
    final String iter = getJasyptParamFromEnv(environment, JasyptEncryptionParameters.ITERATIONS);
    if (StringUtils.isNotBlank(iter) && NumberUtils.isCreatable(iter)) {
        LOGGER.debug("Configured decryptor iterations");
        decryptor.setKeyObtentionIterations(Integer.valueOf(iter));
    }
}
 
Example 7
Project: cas-5.1.0   File: Beans.java   View Source Code Vote up 5 votes
/**
 * New duration. If the provided length is duration,
 * it will be parsed accordingly, or if it's a numeric value
 * it will be pared as a duration assuming it's provided as seconds.
 *
 * @param length the length in seconds.
 * @return the duration
 */
public static Duration newDuration(final String length) {
    try {
        if (NumberUtils.isCreatable(length)) {
            return Duration.ofSeconds(Long.valueOf(length));
        }
        return Duration.parse(length);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 8
Project: MoMuOSB   File: ChangeCommands.java   View Source Code Vote up 5 votes
/**
 * Change the Username of the Bot
 * @param event MessageEvent
 * @param args Argumente
 * @return state
 */
@Command(
        command = "changeprop",
        arguments = {"Option", "Value"},
        description = "Change the Property",
        alias = "chp",
        permission = Globals.BOT_OWNER,
        prefix = Globals.ADMIN_PREFIX
)
public boolean changeProperty(MessageReceivedEvent event, String[] args) {
        if (args[0].equalsIgnoreCase("NA") || args[1].equalsIgnoreCase("NA")) {
            BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.ERROR+ LANG.getTranslation("notchanged_error")), true);
        } else {
            if (!DRIVER.getPropertyOnly(DRIVER.CONFIG, args[0]).equals("No Value")) {
                Object value = args[1];
                boolean error = false;
                if (args[1].equalsIgnoreCase("false") || args[1].equalsIgnoreCase("true")) {
                    value = Boolean.valueOf(args[1]);
                }
                try {
                    if (NumberUtils.isCreatable(args[1])) {
                        value = NumberFormat.getInstance().parse(args[1]);
                    }

                } catch (Exception ex) {
                    BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.ERROR + LANG.getTranslation("parse_error")), true);
                    error = true;
                }
                if (!error) {
                    DRIVER.setProperty(DRIVER.CONFIG, args[0], value);
                    BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.SUCCESS+LANG.getTranslation("command_success")), true);
                }
                DRIVER.saveJson();
            } else {
                BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.ERROR+ LANG.getTranslation("changeprop_error")), true);
            }
        }
    return true;
}
 
Example 9
Project: EgTest   File: GroovyInjector.java   View Source Code Vote up 5 votes
/** Exposed for unit testing. */
static boolean plainJava(TypeKind kind, String text) {
    switch (kind) {
        case BOOLEAN: return "true".equals(text) || "false".equals(text);
        case BYTE:    return NumberUtils.isCreatable(text);  // Unfortunately doesn't handle "12_345".
        case CHAR:    return text.matches("'.'");            // e.g. 'a', '\t'; note that newline isn't a character
        case DOUBLE:  return NumberUtils.isCreatable(text);
        case FLOAT:   return NumberUtils.isCreatable(text);
        case INT:     return NumberUtils.isCreatable(text);
        case LONG:    return NumberUtils.isCreatable(text);
        case SHORT:   return NumberUtils.isCreatable(text);
        default:      return false;
    }
}
 
Example 10
Project: smockin   File: InboundParamMatchServiceImpl.java   View Source Code Vote up 4 votes
private int generateRandomforRange(final String range) {

        String arg = null;

        if (range.toUpperCase().contains(TO_ARG)) {
            arg = TO_ARG;
        } else if (range.toUpperCase().contains(UNTIL_ARG)) {
            arg = UNTIL_ARG;
        }

        if (arg == null) {
            throw new IllegalArgumentException("Expected '" + TO_ARG + "' or '" + UNTIL_ARG + "' arg in '" + ParamMatchTypeEnum.RANDOM_NUMBER.name() + "=' token");
        }

        final String[] rangeToArray = range.toUpperCase().split(arg);

        if (rangeToArray.length != 2) {
            throw new IllegalArgumentException("Missing number range for '" + arg + "' args. (i.e expect 1 " + arg + " 5)");
        }

        if (!NumberUtils.isCreatable(StringUtils.trim(rangeToArray[0]))
                || !NumberUtils.isCreatable(StringUtils.trim(rangeToArray[1]))) {
            throw new IllegalArgumentException("Range does not contain valid numbers. (i.e expect 1 " + arg + " 5)");
        }

        final int start = NumberUtils.toInt(StringUtils.trim(rangeToArray[0]));
        final int end = NumberUtils.toInt(StringUtils.trim(rangeToArray[1]));

        if (start >= 0 && end > 0) {

            return RandomUtils.nextInt(start, (arg.equals(TO_ARG))?(end+1):end);
        } else if (start <= 0 && end >= 0) {

            int s = -Math.abs(RandomUtils.nextInt(0, (arg.equals(TO_ARG))?(Math.abs(start)+1):Math.abs(start)));
            int e = RandomUtils.nextInt(0, (arg.equals(TO_ARG))?(end+1):end);

            return (e + s);
        } else if (start < 0 && end < 0) {

           return -Math.abs(RandomUtils.nextInt(Math.abs(end), (arg.equals(TO_ARG))?(Math.abs(start)+1):Math.abs(start)));
        }

        return 0;
    }
 
Example 11
Project: util   File: NumberUtil.java   View Source Code Vote up 4 votes
/**
 * 判断字符串是否合法数字
 */
public static boolean isNumber(String str) {
	return NumberUtils.isCreatable(str);
}
 
Example 12
Project: cas-5.1.0   File: LdapUtils.java   View Source Code Vote up 3 votes
/**
 * Reads a Long value from the LdapEntry.
 *
 * @param entry     the ldap entry
 * @param attribute the attribute name
 * @param nullValue the value which should be returning in case of a null value
 * @return the long value
 */
public static Long getLong(final LdapEntry entry, final String attribute, final Long nullValue) {
    final String v = getString(entry, attribute, nullValue.toString());
    if (v != null && NumberUtils.isCreatable(v)) {
        return Long.valueOf(v);
    }
    return nullValue;
}