Java Code Examples for org.apache.commons.lang3.math.NumberUtils

The following are top voted examples for showing how to use org.apache.commons.lang3.math.NumberUtils. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: take   File: XiCiProxyParser.java   View source code 6 votes vote down vote up
@Override
public List<Proxy> parse(String html) {
    Document document = Jsoup.parse(html);
    Elements elements = document.select("table[id=ip_list] tr[class]");
    List<Proxy> proxyList = new LinkedList<>();
    for (int i = 0; i < elements.size(); i++) {
        if (i == 0) {
            continue;
        }
        Element element = elements.get(i);
        String ip = element.select("td:eq(1)").first().text();
        String port  = element.select("td:eq(2)").first().text();
        String isAnonymous = element.select("td:eq(4)").first().text();
        Proxy p = new Proxy();
        p.setIp(ip);
        p.setPort(NumberUtils.toInt(port));
        p.setAnonymity(isAnonymous);
        proxyList.add(p);
    }
    return proxyList;
}
 
Example 2
Project: InComb   File: CategoryDao.java   View source code 6 votes vote down vote up
/**
 * Converts the given {@link DocumentsSearchResult} to a {@link ISearchResult} containing
 * the found {@link Category}s. It extracts all category ids from the {@link Document}s
 * and queries the database for them.
 * @param docsResult the {@link DocumentsSearchResult} to convert.
 * @return {@link ISearchResult} containing the {@link Category}s.
 */
private ISearchResult<Category> docsToCategories(final DocumentsSearchResult docsResult) {
	final List<Category> categories = new ArrayList<>();

	for (final Document doc : docsResult.getResults()) {
		final String categoryId = doc.get(IIndexElement.FIELD_ID);
		if(NumberUtils.isNumber(categoryId)) {
			categories.add(getCategory(Integer.parseInt(categoryId)));
		}
		else {
			LOGGER.error("Not numeric category id from index {}.", categoryId);
		}
	}

	return new SimpleSearchResult<>(categories, docsResult.getTotalHits());
}
 
Example 3
Project: InComb   File: ProviderDao.java   View source code 6 votes vote down vote up
/**
 * Builds {@link Provider}s for the given {@link Document}s.
 * @param docsResult the {@link Document}s to convert.
 * @return a new {@link ISearchResult} containing the {@link Provider}s and the
 * 			totalHits from the given {@link DocumentsSearchResult}.
 */
private ISearchResult<Provider> docsToProviders(final DocumentsSearchResult docsResult) {
	final List<Provider> providers = new ArrayList<>();

	for (final Document doc : docsResult.getResults()) {
		final String providerId = doc.get(IIndexElement.FIELD_ID);
		if(NumberUtils.isNumber(providerId)) {
			providers.add(getProvider(Integer.parseInt(providerId)));
		}
		else {
			LOGGER.error("Not numeric user id from index {}.", providerId);
		}
	}

	return new SimpleSearchResult<>(providers, docsResult.getTotalHits());
}
 
Example 4
Project: solo-spring   File: Requests.java   View source code 6 votes vote down vote up
/**
 * Gets the request page number from the specified path.
 *
 * @param path
 *            the specified path, see {@link #PAGINATION_PATH_PATTERN} for
 *            the details
 * @return page number, returns {@code 1} if the specified request URI can
 *         not convert to an number
 * @see #PAGINATION_PATH_PATTERN
 */
public static int getCurrentPageNum(final String path) {
	logger.trace("Getting current page number[path={}]", path);

	if (StringUtils.isBlank(path) || path.equals("/")) {
		return 1;
	}

	final String currentPageNumber = path.split("/")[0];

	if (!NumberUtils.isDigits(currentPageNumber)) {
		return 1;
	}

	return Integer.valueOf(currentPageNumber);
}
 
Example 5
Project: exam   File: ClozeTestAnswer.java   View source code 6 votes vote down vote up
private boolean isCorrectNumericAnswer(Element blank, Map<String, String> answers) {
    String key = blank.attr("id");
    if (!answers.containsKey(key) || answers.get(key) == null) {
        return false;
    }
    String answerText = answers.get(key);
    answerText = answerText.trim();
    if (!NumberUtils.isParsable(answerText)) {
        return false;
    }
    String precisionAttr = blank.attr("precision");
    Double answer = Double.parseDouble(answerText);
    Double correctAnswer = Double.parseDouble(blank.text().trim());
    Double precision = precisionAttr == null ? 0.0 : Double.parseDouble(precisionAttr);
    return correctAnswer - precision <= answer && answer <= correctAnswer + precision;
}
 
