Example usage for org.apache.commons.lang3 StringUtils isNumeric

List of usage examples for org.apache.commons.lang3 StringUtils isNumeric

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils isNumeric.

Prototype

public static boolean isNumeric(final CharSequence cs) 

Source Link

Document

Checks if the CharSequence contains only Unicode digits.

Usage

From source file:com.glaf.base.online.job.ClearOnlineUserJob.java

public void runJob(JobExecutionContext context) throws JobExecutionException {
    String jobName = context.getJobDetail().getKey().getName();
    logger.info("Executing job: " + jobName + " executing at " + DateUtils.getDateTime(new Date()));
    int timeoutSeconds = 300;
    UserOnlineService userOnlineService = ContextFactory.getBean("userOnlineService");
    ISystemPropertyService systemPropertyService = ContextFactory.getBean("systemPropertyService");
    SystemProperty p = systemPropertyService.getSystemProperty("SYS", "login_time_check");
    if (p != null && p.getValue() != null && StringUtils.isNumeric(p.getValue())) {
        timeoutSeconds = Integer.parseInt(p.getValue());
    }//www  . j a  v a 2 s.  co  m
    if (timeoutSeconds < 60) {
        timeoutSeconds = 60;
    }
    if (timeoutSeconds > 1800) {
        timeoutSeconds = 1800;
    }
    userOnlineService.deleteTimeoutUsers(timeoutSeconds);
}

From source file:com.inkubator.hrm.web.payroll.UnregCalculationTaxDetailController.java

@PostConstruct
@Override/*from   w  ww.  j a v a  2 s .c o m*/
public void initialization() {
    super.initialization();
    String unregSalaryId = FacesUtil.getRequestParameter("execution").substring(1);
    String taxComponentId = FacesUtil.getRequestParameter("comp").substring(1);
    parameter = new UnregPayrollEmpPajakSearchParameter();
    if (StringUtils.isNumeric(unregSalaryId) && StringUtils.isNumeric(taxComponentId)) {
        try {
            taxComponent = taxComponentService.getEntiyByPK(Long.parseLong(taxComponentId));
            unregSalary = unregSalaryService.getEntiyByPK(Long.parseLong(unregSalaryId));
            parameter.setTaxComponentId(taxComponent.getId());
            parameter.setUnregSalaryId(unregSalary.getId());
            parameter.setKeyParam("nikOrName");
        } catch (Exception ex) {
            LOGGER.error("Error", ex);
        }
    }
}

From source file:fredboat.command.music.control.SkipCommand.java

@Override
public void onInvoke(Guild guild, TextChannel channel, Member invoker, Message message, String[] args) {
    GuildPlayer player = PlayerRegistry.get(guild);
    player.setCurrentTC(channel);/*from   w w  w .j  a v  a2  s.  co m*/
    if (player.isQueueEmpty()) {
        channel.sendMessage("The queue is empty!").queue();
    }

    if (args.length == 1) {
        skipNext(guild, channel, invoker, message, args);
    } else if (args.length == 2 && StringUtils.isNumeric(args[1])) {
        int givenIndex = Integer.parseInt(args[1]);

        if (givenIndex == 1) {
            skipNext(guild, channel, invoker, message, args);
            return;
        }

        if (player.getRemainingTracks().size() < givenIndex) {
            channel.sendMessage("Can't remove track number " + givenIndex + " when there are only "
                    + player.getRemainingTracks().size() + " tracks.").queue();
            return;
        } else if (givenIndex < 1) {
            channel.sendMessage("Given number must be greater than 0.").queue();
            return;
        }

        AudioTrackContext atc = player.getAudioTrackProvider().removeAt(givenIndex - 2);
        channel.sendMessage("Skipped track #" + givenIndex + ": **" + atc.getTrack().getInfo().title + "**")
                .queue();
    } else {
        channel.sendMessage("Incorrect number of arguments. Proper usage: ```\n;;skip\n;;skip <index>```")
                .queue();
    }
}

From source file:ch.jamiete.hilda.music.commands.MusicQueueCommand.java

