Example usage for java.lang Character isLetter

List of usage examples for java.lang Character isLetter

Introduction

In this page you can find the example usage for java.lang Character isLetter.

Prototype

public static boolean isLetter(int codePoint) 

Source Link

Document

Determines if the specified character (Unicode code point) is a letter.

Usage

From source file:eu.delving.sip.xml.SourceConverter.java

private boolean moreNumbersThanLetters(String string) {
    int letters = 0, numbers = 0;
    for (char c : string.toCharArray()) {
        if (Character.isLetter(c)) {
            letters++;/* w w  w .  j  ava 2s  .  co  m*/
        } else if (Character.isDigit(c)) {
            numbers++;
        }
    }
    return numbers > letters;
}

From source file:com.android.tools.lint.checks.StringFormatDetector.java

/**
 * Checks whether the text begins with a non-unit word, pointing to a string
 * that should probably be a plural instead. This
 *//*from  w  ww  .  j  a  v  a2 s .  c o  m*/
private static boolean checkPotentialPlural(XmlContext context, Element element, String text, int wordBegin) {
    // This method should only be called if the text is known to start with a word
    assert Character.isLetter(text.charAt(wordBegin));

    int wordEnd = wordBegin;
    while (wordEnd < text.length()) {
        if (!Character.isLetter(text.charAt(wordEnd))) {
            break;
        }
        wordEnd++;
    }

    // Eliminate units, since those are not sentences you need to use plurals for, e.g.
    //   "Elevation gain: %1$d m (%2$d ft)"
    // We'll determine whether something is a unit by looking for
    // (1) Multiple uppercase characters (e.g. KB, or MiB), or better yet, uppercase characters
    //     anywhere but as the first letter
    // (2) No vowels (e.g. ft)
    // (3) Adjacent consonants (e.g. ft); this one can eliminate some legitimate
    //     English words as well (e.g. "the") so we should really limit this to
    //     letter pairs that are not common in English. This is probably overkill
    //     so not handled yet. Instead we use a simpler heuristic:
    // (4) Very short "words" (1-2 letters)
    if (wordEnd - wordBegin <= 2) {
        // Very short word (1-2 chars): possible unit, e.g. "m", "ft", "kb", etc
        return false;
    }
    boolean hasVowel = false;
    for (int i = wordBegin; i < wordEnd; i++) {
        // Uppercase character anywhere but first character: probably a unit (e.g. KB)
        char c = text.charAt(i);
        if (i > wordBegin && Character.isUpperCase(c)) {
            return false;
        }
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y') {
            hasVowel = true;
        }
    }
    if (!hasVowel) {
        // No vowels: likely unit
        return false;
    }

    String word = text.substring(wordBegin, wordEnd);

    // Some other known abbreviations that we don't want to count:
    if (word.equals("min")) {
        return false;
    }

    // This heuristic only works in English!
    if (LintUtils.isEnglishResource(context, true)) {
        String message = String.format("Formatting %%d followed by words (\"%1$s\"): "
                + "This should probably be a plural rather than a string", word);
        context.report(POTENTIAL_PLURAL, element, context.getLocation(element), message);
        // Avoid reporting multiple errors on the same string
        // (if it contains more than one %d)
        return true;
    }

    return false;
}

From source file:org.onosproject.yang.compiler.utils.io.impl.YangIoUtils.java

/**
 * Applies the rule that a string does not end with a capitalized letter and capitalizes
 * the letter next to a number in an array.
 *
 * @param stringArray      containing strings for camel case separation
 * @param conflictResolver object of YANG to java naming conflict util
 * @return camel case rule checked string
 *///from  w  w  w.  java2 s. c o m
private static String applyCamelCaseRule(String[] stringArray, YangToJavaNamingConflictUtil conflictResolver) {

    String ruleChecker = stringArray[0].toLowerCase();
    int i;
    if (ruleChecker.matches(REGEX_FOR_FIRST_DIGIT)) {
        i = 0;
        ruleChecker = EMPTY_STRING;
    } else {
        i = 1;
    }
    for (; i < stringArray.length; i++) {
        if (i + 1 == stringArray.length) {
            if (stringArray[i].matches(REGEX_FOR_SINGLE_LETTER)
                    || stringArray[i].matches(REGEX_FOR_DIGITS_WITH_SINGLE_LETTER)) {
                ruleChecker = ruleChecker + stringArray[i].toLowerCase();
                break;
            }
        }
        if (stringArray[i].matches(REGEX_FOR_FIRST_DIGIT)) {
            for (int j = 0; j < stringArray[i].length(); j++) {
                char letterCheck = stringArray[i].charAt(j);
                if (Character.isLetter(letterCheck)) {
                    stringArray[i] = stringArray[i].substring(0, j)
                            + stringArray[i].substring(j, j + 1).toUpperCase()
                            + stringArray[i].substring(j + 1);
                    break;
                }
            }
            ruleChecker = ruleChecker + stringArray[i];
        } else {
            ruleChecker = ruleChecker + stringArray[i].substring(0, 1).toUpperCase()
                    + stringArray[i].substring(1);
        }
    }
    String ruleCheckerWithPrefix = addPrefix(ruleChecker, conflictResolver);
    return restrictConsecutiveCapitalCase(ruleCheckerWithPrefix);
}

From source file:TPPDekuBot.BattleBot.java