Example 6
Project: sumo   File: Ambiguity.java   View source code 6 votes vote down vote up
/**
 * 
 * @param boat
 * @param xPos
 * @param yPos
 * @param deltaAzimuth azimuth correction in pixels
 * @param pxSize
 * @param pySize
 * @return
 * @throws IOException
 */
protected boolean isAmbiguityMultipleBand(Boat boat,int xPos, int yPos,int deltaAzimuth,double pxSize ,double pySize) throws IOException{
	for(int i=0;i<band.length;i++){
 	Window winUp=Window.createWindowFromAzimuth(xPos, yPos, deltaAzimuth,pxSize ,pySize,true);
    // logger.info(new StringBuffer().append("\nSearch Window start from: ").append(winUp.x).append(" ").append(winUp.sizeY).append("  D Azimuth:").append(deltaAzimuth).toString());
     int maxVal=getWindowMaxPixelValue(winUp.x,winUp.y,winUp.sizeX,winUp.sizeY,band[i]);
     
     String bb=sumoImage.getBandName(band[i]);
     int boatMaxValue=NumberUtils.max(boat.getStatMap().getMaxValue(bb));
     if(maxVal>(boatMaxValue*AZIMUT_FACTOR)){
     	return true;
     }else{
     	Window winDown=Window.createWindowFromAzimuth(xPos, yPos, deltaAzimuth,pxSize ,pySize,false);
     	maxVal=getWindowMaxPixelValue(winDown.x,winDown.y,winDown.sizeX,winDown.sizeY,band[i]);
     	if(maxVal>(boatMaxValue*AZIMUT_FACTOR)){
         	return true;
     	}	
     }	
  
	}
	return false;
}
 
Example 7
Project: mafia   File: DsMasterConfig.java   View source code 6 votes vote down vote up
@Bean(name = ConfigConstant.NAME_DS_MASTER)
@Primary
@ConfigurationProperties(prefix = ConfigConstant.PREFIX_DS_MASTER)
public DataSource mafMasterDataSource() {
    logger.info("----- MAFIA master data source INIT -----");
    DruidDataSource ds = new DruidDataSource();
    try {
        ds.setFilters(env.getProperty("ds.filters"));
    } catch (SQLException e) {
        logger.warn("Data source set filters ERROR:", e);
    }
    ds.setMaxActive(NumberUtils.toInt(env.getProperty("ds.maxActive"), 90));
    ds.setInitialSize(NumberUtils.toInt(env.getProperty("ds.initialSize"), 10));
    ds.setMaxWait(NumberUtils.toInt(env.getProperty("ds.maxWait"), 60000));
    ds.setMinIdle(NumberUtils.toInt(env.getProperty("ds.minIdle"), 1));
    ds.setTimeBetweenEvictionRunsMillis(NumberUtils.toInt(env.getProperty("ds.timeBetweenEvictionRunsMillis"), 60000));
    ds.setMinEvictableIdleTimeMillis(NumberUtils.toInt(env.getProperty("ds.minEvictableIdleTimeMillis"), 300000));
    ds.setValidationQuery(env.getProperty("ds.validationQuery"));
    ds.setTestWhileIdle(BooleanUtils.toBoolean(env.getProperty("ds.testWhileIdle")));
    ds.setTestOnBorrow(BooleanUtils.toBoolean(env.getProperty("ds.testOnBorrow")));
    ds.setTestOnReturn(BooleanUtils.toBoolean(env.getProperty("ds.testOnReturn")));
    ds.setPoolPreparedStatements(BooleanUtils.toBoolean(env.getProperty("ds.poolPreparedStatements")));
    ds.setMaxOpenPreparedStatements(NumberUtils.toInt(env.getProperty("ds.maxOpenPreparedStatements"), 20));
    return ds;
}
 
Example 8
Project: plugin-password   File: PasswordResource.java   View source code 6 votes vote down vote up
/**
 * Reset password from a mail challenge :token + mail + user name.
 * 
 * @param request
 *            the user request.
 * @param uid
 *            the user UID.
 */