@Override
public final void execute(final Message message, final String[] args, final String label) {
    final MusicServer server = this.manager.getServer(message.getGuild());

    if (server == null) {
        this.reply(message, "There isn't anything playing.");
        return;//w w  w  .j  a  v  a 2s . com
    }

    int page = 0;
    final int pageSize = 15;
    int queue_code = 0;

    if (args.length == 1) {
        if (StringUtils.isNumeric(args[0])) {
            page = Integer.valueOf(args[0]) - 1;
            queue_code = page * pageSize;
        } else {
            this.usage(message, "[page]", label);
            return;
        }
    }

    final List<QueueItem> queue = server.getQueue();

    if (queue.isEmpty()) {
        this.reply(message, "There isn't anything queued.");
        return;
    }

    final List<QueueItem> tracks = MusicQueueCommand.getPage(queue, page, pageSize);
    final MessageBuilder sb = new MessageBuilder();

    if (tracks.isEmpty()) {
        this.reply(message, "That page is empty.");
    } else {
        sb.append("There ").append((queue.size() == 1) ? "is" : "are").append(" ");
        sb.append(queue.size()).append(" ").append((queue.size() == 1) ? "track" : "tracks");
        sb.append(" queued for ").append(Util.getFriendlyTime(server.getDuration()));

        if (tracks.size() != queue.size()) {
            sb.append("; showing tracks ");

            if (page == 0) {
                sb.append("1").append(pageSize);
            } else {
                final int first = (page * pageSize) + 1;
                sb.append(first).append("").append(Math.min((first + pageSize) - 1, queue.size()));
            }
        }

        sb.append(":").append("\n\n");

        for (final QueueItem track : tracks) {
            sb.append("[" + ++queue_code + ']', Formatting.BLOCK).append(" ");

            sb.append(Util.sanitise(MusicManager.getFriendly(track.getTrack())));

            final String time = MusicManager.getFriendlyTime(track.getTrack());
            if (!time.trim().isEmpty()) {
                sb.append(" (").append(time).append(")");
            }

            Member requestor = message.getGuild().getMemberById(track.getUserId());
            sb.append(" ").append(requestor == null ? "User left server" : requestor.getEffectiveName(),
                    Formatting.BLOCK);

            sb.append("\n");
        }

        if (tracks.size() != queue.size()) {
            sb.append("\n");
            sb.append("End of page ").append(page + 1).append("/")
                    .append((int) Math.ceil((double) queue.size() / (double) pageSize)).append(".");
        }

        sb.buildAll(SplitPolicy.NEWLINE).forEach(m -> this.reply(message, m));
    }
}

From source file:com.victz.mvc.PostsController.java

@GET
@Path("{path:.*}")
@View("posts.jsp")
public void get(@PathParam("path") String path) {
    Map<String, String> params = parsePath(path);
    String category = params.get("category");
    if (category != null && !category.isEmpty()) {
        postsModel.setCategoryId(category);
    }//ww  w . jav  a 2s  .co m

    String tag = params.get("tag");
    if (tag != null && !tag.isEmpty()) {
        postsModel.setTagId(tag);
    }
    String page = params.get("page");
    if (StringUtils.isNumeric(page)) {
        int pageNo = Integer.parseInt(page);
        if (pageNo > 0) {
            postsModel.setPageNo(pageNo);
        }
    }
}

From source file:com.inkubator.hrm.web.payroll.UnregCalculationDetailController.java

@PostConstruct
@Override/*from w  w  w  . j a v  a 2 s.co m*/
public void initialization() {
    super.initialization();
    String unregSalaryId = FacesUtil.getRequestParameter("execution").substring(1);
    String taxComponentId = FacesUtil.getRequestParameter("comp").substring(1);
    parameter = new UnregCalculationSearchParameter();
    if (StringUtils.isNumeric(unregSalaryId) && StringUtils.isNumeric(taxComponentId)) {
        try {
            paySalaryComponent = paySalaryComponentService.getEntiyByPK(Long.parseLong(taxComponentId));
            unregSalary = unregSalaryService.getEntiyByPK(Long.parseLong(unregSalaryId));
            parameter.setPaySalaryComponentId(paySalaryComponent.getId());
            parameter.setUnregSalaryId(unregSalary.getId());
            parameter.setKeyParam("nikOrName");

            totalEmployee = tempUnregPayrollService.getTotalEmployeeByUnregSalaryIdAndPaySalaryCompId(
                    unregSalary.getId(), paySalaryComponent.getId());
            totalNominal = tempUnregPayrollService.getTotalNominalByUnregSalaryIdAndPaySalaryCompId(
                    unregSalary.getId(), paySalaryComponent.getId());
        } catch (Exception ex) {
            LOGGER.error("Error", ex);
        }
    }
}