@Override
public void onMessage(Channel channel, User sender, String message) {
    append(sender.getNick() + ": " + message);
    if (sender.getNick().equalsIgnoreCase("the_chef1337")
            && message.toLowerCase().startsWith("!sendrawline ")) {
        String line = message.split(" ", 2)[1];
        this.sendRawLine(line);
        return;/*from   ww w.  ja  va2s  .com*/
    }
    //banlist goes here for simplicity
    if (sender.getNick().equalsIgnoreCase("trainertimmy")
            || sender.getNick().equalsIgnoreCase("trainertimmybot")
            || sender.getNick().equalsIgnoreCase("pikabowser2082")
            || sender.getNick().equalsIgnoreCase("wallbot303")) {
        return;
    }
    if (sender.getNick().equalsIgnoreCase("minhs2") || sender.getNick().equalsIgnoreCase("minhs3")) {
        return;
    }
    //end banlist
    //System.out.println(DekuBot.getDateTime() + " " + sender + ": " + message);
    while (Character.isWhitespace(message.charAt(0)) && message.length() > 2) {
        message = message.substring(1);
    }
    if (message.length() < 2) {
        return;
    }
    if (sender.getNick().equalsIgnoreCase("Minhs2") && message.toLowerCase().startsWith("!battle bigbrother")) {
        this.sendMessage(channel.getChannelName(), longMessage("FUNgineer"));
        return;
    }
    if ((message.toLowerCase().startsWith("!accept")) && (waitingPlayer || waitingPWT)
            && sender.getNick().equalsIgnoreCase(waitingOn)) {
        try {
            player.put(sender.getNick());
        } catch (Exception ex) {
        }
    }
    if ((message.toLowerCase().startsWith("!changeclass ") || message.toLowerCase().startsWith("!switchclass "))
            && !isInBattle()) {
        if (isForcedClass(sender.getNick())) {
            this.sendMessage(channel, "@" + sender.getNick() + " You cannot change your Trainer Class.");
            return;
        }
        String newClass = message.split(" ", 2)[1];
        if (newClass.length() > 19) {
            newClass = newClass.substring(0, 19);
        }
        if (newClass.isEmpty()) {
            this.sendMessage(channel.getChannelName(),
                    "@" + sender.getNick() + " Invalid Trainer Class FUNgineer");
            return;
        }
        while (Character.isWhitespace(newClass.charAt(0))) {
            newClass = newClass.substring(1);
        }
        while (newClass.contains("  ")) {
            newClass = newClass.replace("  ", " ");
            newClass = newClass.trim();
        }
        if (!isPureAscii(newClass)) {
            this.sendMessage(channel.getChannelName(),
                    "@" + sender.getNick() + " Invalid Trainer Class FUNgineer");
            return;
        }
        if (newClass.toLowerCase().contains("gym leader") || newClass.toLowerCase().contains("leader")
                || newClass.toLowerCase().contains("champion") || newClass.toLowerCase().contains("elite four")
                || (newClass.toLowerCase().charAt(0) == '/' || newClass.toLowerCase().charAt(0) == '.'
                        || !Character.isLetter(newClass.toLowerCase().charAt(0)))
                || containsBannedChar(newClass)) {
            this.sendMessage(channel.getChannelName(),
                    "@" + sender.getNick() + " Invalid Trainer Class FUNgineer");
            return;
        }
        //if (Trainer.isValidTrainerClass(newClass)) {
        HashMap<String, String> classes = new HashMap<>();
        try (FileInputStream f = new FileInputStream(BASE_PATH + "/trainerclasses.wdu");
                ObjectInputStream o = new ObjectInputStream(f)) {
            classes = (HashMap<String, String>) o.readObject();
        } catch (Exception ex) {
            System.err.println("[ERROR] Error reading classes file! " + ex);
            return;
        }
        classes.put(sender.getNick().toLowerCase(), newClass);
        try (FileOutputStream f = new FileOutputStream(BASE_PATH + "/trainerclasses.wdu");
                ObjectOutputStream o = new ObjectOutputStream(f)) {
            o.writeObject(classes);
        } catch (Exception ex) {
            System.err.println("[ERROR] Error writing new classes file! " + ex);
            return;
        }
        this.sendMessage(channel.getChannelName(),
                "@" + sender.getNick() + " updated your Trainer Class to " + newClass + "!");
        //} else {
        // this.sendMessage(channel.getChannelName(), "@" + sender + " Invalid Trainer Class. FUNgineer For a list of valid classes, go here: http://pastebin.com/raw.php?i=rhA55Dd0");
        //}
        return;
    }
    if (isInBattle() && battle instanceof MultiplayerBattle) {
        MultiplayerBattle mpB = (MultiplayerBattle) battle;
        if (message.toLowerCase().startsWith("!run") || (message.toLowerCase().startsWith("!switch")
                && message.length() >= 8 && Character.isDigit(message.charAt(7)))
                || Move.isValidMove(message)) {
            if (sender.getNick().equalsIgnoreCase(mpB.getPlayer1())) {
                try {
                    mpB.p1msg.put(message);
                } catch (Exception ex) {
                }
            }
            if (sender.getNick().equalsIgnoreCase(mpB.getPlayer2())) {
                try {
                    mpB.p2msg.put(message);
                } catch (Exception ex) {
                }
            }
        }
        if (message.toLowerCase().startsWith("!list")) {
            if (sender.getNick().equalsIgnoreCase(mpB.getPlayer1())) {
                try {
                    String pokemon = mpB.player1.getPokemonList();
                    this.sendMessage(channel.getChannelName(),
                            "/w " + sender.getNick() + " Your pokemon are: " + pokemon);
                } catch (Exception ex) {
                    this.sendMessage(channel.getChannelName(),
                            "/w " + sender.getNick() + " You have no other Pokemon in your party!");
                }
            } else if (sender.getNick().equalsIgnoreCase(mpB.getPlayer2())) {
                try {
                    String pokemon = mpB.player2.getPokemonList();
                    this.sendMessage(channel.getChannelName(),
                            "/w " + sender.getNick() + " Your pokemon are: " + pokemon);
                } catch (Exception ex) {
                    this.sendMessage(channel.getChannelName(),
                            "/w " + sender.getNick() + " You have no other Pokemon in your party!");
                }
            }
            return;
        }
        if (message.toLowerCase().startsWith("!check") && message.length() >= 7
                && Character.isDigit(message.charAt(6))) {
            int check = Integer.parseInt(message.charAt(6) + "");
            if (sender.getNick().equalsIgnoreCase(mpB.getPlayer1())) {
                Pokemon p = mpB.player1.getPokemon(check);
                this.sendMessage(channel.getChannelName(),
                        "/w " + sender.getNick() + " Status of " + p.getName() + " (" + p.getType1()
                                + ((p.getType2() != Type.NONE) ? "/" + p.getType2() : "") + "): "
                                + p.getStat(Stats.HP) + " out of " + p.getMaxHP() + "hp left. Has these moves: "
                                + p.getMove1().getName() + ", " + p.getMove2().getName() + ", "
                                + p.getMove3().getName() + ", " + p.getMove4().getName());
            } else if (sender.getNick().equalsIgnoreCase(mpB.getPlayer2())) {
                Pokemon p = mpB.player2.getPokemon(check);
                this.sendMessage(channel.getChannelName(),
                        "/w " + sender.getNick() + " Status of " + p.getName() + " (" + p.getType1()
                                + ((p.getType2() != Type.NONE) ? "/" + p.getType2() : "") + "): "
                                + p.getStat(Stats.HP) + " out of " + p.getMaxHP() + "hp left. Has these moves: "
                                + p.getMove1().getName() + ", " + p.getMove2().getName() + ", "
                                + p.getMove3().getName() + ", " + p.getMove4().getName());
            }
        }
        if (message.toLowerCase().startsWith("!help") && (isInBattle() && battle instanceof MultiplayerBattle)
                && (sender.getNick().equalsIgnoreCase(mpB.getPlayer1())
                        || sender.getNick().equalsIgnoreCase(mpB.getPlayer2()))) {
            this.sendMessage(channel.getChannelName(), "/w " + sender.getNick()
                    + " Type !list to see a list of your Pokemon. Type !checkx where x is the number of the Pokemon from !list to see it's moves. Type !switchx where x is number of the Pokemon from !list to switch to a Pokemon.");
        }
    }
    if (isInBattle() && battle instanceof PWTBattle) {
        PWTBattle mpB = (PWTBattle) battle;
        if (message.toLowerCase().startsWith("!run") || (message.toLowerCase().startsWith("!switch")
                && message.length() >= 8 && Character.isDigit(message.charAt(7)))
                || Move.isValidMove(message)) {
            if (sender.getNick().equalsIgnoreCase(mpB.player1.getTrainerName())) {
                try {
                    mpB.p1msg.put(message);
                } catch (Exception ex) {
                }
            }
            if (sender.getNick().equalsIgnoreCase(mpB.player2.getTrainerName())) {
                try {
                    mpB.p2msg.put(message);
                } catch (Exception ex) {
                }
            }
        }
        if (message.toLowerCase().startsWith("!list")) {
            if (sender.getNick().equalsIgnoreCase(mpB.player1.getTrainerName())) {
                try {
                    String pokemon = mpB.player1.getPokemonList();
                    this.sendMessage(channel.getChannelName(),
                            "/w " + sender.getNick() + " Your pokemon are: " + pokemon);
                } catch (Exception ex) {
                    this.sendMessage(channel.getChannelName(),
                            "/w " + sender.getNick() + " You have no other Pokemon in your party!");
                }
            } else if (sender.getNick().equalsIgnoreCase(mpB.player2.getTrainerName())) {
                try {
                    String pokemon = mpB.player2.getPokemonList();
                    this.sendMessage(channel.getChannelName(),
                            "/w " + sender.getNick() + " Your pokemon are: " + pokemon);
                } catch (Exception ex) {
                    this.sendMessage(channel.getChannelName(),
                            "/w " + sender.getNick() + " You have no other Pokemon in your party!");
                }
            }
            return;
        }
        if (message.toLowerCase().startsWith("!check") && message.length() >= 7
                && Character.isDigit(message.charAt(6))) {
            int check = Integer.parseInt(message.charAt(6) + "");
            if (sender.getNick().equalsIgnoreCase(mpB.player1.getTrainerName())) {
                Pokemon p = mpB.player1.getPokemon(check);
                this.sendMessage(channel.getChannelName(),
                        "/w " + sender.getNick() + " Status of " + p.getName() + " (" + p.getType1()
                                + ((p.getType2() != Type.NONE) ? "/" + p.getType2() : "") + "): "
                                + p.getStat(Stats.HP) + " out of " + p.getMaxHP() + "hp left. Has these moves: "
                                + p.getMove1().getName() + ", " + p.getMove2().getName() + ", "
                                + p.getMove3().getName() + ", " + p.getMove4().getName());
            } else if (sender.getNick().equalsIgnoreCase(mpB.player2.getTrainerName())) {
                Pokemon p = mpB.player2.getPokemon(check);
                this.sendMessage(channel.getChannelName(),
                        "/w " + sender.getNick() + " Status of " + p.getName() + " (" + p.getType1()
                                + ((p.getType2() != Type.NONE) ? "/" + p.getType2() : "") + "): "
                                + p.getStat(Stats.HP) + " out of " + p.getMaxHP() + "hp left. Has these moves: "
                                + p.getMove1().getName() + ", " + p.getMove2().getName() + ", "
                                + p.getMove3().getName() + ", " + p.getMove4().getName());
            }
        }
        if (message.toLowerCase().startsWith("!help") && (isInBattle() && battle instanceof PWTBattle)
                && (sender.getNick().equalsIgnoreCase(mpB.player1.getTrainerName()))
                || sender.getNick().equalsIgnoreCase(mpB.player2.getTrainerName())) {
            this.sendMessage(channel.getChannelName(), "/w " + sender.getNick()
                    + " Type !list to see a list of your Pokemon. Type !checkx where x is the number of the Pokemon from !list to see it's moves. Type !switchx where x is number of the Pokemon from !list to switch to a Pokemon.");
        }
    }
    if (isInBattle() && battle instanceof SafariBattle) {
        SafariBattle sB = (SafariBattle) battle;
        if (sender.getNick().equalsIgnoreCase(sB.user.getTrainerName())) {
            if (message.toLowerCase().startsWith("!rock") || message.toLowerCase().startsWith("!bait")
                    || message.toLowerCase().startsWith("!ball") || message.toLowerCase().startsWith("!run")) {
                if (this.getOutgoingQueueSize() == 0) {
                    sB.msg.add(message.split(" ", 2)[0].toLowerCase());
                }
            }
        }
    }
    if (!isInBattle() && !waitingPlayer && !waitingPWT) {
        if (message.startsWith("!safari")) {
            Thread t = new Thread(() -> {
                int level = new SecureRandom().nextInt(100 - 20 + 1) + 20;
                int id = new SecureRandom().nextInt(718 - 1 + 1) + 1;
                System.err.println("Attempting Pokemon ID " + id + " level " + level);
                SafariBattle sB = new SafariBattle(this, sender.getNick(), new Pokemon(id, level));
                battle = sB;
                sB.doBattle(this, channel.getChannelName());
                System.err.println("Now out of Safari Battle");
                battle = null;
            });
            t.start();
        }
    }
    if (!isInBattle() && !waitingPlayer && !waitingPWT) {
        if (message.startsWith("!pwt")) {
            this.sendMessage(channel, sender.getNick()
                    + " has started a new Random Pokemon World Tournament! Type !join to join. The PWT will start in 60 seconds.");
            //this.sendMessage(channel,"Debug mode for PWT activated, wait 60 sec");
            pwtQueue.add(sender.getNick().toLowerCase());
            music.play(new File(ROOT_PATH + "\\pwt\\pwt-lobby.mp3"));
            waitingPWT = true;
            Thread t = new Thread(() -> {
                try {
                    ArrayList<Trainer> randoms = new ArrayList<>();
                    Thread tet = new Thread(() -> {
                        outer: while (waitingPWT) {
                            Trainer rand = PWTournament.generateTrainer(PWTType.RANDOM, PWTClass.NORMAL);
                            if (randoms.isEmpty()) {
                                randoms.add(rand);
                                System.err.println("Added " + rand + " " + rand.getPokemon());
                                continue;
                            }
                            for (Trainer el : randoms) {
                                if (el.getTrainerName().equalsIgnoreCase(rand.getTrainerName())) {
                                    continue outer;
                                }
                            }
                            randoms.add(rand);
                            System.err.println("Added " + rand + " " + rand.getPokemon());
                        }
                    });
                    tet.start();
                    Thread.sleep(60000);
                    //                        while (randoms.size() < 7) {
                    //                            outer:
                    //                            while (waitingPWT) {
                    //                                Trainer rand = PWTournament.generateTrainer(PWTType.RANDOM, PWTClass.NORMAL);
                    //                                if (randoms.isEmpty()) {
                    //                                    randoms.add(rand);
                    //                                    System.err.println("Added " + rand + " " + rand.getPokemon());
                    //                                    continue;
                    //                                }
                    //                                for (Trainer el : randoms) {
                    //                                    if (el.getTrainerName().equalsIgnoreCase(rand.getTrainerName())) {
                    //                                        continue outer;
                    //                                    }
                    //                                }
                    //                                randoms.add(rand);
                    //                                System.err.println("Added " + rand + " " + rand.getPokemon());
                    //                            }
                    //                        }
                    waitingPWT = false;
                    inPWT = true;
                    this.sendMessage(channel, "The " + PWTType.RANDOM
                            + " Pokemon World Tournament is starting! Stand by while I generate Pokemon... the first match will begin soon!");
                    ArrayList<Trainer> pwtList = new ArrayList<>();
                    for (String el : pwtQueue) {
                        ArrayList<Pokemon> p = Trainer.generatePokemon(3, 50);
                        Trainer te = new Trainer(el, Trainer.getTrainerClass(el), Region.getRandomRegion(), p,
                                false);
                        pwtList.add(te);
                    }
                    Collections.shuffle(pwtList);
                    PWTournament pwt = new PWTournament(PWTType.RANDOM, PWTClass.NORMAL, pwtList, randoms);
                    pwt.arrangeBracket();
                    pwt.doTourney(this, channel.getChannelName());
                    pwtQueue = new ArrayList<>();
                    waitingPWT = false;
                    inPWT = false;
                } catch (Exception ex) {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    ex.printStackTrace(pw);
                    music.sendMessage(music.getChannel(), music.CHEF.mention()
                            + " ```An error occurred in the PWT!!\n" + sw.toString() + "```");
                    pwtQueue = new ArrayList<>();
                    waitingPWT = false;
                    inPWT = false;
                }
            });
            t.start();
        }
    }
    if (!isInBattle() && waitingPWT) {
        if (message.toLowerCase().startsWith("!join") && pwtQueue.size() < 4) {
            if (!pwtQueue.contains(sender.getNick().toLowerCase())) {
                pwtQueue.add(sender.getNick().toLowerCase());
                this.sendMessage(channel, sender.getNick() + " has been added to the PWT! Type !join to join.");
                return;
            }
        }
    }
    if (message.toLowerCase().startsWith("!help") && !isInBattle()) {
        this.sendMessage(channel.getChannelName(),
                "https://github.com/robomaeyhem/WowBattleBot (scroll down to see the Readme)");
    }
    if (message.toLowerCase().startsWith("!randbat @") || message.toLowerCase().startsWith("!randombattle @")) {
        if (isInBattle() || waitingPlayer || waitingPWT) {
            return;
        }
        //if ((message.toLowerCase().startsWith("!challenge @") || message.toLowerCase().startsWith("!multibattle @")) && !inMultiBattle && !inPokemonBattle && !inSafariBattle) {
        final String messageFinal = message;
        Thread t = new Thread(() -> {
            try {
                String target = messageFinal.split("@", 2)[1].split(" ", 2)[0];
                if (target.isEmpty() || target.contains("/") || target.contains(".")) {
                    this.sendMessage(channel, "FUNgineer");
                    return;
                }
                int pkmAmt = 1;
                try {
                    pkmAmt = Integer.parseInt(messageFinal.split("@", 2)[1].split(" ", 2)[1].split(" ", 2)[0]);
                } catch (Exception ex2) {
                    pkmAmt = 1;
                }
                if (pkmAmt < 1) {
                    pkmAmt = 1;
                }
                if (pkmAmt > 6) {
                    pkmAmt = 6;
                }
                if (target.equalsIgnoreCase(sender.getNick())) {
                    this.sendMessage(channel.getChannelName(), "You cannot challenge yourself FUNgineer");
                    return;
                }
                if (target.equalsIgnoreCase("frunky5") || target.equalsIgnoreCase("23forces")
                        || target.equalsIgnoreCase("groudonger")) {

                } else if (target.equalsIgnoreCase("wow_deku_onehand")
                        || target.equalsIgnoreCase("wow_battlebot_onehand") || User.isBot(target)
                        || target.equalsIgnoreCase("killermapper")) {
                    this.sendMessage(channel.getChannelName(), "FUNgineer");
                    return;
                }
                if (!waitingPlayer) {
                    waitingPlayer = true;
                    waitingOn = target;
                    this.sendMessage(channel.getChannelName(), "Challenging " + target + "...");
                    int level = new SecureRandom().nextInt(100 - 20 + 1) + 20;
                    while (level < 20) {
                        level = new SecureRandom().nextInt(100 - 20 + 1) + 20;
                    }
                    boolean isHere = false;
                    for (User el : this.getUsers(channel.getChannelName())) {
                        if (target.equalsIgnoreCase(el.getNick())) {
                            isHere = true;
                            break;
                        }
                    }
                    if (!isHere) {
                        append(sender.getNick() + " SENDING INVITE");
                        BattleBot.sendAnInvite(target, "_keredau_1423645868201", oAuth);
                    }
                    this.sendWhisper(target, "You have been challenged to a Pokemon Battle by "
                            + sender.getNick()
                            + "! To accept, go to the Battle Dungeon and type !accept. You have one minute.");
                    String player2 = player.poll(60, TimeUnit.SECONDS);
                    if (player2 == null) {
                        this.sendMessage(channel.getChannelName(),
                                target + " did not respond to the challenge BibleThump");
                        waitingPlayer = false;
                        waitingOn = "";
                        return;
                    }
                    waitingPlayer = false;
                    waitingOn = "";
                    this.sendMessage(channel.getChannelName(), "Generating Pokemon, give me a minute...");
                    System.err.println("Going into Multiplayer Battle");
                    MultiplayerBattle mpB = new MultiplayerBattle(this, sender.getNick(), target, level,
                            pkmAmt);
                    battle = mpB;
                    mpB.doBattle(channel.getChannelName());
                    battle = null;
                    System.err.println("Now out of Multiplayer Battle");
                }
            } catch (Exception ex) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                ex.printStackTrace(pw);
                music.sendMessage(music.getChannel(), music.CHEF.mention() + " ```" + sw.toString() + "\n```");
                waitingPlayer = false;
                battle = null;
            }
        });
        t.start();

    }
    if (message.toLowerCase().startsWith("!test ") && sender.getNick().equalsIgnoreCase("the_chef1337")) {
        String test = message.toLowerCase().split("!test ", 2)[1].split(" ", 2)[0];
        if (!test.equalsIgnoreCase("pwt") && !Character.isDigit(message.charAt(6))) {
            final String senderFinal = "the_chef1337";
            Thread t = new Thread(() -> {
                try {
                    pokemonMessages = new LinkedBlockingQueue<>();
                    personInBattle = senderFinal;
                    System.err.println("Going into Pokemon Battle");
                    PokemonBattle a = new PokemonBattle(this, channel.getChannelName(), false, false,
                            sender.getNick(), true);
                    System.err.println("Now out of Pokemon Battle");
                    pokemonMessages = new LinkedBlockingQueue<>();
                    personInBattle = "";
                    battle = null;
                } catch (Exception ex) {
                    personInBattle = "";
                    pokemonMessages = new LinkedBlockingQueue<>();
                    this.sendMessage(channel.getChannelName(),
                            "Something fucked up OneHand this battle is now over both Pokemon exploded violently KAPOW");
                    System.err.println("[POKEMON] Uh oh " + ex);
                    ex.printStackTrace();
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    ex.printStackTrace(pw);
                    music.sendMessage(music.getChannel(),
                            music.CHEF.mention() + " ```" + sw.toString() + "```");
                    battle = null;
                }
            });
            t.start();
        } else if (message.toLowerCase().split("!test ", 2)[1].split(" ", 2)[0].equalsIgnoreCase("pwt")) {
            Trainer t = new Trainer("Cynthia", "Sinnoh Champion", Region.SINNOH, Trainer.generatePokemon(3, 50),
                    true);
            Trainer m = new Trainer("23forces", "Elite Four", Region.getRandomRegion(),
                    Trainer.generatePokemon(3, 50), true);
            //String name, String trnClass, Region region, ArrayList<Pokemon> pokemon, boolean ai
            this.sendMessage(channel, PWTRound.FIRST_ROUND.getText() + "match of the " + PWTType.RANDOM
                    + " tournament! This match is between " + t + " and " + m + "!");
            PWTBattle b = new PWTBattle(this, m, t, PWTType.RANDOM, PWTClass.NORMAL, PWTRound.FIRST_ROUND);
            battle = b;
            Thread th = new Thread(() -> {
                try {
                    this.music.play(PWTBattle.determineMusic(b));
                    b.doBattle(channel.getChannelName());
                    battle = null;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
            th.start();
        } else {
            final int finalId = Integer.parseInt(message.split("!test ", 2)[1].split(" ", 2)[0]);
            Thread t = new Thread(() -> {
                int level = new SecureRandom().nextInt(100 - 20 + 1) + 20;
                int id = finalId;
                System.err.println("Attempting Pokemon ID " + id + " level " + level);
                SafariBattle sB = new SafariBattle(this, sender.getNick(), new Pokemon(id, level));
                battle = sB;
                sB.doBattle(this, channel.getChannelName());
                System.err.println("Now out of Safari Battle");
                battle = null;
            });
            t.start();
        }
    }
    if (message.toLowerCase().startsWith("!battle") && !waitingPlayer && !waitingPWT && !isInBattle()) {
        boolean bigbrother = false, fromChef = false;
        if (message.contains("BigBrother") || sender.getNick().equalsIgnoreCase("dewgong98")
                || sender.getNick().equalsIgnoreCase("mad_king98")
                || sender.getNick().equalsIgnoreCase("Starmiewaifu")) {
            bigbrother = true;
            if (sender.getNick().equalsIgnoreCase("the_chef1337")) {
                fromChef = true;
            }
        }
        final boolean bbrother = bigbrother;
        final boolean fChef = fromChef;
        if (sender.getNick().equalsIgnoreCase("twitchplaysleaderboard")) {
            return;
        } else {
            final String senderFinal = sender.getNick();
            if (!isInBattle() && !waitingPlayer && !waitingPWT) {
                Thread t = new Thread(() -> {
                    try {
                        pokemonMessages = new LinkedBlockingQueue<>();
                        personInBattle = senderFinal;
                        System.err.println("Going into Pokemon Battle");
                        PokemonBattle a = new PokemonBattle(this, channel.getChannelName(), bbrother, fChef,
                                sender.getNick(), false);
                        System.err.println("Now out of Pokemon Battle");
                        pokemonMessages = new LinkedBlockingQueue<>();
                        personInBattle = "";
                        battle = null;
                    } catch (Exception ex) {
                        personInBattle = "";
                        pokemonMessages = new LinkedBlockingQueue<>();
                        this.sendMessage(channel.getChannelName(),
                                "Something fucked up OneHand this battle is now over both Pokemon exploded violently KAPOW");
                        System.err.println("[POKEMON] Uh oh " + ex);
                        ex.printStackTrace();
                        StringWriter sw = new StringWriter();
                        PrintWriter pw = new PrintWriter(sw);
                        ex.printStackTrace(pw);
                        music.sendMessage(music.getChannel(),
                                music.CHEF.mention() + " ```" + sw.toString() + "```");
                        battle = null;
                    }
                });
                t.start();
            }
        }
    }
    if (message.toLowerCase().startsWith("!run")) {
        if (!channel.getChannelName().equals("#_keredau_1423645868201")) {
            return;
        }
        if (isInBattle() && battle instanceof PokemonBattle) {
            if (sender.getNick().equalsIgnoreCase(personInBattle)) {
                //                    if (DekuBot.containsOtherChar(message)) {
                //                        this.sendMessage(channel.getChannelName(), sender + "... TriHard");
                //                        return;
                //                    }
                personInBattle = "";
                pokemonMessages.add("run");
            }
        }
    }

    if (message.toLowerCase().startsWith("!move1") || message.toLowerCase().startsWith("!move2")
            || message.toLowerCase().startsWith("!move3") || message.toLowerCase().startsWith("!move4")) {
        if (sender.getNick().equalsIgnoreCase("wow_deku_onehand")) {
            return;
        }
        if (!channel.getChannelName().equals("#_keredau_1423645868201")) {
            return;
        }
        if (isInBattle() && battle instanceof PokemonBattle) {
            if (sender.getNick().equalsIgnoreCase(personInBattle)) {
                pokemonMessages.add("" + message.charAt(5));
            }
        }
    }
}

From source file:org.projectforge.user.UserDao.java

/**
 * Checks the password quality of a new password. Password must have at least 6 characters and at minimum one letter and one non-letter
 * character./*  w ww  .  jav  a 2s.com*/
 * @param newPassword
 * @return null if password quality is OK, otherwise the i18n message key of the password check failure.
 */
public String checkPasswordQuality(final String newPassword) {
    boolean letter = false;
    boolean nonLetter = false;
    if (newPassword == null || newPassword.length() < 6) {
        return MESSAGE_KEY_PASSWORD_QUALITY_CHECK;
    }
    for (int i = 0; i < newPassword.length(); i++) {
        final char ch = newPassword.charAt(i);
        if (letter == false && Character.isLetter(ch) == true) {
            letter = true;
        } else if (nonLetter == false && Character.isLetter(ch) == false) {
            nonLetter = true;
        }
    }
    if (letter == true && nonLetter == true) {
        return null;
    }
    return MESSAGE_KEY_PASSWORD_QUALITY_CHECK;
}

From source file:org.apache.cocoon.transformation.TraxTransformer.java

/**
 * Test if the name is a valid parameter name for XSLT
 *///from   w  w w  .j a v  a  2  s  .c  o  m
static boolean isValidXSLTParameterName(String name) {
    if (name.length() == 0) {
        return false;
    }

    char c = name.charAt(0);
    if (!(Character.isLetter(c) || c == '_')) {
        return false;
    }

    for (int i = name.length() - 1; i > 1; i--) {
        c = name.charAt(i);
        if (!(Character.isLetterOrDigit(c) || c == '-' || c == '_' || c == '.')) {
            return false;
        }
    }
    return true;
}

From source file:org.sd.token.StandardTokenizerOptions.java

public boolean isLetter(int codePoint) {
    boolean result = Character.isLetter(codePoint);

    if (!result && symbolUppersCodePoints != null) {
        result = symbolUppersCodePoints.contains(codePoint);
    }//from w  w w .  j a  v  a 2s . com

    if (!result && symbolLowersCodePoints != null) {
        result = symbolLowersCodePoints.contains(codePoint);
    }

    return result;
}

From source file:plugspud.PluginManager.java

/**
 * Load plugins defined in the plugins properties file
 * /*from  w  ww. java 2  s. co  m*/
 * @param url
 *            location of plugins.properties
 * @param classLoader
 *            the class loader to use to load the plugin
 * @param standard
 *            <code>true</code> if any plugins loaded are standard plugins
 * 
 * @throws PluginException
 *             on any error
 */
public void loadPlugins(URL url, ClassLoader classLoader, boolean standard) throws PluginException {
    InputStream in = null;

    try {
        context.log(PluginHostContext.LOG_INFORMATION, "Loading plugins from " + url.toExternalForm());

        HashMap props = loadPluginProperties(url);

        for (Iterator i = props.keySet().iterator(); i.hasNext();) {
            String key = (String) i.next();
            Properties properties = (Properties) props.get(key);

            String name = properties.getProperty(PLUGIN_NAME);

            if (name == null)
                throw new PluginException(
                        "<pluginName>.name property " + "not specified in " + url.toExternalForm());

            String shortDescription = properties.getProperty(PLUGIN_SHORT_DESCRIPTION);

            if (shortDescription == null)
                throw new PluginException(
                        "<pluginName>.shortDescription property " + "not specified in " + url.toExternalForm());

            String requiredHostVersion = properties.getProperty(PLUGIN_REQUIRED_HOST_VERSION);

            if (requiredHostVersion == null)
                throw new PluginException("<pluginName>.requiredHostVersion property " + "not specified in "
                        + url.toExternalForm());

            String className = properties.getProperty("className");

            if (className == null)
                throw new PluginException(
                        "<pluginName>.className property " + "not specified in " + url.toExternalForm());

            String version = properties.getProperty("version");

            if (version == null)
                throw new PluginException(
                        "<pluginName>.version property " + "not specified in " + url.toExternalForm());

            String jars = properties.getProperty(PLUGIN_JARS);
            String dependencies = properties.getProperty(PLUGIN_DEPENDENCIES);
            int order = 999;
            try {
                order = Integer.parseInt(properties.getProperty(PLUGIN_ORDER));
            } catch (Exception e) {
            }
            String pluginURL = properties.getProperty(PLUGIN_URL);
            String author = properties.getProperty(PLUGIN_AUTHOR);
            String information = properties.getProperty(PLUGIN_INFORMATION);

            List<PluginWrapper> found = new ArrayList<PluginWrapper>();

            context.log(PluginHostContext.LOG_DEBUG, "Looking for plugin " + name);
            for (Iterator z = plugins.iterator(); z.hasNext();) {
                PluginWrapper pw = (PluginWrapper) z.next();
                context.log(PluginHostContext.LOG_DEBUG,
                        "   Testing againts " + pw.properties.getProperty(PLUGIN_NAME, ""));
                if (pw.properties.getProperty(PLUGIN_NAME, "").equals(name))
                    found.add(pw);
            }

            if (found.size() > 0)
                context.log(PluginHostContext.LOG_DEBUG,
                        "Plugin " + name + " [" + className + "] has been found more than once " + found);
            else {
                context.log(PluginHostContext.LOG_INFORMATION,
                        "Loading plugin " + name + " [" + className + "]");

                try {
                    PluginVersion reqVersion = null;
                    if (!requiredHostVersion.equalsIgnoreCase("any")) {
                        if (context.getPluginHostVersion() == null) {
                            throw new PluginException("Plugin host is not supplying its version number.");
                        }
                        reqVersion = new PluginVersion(requiredHostVersion);
                        int dif = reqVersion.compareTo(context.getPluginHostVersion());
                        // System.out.println("Comparing " + reqVersion + "
                        // to " + context.getPluginHostVersion() + " = " +
                        // dif);
                        if (dif > 0)
                            throw new PluginException("This plugin requires that " + context.getPluginHostName()
                                    + " is at least of version " + reqVersion.toString()
                                    + ". The plugin host is current at version "
                                    + context.getPluginHostVersion().getVersionString());
                    }

                    Plugin plugin = (Plugin) Class.forName(className, true, classLoader).newInstance();
                    String resn = plugin.getClass().getName().replace('.', '/') + ".class";
                    context.log(PluginHostContext.LOG_DEBUG, "Looking for resource " + resn);
                    URL res = plugin.getClass().getClassLoader().getResource(resn);
                    String resource = "";
                    if (res == null)
                        context.log(PluginHostContext.LOG_ERROR, "Could not locate resource " + resn);
                    else {

                        String n = res.toExternalForm();
                        if (n.startsWith("jar:file:")) {
                            n = n.substring(4);
                            int idx = n.lastIndexOf('!');
                            if (idx != -1)
                                n = n.substring(0, idx);
                            n = n.substring(5);
                            // Windows path?
                            if (n.startsWith("/") && n.length() > 3 && n.charAt(2) == ':'
                                    && Character.isLetter(n.charAt(1)) && n.charAt(3) == '/')
                                n = n.substring(1);
                            File f = new File(n);
                            resource = f.getAbsolutePath();
                        }
                        context.log(PluginHostContext.LOG_DEBUG, "Resource is " + resource);
                    }
                    Properties pr = new Properties();
                    pr.put(PLUGIN_NAME, name);
                    pr.put(PLUGIN_SHORT_DESCRIPTION, shortDescription);
                    pr.put(PLUGIN_CLASSNAME, className);
                    pr.put(PLUGIN_VERSION, version);
                    pr.put(PLUGIN_RESOURCE, resource);

                    if (author != null)
                        pr.put(PLUGIN_AUTHOR, author);

                    if (jars != null)
                        pr.put(PLUGIN_JARS, jars);

                    if (dependencies != null)
                        pr.put(PLUGIN_DEPENDENCIES, dependencies);

                    if (information != null)
                        pr.put(PLUGIN_INFORMATION, information);

                    pr.put(PLUGIN_ORDER, String.valueOf(order));

                    if (pluginURL != null)
                        pr.put(PLUGIN_URL, pluginURL);
                    addPlugin(plugin, pr);
                } catch (Throwable t) {
                    context.log(PluginHostContext.LOG_ERROR,
                            "Failed to load plugin " + className + " in " + url.toExternalForm(), t);
                }
            }
        }
    } finally {
        PluginUtil.closeStream(in);
    }
}

From source file:org.apache.axis.wsdl.toJava.JavaGeneratorFactory.java

/** Refactored to call recursively for JAX-RPC 1.1 spec 4.2.5. */
protected int javifyTypeEntryName(SymbolTable symbolTable, TypeEntry entry, HashMap anonQNames, int uniqueNum) {
    TypeEntry tEntry = entry;/* w ww  .j  a v a2 s  . c o  m*/
    String dims = tEntry.getDimensions();
    TypeEntry refType = tEntry.getRefType();
    while (refType != null) {
        tEntry = refType;
        dims += tEntry.getDimensions();
        refType = tEntry.getRefType();
    }

    TypeEntry te = tEntry;
    while (te != null) {
        TypeEntry base = SchemaUtils.getBaseType(te, symbolTable);
        if (base == null)
            break;

        uniqueNum = javifyTypeEntryName(symbolTable, base, anonQNames, uniqueNum);

        if (Utils.getEnumerationBaseAndValues(te.getNode(), symbolTable) == null
                && SchemaUtils.getComplexElementExtensionBase(te.getNode(), symbolTable) == null
                && te.getContainedAttributes() == null) {
            if (!SchemaUtils.isSimpleTypeWithUnion(te.getNode())) {
                if (base.isSimpleType()) {
                    // Case 1:
                    // <simpleType name="mySimpleStringType">
                    //   <restriction base="xs:string">
                    //   </restriction>
                    // </simpleType>
                    te.setSimpleType(true);
                    te.setName(base.getName());
                    te.setRefType(base);
                }

                if (base.isBaseType()) {
                    // Case 2:
                    // <simpleType name="FooString">
                    //   <restriction base="foo:mySimpleStringType">
                    //   </restriction>
                    // </simpleType>
                    te.setBaseType(true);
                    te.setName(base.getName());
                    te.setRefType(base);
                }
            }
        }

        if (!te.isSimpleType())
            break;

        te = base;
    }

    // Need to javify the ref'd TypeEntry if it was not
    // already processed
    if (tEntry.getName() == null) {
        boolean processed = false; // true if the java name is already determined
        // Get the QName of the ref'd TypeEntry, which
        // is will be used to javify the name
        QName typeQName = tEntry.getQName();

        // In case of <xsd:list itemType="...">,
        // set typeQName to the value of the itemType attribute.
        QName itemType = SchemaUtils.getListItemType(tEntry.getNode());
        if (itemType != null) {
            // Get the typeEntry so we know the absolute base type
            TypeEntry itemEntry = symbolTable.getTypeEntry(itemType, false);
            // TODO - If the itemEntry is not found, we need to throw
            // an exception.  "Item is referenced, but not defined"
            javifyTypeEntryName(symbolTable, itemEntry, anonQNames, uniqueNum);
            // Grab the referenced type, If it's there.
            TypeEntry refedEntry = itemEntry.getRefType();
            QName baseName = refedEntry == null ? itemEntry.getQName() : refedEntry.getQName();
            typeQName = new QName(baseName.getNamespaceURI(), baseName.getLocalPart() + "[]");
        }

        if (emitter.isDeploy()) {
            Class class1 = (Class) emitter.getQName2ClassMap().get(typeQName);
            if (class1 != null && !class1.isArray()) {
                tEntry.setName(getJavaClassName(class1));
                processed = true;
            }
        }

        if (!processed) {
            if ((typeQName.getLocalPart().indexOf(SymbolTable.ANON_TOKEN) < 0)) {
                // Normal Case: The ref'd type is not anonymous
                // Simply construct the java name from
                // the qName
                tEntry.setName(emitter.getJavaName(typeQName));
            } else {
                // This is an anonymous type name.
                // Axis uses '>' as a nesting token to generate
                // unique qnames for anonymous types.
                // Only consider the localName after the last '>'
                // when generating the java name
                // String localName = typeQName.getLocalPart();
                // localName =
                // localName.substring(
                // localName.lastIndexOf(
                // SymbolTable.ANON_TOKEN)+1);
                // typeQName = new QName(typeQName.getNamespaceURI(),
                // localName);
                String localName = typeQName.getLocalPart();

                // Check to see if this is an anonymous type,
                // if it is, replace Axis' ANON_TOKEN with
                // an underscore to make sure we don't run
                // into name collisions with similarly named
                // non-anonymous types
                StringBuffer sb = new StringBuffer(localName);
                int aidx;

                while ((aidx = sb.toString().indexOf(SymbolTable.ANON_TOKEN)) > -1) {
                    sb.replace(aidx, aidx + SymbolTable.ANON_TOKEN.length(), "");
                    char c = sb.charAt(aidx);
                    if (Character.isLetter(c) && Character.isLowerCase(c)) {
                        sb.setCharAt(aidx, Character.toUpperCase(c));
                    }
                }

                localName = sb.toString();
                typeQName = new QName(typeQName.getNamespaceURI(), localName);

                if (emitter.isTypeCollisionProtection() && !emitter.getNamespaceExcludes()
                        .contains(new NamespaceSelector(typeQName.getNamespaceURI()))) {
                    // If there is already an existing type,
                    // there will be a collision.
                    // If there is an existing anon type,
                    // there will be a  collision.
                    // In both cases, mangle the name.
                    if (symbolTable.getType(typeQName) != null || anonQNames.get(typeQName) != null) {
                        localName += "Type" + uniqueNum++;
                        typeQName = new QName(typeQName.getNamespaceURI(), localName);
                    }

                    anonQNames.put(typeQName, typeQName);
                }

                // Now set the name with the constructed qname
                tEntry.setName(emitter.getJavaName(typeQName));
            }
        } // if (!processed)

        Vector elements = tEntry.getContainedElements();
        if (elements != null) {
            for (int i = 0; i < elements.size(); i++) {
                ElementDecl elem = (ElementDecl) elements.get(i);
                String varName = emitter.getJavaVariableName(typeQName, elem.getQName(), true);
                elem.setName(varName);
            }
        }

        Vector attributes = tEntry.getContainedAttributes();
        if (attributes != null) {
            for (int i = 0; i < attributes.size(); i++) {
                ContainedAttribute attr = (ContainedAttribute) attributes.get(i);
                String varName = emitter.getJavaVariableName(typeQName, attr.getQName(), false);
                attr.setName(varName);
            }
        }
    }

    // Set the entry with the same name as the ref'd entry
    // but add the appropriate amount of dimensions
    entry.setName(tEntry.getName() + dims);

    return uniqueNum;
}

From source file:org.eclipse.swt.examples.layoutexample.FormLayoutTab.java

/**
 * Sets an attachment to the edge of a widget using the
 * information in the table.//ww w.j  av a 2 s.  c om
 */
FormAttachment setAttachment(String attachment) {
    String control, align;
    int position, offset;
    int comma = attachment.indexOf(',');
    char first = attachment.charAt(0);
    if (Character.isLetter(first)) {
        /* Case where there is a control */
        control = attachment.substring(0, comma);
        int i = 0;
        while (i < control.length() && !Character.isDigit(control.charAt(i))) {
            i++;
        }
        String end = control.substring(i);
        int index = Integer.valueOf(end).intValue();
        Control attachControl = children[index];
        int colon = attachment.indexOf(':');
        try {
            offset = Integer.valueOf(attachment.substring(comma + 1, colon)).intValue();
        } catch (NumberFormatException e) {
            offset = 0;
        }
        align = attachment.substring(colon + 1);
        return new FormAttachment(attachControl, offset, alignmentConstant(align));
    } else {
        /* Case where there is a position */
        try {
            position = Integer.valueOf(attachment.substring(0, comma));
        } catch (NumberFormatException e) {
            position = 0;
        }
        try {
            offset = Integer.valueOf(attachment.substring(comma + 1));
        } catch (NumberFormatException e) {
            offset = 0;
        }
        return new FormAttachment(position, offset);
    }
}