@POST
@Path("reset/{uid}")
@Consumes(MediaType.APPLICATION_JSON)
public void reset(final ResetPasswordByMailChallenge request, @PathParam("uid") final String uid) {
	// check token in database : Invalid token, or out-dated, or invalid
	// user ?
	final PasswordReset passwordReset = repository.findByLoginAndTokenAndDateAfter(uid, request.getToken(),
			DateTime.now().minusHours(NumberUtils.INTEGER_ONE).toDate());
	if (passwordReset == null) {
		throw new BusinessException(BusinessException.KEY_UNKNOW_ID);
	}

	// Check the user and update his/her password
	create(uid, request.getPassword(), false);

	// Remove password reset request since this token is no more valid
	repository.delete(passwordReset);
}
 
Example 9
Project: NGB-master   File: Utils.java   View source code 6 votes vote down vote up
/**
 * Parses a string, representing an array of integers (e.g. [1,2,3]) into an {@link Integer} array
 * @param arrayString an integer array string
 * @return an {@link Integer} array
 */
public static Integer[] parseIntArray(String arrayString) {
    String[] items = arrayString.replaceAll("\\[", "").replaceAll("\\]", "").split(",");

    Integer[] results = new Integer[items.length];

    for (int i = 0; i < items.length; i++) {
        String numberString = items[i].trim();
        if (NumberUtils.isNumber(numberString)) {
            results[i] = Integer.parseInt(numberString);
        } else {
            return null;
        }
    }

    return results;
}
 
Example 10
Project: NGB-master   File: Utils.java   View source code 6 votes vote down vote up
/**
 * Parses a string, representing an array of float numbers (e.g. [1.4,2.12,3.5]) into a {@link Float} array
 * @param arrayString a float array string
 * @return an {@link Float} array
 */
public static Float[] parseFloatArray(String arrayString) {
    String[] items = arrayString.replaceAll("\\[", "").replaceAll("\\]", "").split(",");

    Float[] results = new Float[items.length];

    for (int i = 0; i < items.length; i++) {
        String numberString = items[i].trim();
        if (NumberUtils.isNumber(numberString)) {
            results[i] = Float.parseFloat(numberString);
        } else {
            return null;
        }
    }

    return results;
}
 
Example 11
Project: smockin   File: RuleResolverImpl.java   View source code 6 votes vote down vote up
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 12
Project: alexa-utterance-generator   File: WeightedSegmentsFormatter.java   View source code 6 votes vote down vote up
public WeightedSegmentsFormatter(final String[] args) {
    if (args != null) {
        prependPriority = ArrayUtils.contains(args, "-pp") || ArrayUtils.contains(args, "-prependPriority");

        int index1 = ArrayUtils.indexOf(args, "-weight");
        if (index1 < args.length - 1) {
            final String weightString = args[index1 + 1];
            Validate.isTrue(NumberUtils.isParsable(weightString), "Please provide a numeric value for weight.");
            this.weight = Integer.parseInt(weightString);
        }

        int index2 = ArrayUtils.indexOf(args, "-separator");
        if (index2 < args.length - 1) {
            valueSeparator = args[index2 + 1];
        }
    }
}
 
Example 13
Project: alexa-utterance-generator   File: Resolver.java   View source code 6 votes vote down vote up
public static List<String> resolveSlotValue(final String placeHolderName) {
    final List<String> values = new ArrayList<>();

    Arrays.stream(placeHolderName.split("\\|")).forEach(value -> {
        final String[] ranges = value.split("-");
        if (ranges.length == 2 && NumberUtils.isParsable(ranges[0]) && NumberUtils.isParsable(ranges[1])) {
            final int r1 = Integer.parseInt(ranges[0]);
            final int r2 = Integer.parseInt(ranges[1]);
            final int min = Integer.min(r1, r2);
            final int max = Integer.max(r1, r2);

            for (Integer i = min; i <= max; i++) {
                values.add(i.toString());
            }
        } else {
            values.add(value);
        }
    });
    return values;
}
 