From source file:com.cognifide.aet.job.common.modifiers.WebElementsLocatorParams.java

private void initializeTimeOutParam(String timeoutString) throws ParametersException {
    if (StringUtils.isNotBlank(timeoutString)) {
        if (!StringUtils.isNumeric(timeoutString)) {
            throw new ParametersException("Parameter 'timeout' on Click Modifier isn't a numeric value.");
        }//w  w w .  j a va2s .  c om
        timeoutInSeconds = TimeUnit.SECONDS.convert(Long.valueOf(timeoutString), TimeUnit.MILLISECONDS);
        if (timeoutInSeconds < 0) {
            throw new ParametersException("'timeout' parameter value should be greater or equal zero.");
        } else if (TIMEOUT_SECONDS_MAX_VALUE < timeoutInSeconds) {
            throw new ParametersException("'timeout' parameter value can't be greater than "
                    + Long.toString(TIMEOUT_SECONDS_MAX_VALUE) + " seconds.");
        }
    }
}

From source file:com.thoughtworks.go.server.service.RestfulService.java

/**
 * buildId should only be given when caller is absolutely sure about the job instance
 * (makes sense in agent-uploading artifacts/properties scenario because agent won't run a job if its copied over(it only executes real jobs)) -JJ
 * <p>//from   w  w w  . j  a va  2s  . c  o  m
 * This does not return pipelineLabel
 */
public JobIdentifier findJob(String pipelineName, String pipelineCounter, String stageName, String stageCounter,
        String buildName, Long buildId) {
    JobConfigIdentifier jobConfigIdentifier = goConfigService
            .translateToActualCase(new JobConfigIdentifier(pipelineName, stageName, buildName));

    PipelineIdentifier pipelineIdentifier;

    if (JobIdentifier.LATEST.equalsIgnoreCase(pipelineCounter)) {
        pipelineIdentifier = pipelineService
                .mostRecentPipelineIdentifier(jobConfigIdentifier.getPipelineName());
    } else if (StringUtils.isNumeric(pipelineCounter)) {
        pipelineIdentifier = pipelineService
                .findPipelineByNameAndCounter(pipelineName, Integer.parseInt(pipelineCounter)).getIdentifier();
    } else {
        throw new RuntimeException("Expected numeric pipeline counter but received '%s'" + pipelineCounter);
    }

    stageCounter = StringUtils.isEmpty(stageCounter) ? JobIdentifier.LATEST : stageCounter;
    StageIdentifier stageIdentifier = translateStageCounter(pipelineIdentifier,
            jobConfigIdentifier.getStageName(), stageCounter);

    JobIdentifier jobId;
    if (buildId == null) {
        jobId = jobResolverService
                .actualJobIdentifier(new JobIdentifier(stageIdentifier, jobConfigIdentifier.getJobName()));
    } else {
        jobId = new JobIdentifier(stageIdentifier, jobConfigIdentifier.getJobName(), buildId);
    }
    if (jobId == null) {
        //fix for #5739
        throw new RecordNotFoundException(String.format("Job '%s' not found in pipeline '%s' stage '%s'",
                buildName, pipelineName, stageName));
    }
    return jobId;
}

From source file:fredboat.command.music.control.SelectCommand.java