Example 14
Project: unitstack   File: ReceiveMessageResponder.java   View source code 6 votes vote down vote up
@Override
public MockResponse createResponse(MockRequest request) {
  int maxNumberOfMessages = NumberUtils
      .toInt(request.getBodyParameters().get("MaxNumberOfMessages"), DEFAULT_FETCH_SIZE);
  // int visibilityTimeout =
  // NumberUtils.toInt(request.getBodyParameters().get("VisibilityTimeout"),DEFAULT_VISIBILITY_TIMEOUT);
  String receiptHandle = UUID.randomUUID().toString();
  String queueName = extractQueueName(request);
  List<SqsMessage> messages = new ArrayList<>();

  if (request.getQueues().containsKey(queueName)) {
    AwsQueue queue = request.getQueues().get(queueName);
    messages = pollMaxMessages(maxNumberOfMessages, queue, receiptHandle);
  }
  String messageResponses =
      messages.stream().map(this::getMessageResponseXml).collect(Collectors.joining("\n"));
  return new MockResponse(request.utils().successBody(RECEIVE_MESSAGE_ACTION, messageResponses));
}
 
Example 15
Project: plugin-vm-vcloud   File: VCloudPluginResource.java   View source code 5 votes vote down vote up
/**
 * Build a described {@link Vm} bean from a XML VMRecord entry.
 */
private VCloudVm toVm(final Element record) {
	final VCloudVm result = new VCloudVm();
	result.setId(StringUtils.removeStart(record.getAttribute("id"), "urn:vcloud:vm:"));
	result.setName(record.getAttribute("name"));
	result.setOs(record.getAttribute("guestOs"));

	// Optional attributes
	result.setStorageProfileName(record.getAttribute("storageProfileName"));
	result.setStatus(EnumUtils.getEnum(VmStatus.class, record.getAttribute("status")));
	result.setCpu(NumberUtils.toInt(StringUtils.trimToNull(record.getAttribute("numberOfCpus"))));
	result.setBusy(Boolean.parseBoolean(ObjectUtils.defaultIfNull(StringUtils.trimToNull(record.getAttribute("isBusy")), "false")));
	result.setVApp(StringUtils.trimToNull(record.getAttribute("containerName")));
	result.setVAppId(StringUtils.trimToNull(StringUtils.removeStart(record.getAttribute("container"), "urn:vcloud:vapp:")));
	result.setRam(NumberUtils.toInt(StringUtils.trimToNull(record.getAttribute("memoryMB"))));
	result.setDeployed(
			Boolean.parseBoolean(ObjectUtils.defaultIfNull(StringUtils.trimToNull(record.getAttribute("isDeployed")), "false")));
	return result;
}
 
Example 16
Project: sipsoup   File: ToDoubleFunction.java   View source code 5 votes vote down vote up
@Override
public Object call(Element element, List<SyntaxNode> params) {
    Preconditions.checkArgument(params.size() > 0, getName() + " at last has one parameter");
    Object calc = params.get(0).calc(element);
    if (calc instanceof Double) {
        return calc;
    }
    if (calc == null) {
        return null;
    }

    if (params.size() > 1) {
        Object defaultValue = params.get(1).calc(element);

        Preconditions.checkArgument(defaultValue != null && defaultValue instanceof Double,
                getName() + " parameter 2 must to be a Double now is:" + defaultValue);
        return NumberUtils.toDouble(calc.toString(), (Double) defaultValue);
    }
    return NumberUtils.toDouble(calc.toString());
}
 
Example 17
Project: WurstSDK   File: CrashCommand.java   View source code 5 votes vote down vote up
@Override
public void call(String[] args) throws CmdException {
    if (args.length != 1)
        throw new CmdSyntaxError(this.getCmdName() + " " + this.getSyntax()[0]);

    if (!NumberUtils.isNumber(args[0])) {
        Chat.error("No number!");
        return;
    }
    int number = (int) (NumberUtils.createDouble(args[0]) * 1000);
    Chat.message("Trying to crash using " + args[0] + " packets...");
    for (int i = 0; i < number; i++) {
        Objects.requireNonNull(mc.getConnection()).sendPacketBypass(new CPacketAnimation());
    }
    Chat.message(ChatColor.DARK_BLUE + "Done!");
}
 
Example 18
Project: NGB-master   File: AbstractHTTPCommandHandler.java   View source code 5 votes vote down vote up
/**
 * Loads BiologicalDataItem file from NGB server by an input String.
 * If input String might be interpreted as a number, item will be loaded by BiologicalDataItemID.
 * If input String isn't a number, method interprets it as a file name and tries to find a file
 * with such a name in the NGB server.
 * @param strId input String for file identification
 * @return BiologicalDataItem representing file
 * @throws ApplicationException if method fails to find a file
 */
protected BiologicalDataItem loadFileByNameOrBioID(String strId) {
    if (NumberUtils.isDigits(strId)) {
        return loadFileByBioID(strId);
    } else {
        List<BiologicalDataItem> items = loadItemsByName(strId);
        if (items == null || items.isEmpty()) {
            throw new ApplicationException(getMessage(ERROR_FILE_NOT_FOUND, strId));
        }
        if (items.size() > 1) {
            LOGGER.error(getMessage(SEVERAL_RESULTS_FOR_QUERY, strId));
        }
        return items.get(0);
    }
}
 
Example 19
Project: pnc-repressurized   File: BlockHeatSensor.java   View source code 5 votes vote down vote up
@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 20
Project: pnc-repressurized   File: ProgWidgetEmitRedstone.java   View source code 5 votes vote down vote up
@Override
public int getEmittingRedstone() {
    if (getConnectedParameters()[0] != null) {
        return NumberUtils.toInt(((ProgWidgetString) getConnectedParameters()[0]).string);
    } else {
        return 0;
    }
}
 
Example 21
Project: vscrawler   File: BerkeleyDBSeedManager.java   View source code 5 votes vote down vote up
private BloomFilter<Seed> getOrCreate(String segment) {
    BloomFilter<Seed> seedBloomFilter = bloomFilters.get(segment);
    if (seedBloomFilter != null) {
        return seedBloomFilter;
    }
    synchronized (segment.intern()) {
        seedBloomFilter = bloomFilters.get(segment);
        if (seedBloomFilter != null) {
            return seedBloomFilter;
        }

        long expectedNumber = NumberUtils.toLong(VSCrawlerContext.vsCrawlerConfigFileWatcher.loadedProperties()
                .getProperty(VSCrawlerConstant.VSCRAWLER_SEED_MANAGER_EXPECTED_SEED_NUMBER), 1000000L);

        // any way, build a filter instance if not exist
        seedBloomFilter = BloomFilter.create(new Funnel<Seed>() {
            @Override
            public void funnel(Seed from, PrimitiveSink into) {
                into.putString(seedKeyResolver.resolveSeedKey(from), Charset.defaultCharset());
            }
        }, expectedNumber);

        bloomFilters.put(segment, seedBloomFilter);
    }
    return seedBloomFilter;
}
 
Example 22
Project: take   File: IP181ProxyParser.java   View source code 5 votes vote down vote up
@Override
public List<Proxy> parse(String html) {
    Document document = Jsoup.parse(html);
    Elements elements = document.select("table > tbody > tr");
    List<Proxy> proxyList = new LinkedList<>();
    for (int i = 0; i < elements.size(); i++) {
        if (i == 0) {
            continue;
        }
        Element element = elements.get(i);
        Elements tds = element.getElementsByTag("td");
        Proxy proxy = new Proxy();
        proxyList.add(proxy);
        proxy.setIp(tds.get(0).ownText());
        proxy.setPort(NumberUtils.toInt(tds.get(1).ownText()));
        proxy.setAnonymity(tds.get(2).ownText());
        proxy.setProtocol(tds.get(3).ownText());
        proxy.setSpeed(tds.get(4).ownText());
        proxy.setSource(tds.get(5).ownText());
        Pattern compile = Pattern.compile("(\\d+)分钟");
        Matcher matcher = compile.matcher(tds.get(6).ownText());
        if (matcher.find()) {
            String group = matcher.group(1);
            DateTime time = DateTime.now().minusMinutes(NumberUtils.toInt(group));
            proxy.setUpdateTime(time.toDate());
        }
    }
    return proxyList;
}
 
Example 23
Project: ClientAPI   File: NumberParser.java   View source code 5 votes vote down vote up
@Override
public final Number parse(ExecutionContext context, Type type, String raw) {
    if (NumberUtils.isCreatable(raw)) {
        return NumberUtils.createNumber(raw);
    }
    return null;
}
 
Example 24
Project: file-format-streaming-converter   File: DateCellDataHandler.java   View source code 5 votes vote down vote up
@Override
public String handleCell(StreamingCell cell) {
    String rawContents = (String) cell.getRawContents();
    if (NumberUtils.isNumber(rawContents)) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date dateCellValue = cell.getDateCellValue();
            return dateFormat.format(dateCellValue);
        } catch (Exception e) {
            logger.warn("Tried to convert date " + rawContents + "but failed. skipping conversion");
        }
    }
    return rawContents;
}
 