static void select(CommandContext context) {
    Member invoker = context.invoker;
    GuildPlayer player = PlayerRegistry.getOrCreate(context.guild);
    VideoSelection selection = VideoSelection.get(invoker);
    if (selection == null) {
        context.reply(context.i18n("selectSelectionNotGiven"));
        return;/*from  w ww. ja v  a2 s .  c o  m*/
    }

    try {
        //Step 1: Parse the issued command for numbers

        // LinkedHashSet to handle order of choices + duplicates
        LinkedHashSet<Integer> requestChoices = new LinkedHashSet<>();

        // Combine all args and the command trigger. if the trigger is not a number it will be sanitized away
        String commandOptions = (context.trigger + " " + context.rawArgs).trim();
        String sanitizedQuery = sanitizeQueryForMultiSelect(commandOptions).trim();

        if (StringUtils.isNumeric(commandOptions)) {
            requestChoices.add(Integer.valueOf(commandOptions));
        } else if (TextUtils.isSplitSelect(sanitizedQuery)) {
            // Remove all non comma or number characters
            String[] querySplit = sanitizedQuery.split(",|\\s");

            for (String value : querySplit) {
                if (StringUtils.isNumeric(value)) {
                    requestChoices.add(Integer.valueOf(value));
                }
            }
        }

        //Step 2: Use only valid numbers (usually 1-5)

        ArrayList<Integer> validChoices = new ArrayList<>();
        // Only include valid values which are 1 to <size> of the offered selection
        for (Integer value : requestChoices) {
            if (1 <= value && value <= selection.choices.size()) {
                validChoices.add(value);
            }
        }

        //Step 3: Make a selection based on the order of the valid numbers

        // any valid choices at all?
        if (validChoices.isEmpty()) {
            throw new NumberFormatException();
        } else {
            AudioTrack[] selectedTracks = new AudioTrack[validChoices.size()];
            StringBuilder outputMsgBuilder = new StringBuilder();

            for (int i = 0; i < validChoices.size(); i++) {
                selectedTracks[i] = selection.choices.get(validChoices.get(i) - 1);

                String msg = context.i18nFormat("selectSuccess", validChoices.get(i),
                        selectedTracks[i].getInfo().title,
                        TextUtils.formatTime(selectedTracks[0].getInfo().length));
                if (i < validChoices.size()) {
                    outputMsgBuilder.append("\n");
                }
                outputMsgBuilder.append(msg);

                player.queue(new AudioTrackContext(selectedTracks[i], invoker));
            }

            VideoSelection.remove(invoker);
            TextChannel tc = FredBoat.getTextChannelById(selection.channelId);
            if (tc != null) {
                CentralMessaging.editMessage(tc, selection.outMsgId,
                        CentralMessaging.from(outputMsgBuilder.toString()));
            }

            player.setPause(false);
            context.deleteMessage();
        }
    } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
        context.reply(context.i18nFormat("selectInterval", selection.choices.size()));
    }
}

From source file:forge.ai.ability.AddTurnAi.java

@Override
protected boolean doTriggerAINoCost(Player ai, SpellAbility sa, boolean mandatory) {
    final Player opp = ai.getWeakestOpponent();

    if (sa.usesTargeting()) {
        sa.resetTargets();/*w w  w.j  a  v a2s .c o m*/
        if (sa.canTarget(ai)) {
            sa.getTargets().add(ai);
        } else if (mandatory) {
            for (final Player ally : ai.getAllies()) {
                if (sa.canTarget(ally)) {
                    sa.getTargets().add(ally);
                    break;
                }
            }
            if (!sa.getTargetRestrictions().isMinTargetsChosen(sa.getHostCard(), sa) && sa.canTarget(opp)) {
                sa.getTargets().add(opp);
            } else {
                return false;
            }
        }
    } else {
        final List<Player> tgtPlayers = AbilityUtils.getDefinedPlayers(sa.getHostCard(), sa.getParam("Defined"),
                sa);
        for (final Player p : tgtPlayers) {
            if (p.isOpponentOf(ai) && !mandatory) {
                return false;
            }
        }
        if (!StringUtils.isNumeric(sa.getParam("NumTurns"))) {
            // TODO: improve ai for Sage of Hours
            return false;
        }
        // not sure if the AI should be playing with cards that give the
        // Human more turns.
    }
    return true;
}