Example 25
Project: xxpay-master   File: PayChannelController.java   View source code 5 votes vote down vote up
@RequestMapping("/edit.html")
public String editInput(String id, ModelMap model) {
    PayChannel item = null;
    if(StringUtils.isNotBlank(id) && NumberUtils.isNumber(id)) {
        item = payChannelService.selectPayChannel(Integer.parseInt(id));
    }
    if(item == null) item = new PayChannel();
    model.put("item", item);
    return "pay_channel/edit";
}
 
Example 26
Project: para-search-elasticsearch   File: ElasticSearchUtils.java   View source code 5 votes vote down vote up
/**
 * @param from from value
 * @param to to value
 * @return either "properties.vn" if one of the range limits is a number, or "properties.v" otherwise.
 */
static String getValueFieldNameFromRange(String from, String to) {
	if (("*".equals(from) && "*".equals(to)) || NumberUtils.isDigits(from) || NumberUtils.isDigits(to)) {
		return PROPS_PREFIX + "vn";
	}
	return PROPS_PREFIX + "v";
}
 
Example 27
Project: AEM   File: AssetProviderServlet.java   View source code 5 votes vote down vote up
@Activate
protected void activate(final ComponentContext context) {
    String maxDimensionsValue = getProperty(MAX_DIMENSIONS_PN, context);
    String[] maxDimensionsArray = maxDimensionsValue.split("x");
    if (maxDimensionsArray.length == 2) {
        maxHeight = NumberUtils.toInt(maxDimensionsArray[0], maxHeight);
        maxWidth = NumberUtils.toInt(maxDimensionsArray[1], maxWidth);
    }
}
 
Example 28
Project: cas-5.1.0   File: GoogleAuthenticatorAuthenticationHandler.java   View source code 5 votes vote down vote up
@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 29
Project: cas-5.1.0   File: OidcAuthorizationRequestSupport.java   View source code 5 votes vote down vote up
/**
 * Gets oidc max age from authorization request.
 *
 * @param context the context
 * @return the oidc max age from authorization request
 */
public static Optional<Long> getOidcMaxAgeFromAuthorizationRequest(final WebContext context) {
    final URIBuilder builderContext = new URIBuilder(context.getFullRequestURL());
    final Optional<URIBuilder.BasicNameValuePair> parameter = builderContext.getQueryParams()
            .stream().filter(p -> OidcConstants.MAX_AGE.equals(p.getName()))
            .findFirst();

    if (parameter.isPresent()) {
        final long maxAge = NumberUtils.toLong(parameter.get().getValue(), -1);
        return Optional.of(maxAge);
    }
    return Optional.empty();
}
 
Example 30
Project: cas-5.1.0   File: BaseWSFederationRequestController.java   View source code 5 votes vote down vote up
/**
 * 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 31
Project: cas-5.1.0   File: CasConfigurationJasyptDecryptor.java   View source code 5 votes vote down vote up
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 32
Project: cas-5.1.0   File: Beans.java   View source code 5 votes vote down vote up
/**
 * 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 33
Project: solo-spring   File: PermalinkQueryService.java   View source code 5 votes vote down vote up
/**
 * Checks whether the specified user-defined permalink is invalid on format.
 * 
 * @param permalink
 *            the specified user-defined permalink
 * @return {@code true} if invalid, returns {@code false} otherwise
 */
private static boolean invalidUserDefinedPermalinkFormat(final String permalink) {
	if (StringUtils.isBlank(permalink)) {
		return true;
	}

	if (isReservedLink(permalink)) {
		return true;
	}
	if (NumberUtils.isDigits(permalink.substring(1))) {
		// See issue 120
		// (http://code.google.com/p/b3log-solo/issues/detail?id=120#c4) for
		// more details
		return true;
	}

	int slashCnt = 0;

	for (int i = 0; i < permalink.length(); i++) {
		if ('/' == permalink.charAt(i)) {
			slashCnt++;
		}

		if (slashCnt > 1) {
			return true;
		}
	}

	return !UrlValidator.getInstance().isValid(Latkes.getServer() + permalink);
}
 
Example 34
Project: webdriver-supplier   File: StringUtils.java   View source code 5 votes vote down vote up
public static Optional<Dimension> toDimention(final String value) {
    return ofNullable(value)
            .map(val -> StreamEx.of(val.split("x"))
                                .filter(NumberUtils::isDigits)
                                .mapToInt(Integer::parseInt)
                                .toArray())
            .filter(val -> val.length >= 2)
            .map(val -> new Dimension(val[0], val[1]));
}
 
Example 35
Project: private-WeChat   File: ChineseUtil.java   View source code 5 votes vote down vote up
/**
 * 功能描述: 返回中文字个数<br>
 * .
 * 
 * @param chinese the chinese
 * @return the int
 */
public static int countChinese(String chinese) {
    if (StringUtils.isBlank(chinese)) {
        return NumberUtils.INTEGER_ZERO;
    }
    int count = NumberUtils.INTEGER_ZERO;
    String regEx = "[\\u4e00-\\u9fa5]";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(chinese);
    while (m.find()) {
            count++;
    }
    return count;
}
 
Example 36
Project: pay-xxpay-master   File: PayChannelController.java   View source code 5 votes vote down vote up
@RequestMapping("/edit.html")
public String editInput(String id, ModelMap model) {
    PayChannel item = null;
    if(StringUtils.isNotBlank(id) && NumberUtils.isNumber(id)) {
        item = payChannelService.selectPayChannel(Integer.parseInt(id));
    }
    if(item == null) item = new PayChannel();
    model.put("item", item);
    return "pay_channel/edit";
}
 
Example 37
Project: gitplex-mit   File: GitVersion.java   View source code 5 votes vote down vote up
public GitVersion(String versionStr) {
	for (String each: LoaderUtils.splitAndTrim(versionStr, ".")) {
		if (NumberUtils.isDigits(each))
			parts.add(Integer.valueOf(each));
		else if (each.equals("msysgit"))
			msysgit = true;
	}
}
 
Example 38
Project: NGB-master   File: UrlGeneratorHandler.java   View source code 5 votes vote down vote up
@Override
public void parseAndVerifyArguments(List<String> arguments, ApplicationOptions options) {
    if (CollectionUtils.isEmpty(arguments)) {
        throw new IllegalArgumentException(MessageConstants
                .getMessage(MINIMUM_COMMAND_ARGUMENTS, getCommand(), 1, arguments.size()));
    }

    dataset = arguments.get(0);
    ids = arguments.subList(1, arguments.size());

    printJson = options.isPrintJson();
    printTable = options.isPrintTable();

    String location = options.getLocation();
    if (StringUtils.isNoneBlank(location)) {
        String[] parts = location.split(":");
        chrName = parts[0];

        if (parts.length > 1 && parts[1].contains("-")) {
            String[] subParts = parts[1].split("-");
            if (NumberUtils.isDigits(subParts[0])) {
                startIndex = Integer.parseInt(subParts[0]);
            }
            if (NumberUtils.isDigits(subParts[1])) {
                endIndex = Integer.parseInt(subParts[1]);
            }
        }
    }
}
 
Example 39
Project: NGB-master   File: NggbBedCodec.java   View source code 5 votes vote down vote up
private void parseAndSetColour(String[] tokens, int tokenCount, NggbSimpleBedFeature feature) {
    if (tokenCount > COLOUR_OFFSET) {
        String colorString = tokens[COLOUR_OFFSET];
        feature.setColor(ParsingUtils.parseColor(colorString));
        // ThickStart and ThickEnd
        if (NumberUtils.isNumber(tokens[THICK_START_OFFSET])
                && NumberUtils.isNumber(tokens[THICK_END_OFFSET])) {
            feature.setThickStart(Integer.parseInt(tokens[THICK_START_OFFSET]));
            feature.setThickEnd(Integer.parseInt(tokens[THICK_END_OFFSET]));
        }
    }
}
 
Example 40
Project: Open_Source_ECOA_Toolset_AS5   File: DeployedModuleInstanceNode.java   View source code 5 votes vote down vote up
@Override
public ArrayList<String> validate() {
	ArrayList<String> ret = new ArrayList<>();
	if (compName == null || compName.equalsIgnoreCase("null") || compName.trim().length() == 0)
		ret.add("Computing Platform Name Cannot be empty");
	if (moduleName == null || moduleName.equalsIgnoreCase("null") || moduleName.trim().length() == 0)
		ret.add("Module Instance Name Cannot be empty");
	if (priority == null || priority.equalsIgnoreCase("null") || priority.trim().length() == 0 || (!NumberUtils.isNumber(priority)))
		ret.add("Priority Cannot be empty or a Non-numeric value");
	return ret;
}