Example usage for org.apache.commons.lang StringUtils isAlpha

List of usage examples for org.apache.commons.lang StringUtils isAlpha

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils isAlpha.

Prototype

public static boolean isAlpha(String str) 

Source Link

Document

Checks if the String contains only unicode letters.

Usage

From source file:de.weltraumschaf.registermachine.asm.CharUtils.java

static boolean isAlpha(final char c) {
    return StringUtils.isAlpha(String.valueOf(c));
}

From source file:jp.co.tis.gsp.tools.dba.util.SqlSplitter.java

/**
 * Check if the given sql line contains a delimiter representing the end of the command.
 * Please note that we do <em>not</em> fully parse the SQL,
 * so if we get a malformed statement, we cannot detect it.
 *
 * @param line to parse// www.  j  a va  2 s. c  om
 * @param delimiter which should be used to split SQL commands
 * @param overflowValue 0=none, {@link SqlSplitter#OVERFLOW_COMMENT},
 *        {@link SqlSplitter#OVERFLOW_SINGLE_QUOTE} or
 *        {@link SqlSplitter#OVERFLOW_DOUBLE_QUOTE}
 * @return position after the end character if the given line contains the end of a SQL script,
 *         {@link SqlSplitter#NO_END} if it doesn't contain an end char. {@link SqlSplitter#OVERFLOW_SINGLE_QUOTE}
 *         will be returned if a single quote didn't get closed, {@link SqlSplitter#OVERFLOW_DOUBLE_QUOTE} likewise
 *         for not closed double quotes.
 */
public static int containsSqlEnd(String line, String delimiter, final int overflowValue) {
    int ret = overflowValue >= 0 ? NO_END : overflowValue;

    // / * * / comments
    boolean isComment = (overflowValue == OVERFLOW_COMMENT);

    String quoteChar = null;
    if (overflowValue == OVERFLOW_SINGLE_QUOTE) {
        quoteChar = "'";
    } else if (overflowValue == OVERFLOW_DOUBLE_QUOTE) {
        quoteChar = "\"";
    }

    boolean isAlphaDelimiter = StringUtils.isAlpha(delimiter);

    if (line == null || line.length() == 0) {
        return ret;
    }

    int pos = 0;
    int maxpos = line.length() - 1;

    char c1;
    char c2 = line.charAt(0);
    statement: do {
        if (isComment) {
            do {
                // keep c2 in line
                if (pos < maxpos) {
                    c2 = line.charAt(pos + 1);
                }

                if (startsWith(line, '*', pos) && startsWith(line, '/', pos + 1)) {
                    ret = NO_END;
                    isComment = false;

                    continue statement;
                }
            } while (pos++ < maxpos);

            //reached EOL
            break statement;
        }

        // if in quote-mode, search for end quote, respecting escaped characters
        if (quoteChar != null) {
            String doubleQuote = quoteChar + quoteChar;
            do {
                // keep c2 in line
                if (pos < maxpos) {
                    c2 = line.charAt(pos + 1);
                }

                if (startsWith(line, "\\", pos) || startsWith(line, doubleQuote, pos)) {
                    //skip next character, but stay in quote-mode
                    pos++;
                } else if (startsWith(line, quoteChar, pos)) {
                    ret = NO_END;
                    quoteChar = null;

                    continue statement;
                }
            } while (pos++ < maxpos);

            // reach EOL
            break statement;
        }

        // use the nextchar from the previous iteration
        c1 = c2;
        if (pos < maxpos) {
            // and set the following char
            c2 = line.charAt(pos + 1);
        } else {
            // or reset to blank if the line has ended
            c2 = ' ';
        }

        // verify if current char indicates start  of new quoted block
        if (c1 == '\'' || c1 == '"') {
            quoteChar = String.valueOf(c1);
            ret = quoteChar.equals("'") ? OVERFLOW_SINGLE_QUOTE : OVERFLOW_DOUBLE_QUOTE;
            continue statement;
        }

        // parse for a / * start of comment
        if (c1 == '/' && c2 == '*') {
            isComment = true;
            pos++;
            ret = OVERFLOW_COMMENT;
            continue statement;
        }

        if (c1 == '-' && c2 == '-') {
            return ret;
        }

        if (startsWith(line, delimiter, pos)) {
            if (isAlphaDelimiter) {
                // check if delimiter is at start or end of line, surrounded
                // by non-alpha character
                if ((pos == 0 || !isAlpha(line.charAt(pos - 1))) && (line.length() == pos + delimiter.length()
                        || !isAlpha(line.charAt(pos + delimiter.length())))) {
                    return pos + delimiter.length();
                }
            } else {
                return pos + delimiter.length();
            }
        }

    } while (maxpos > pos++);

    return ret;
}

From source file:morphy.command.LoginsCommand.java

public void process(String arguments, UserSession userSession) {
    /*if (arguments.equals("")) {
       process(userSession.getUser().getUserName(),userSession);
       return;//from w ww . ja v a2 s.  c  o m
    }*/
    /*    log googlephone
       googlephone has not logged on.
     */
    /* log YUBBUB
       Sun Aug  7, 13:00 MDT 2011: YUBBUB(U)            login 
       log YUBBUBTWO
       There is no player matching the name yubbubtwo.
     */

    arguments = arguments.trim();

    String username = arguments;

    if (username.equals("")) {
        username = userSession.getUser().getUserName();
    }

    if (username.equals("*")) {
        new LLoginsCommand().process("", userSession);
        return;
    }

    int strlen = username.length();
    if (strlen < 2) {
        userSession.send("You need to specify at least two characters of the name.");
        return;
    }
    if (!arguments.contains("*") && !StringUtils.isAlpha(username)) {
        userSession.send(username + " is not a valid handle.");
        return;
    }
    if (arguments.contains("*"))
        username = username.replace("*", "%");

    boolean isAdmin = UserService.getInstance().isAdmin(userSession.getUser().getUserName());
    StringBuilder b = new StringBuilder();
    final java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEE MMM dd, HH:mm z yyyy");

    int limit = 20;
    int count = 0;

    String query = "SELECT COUNT(*) FROM `logins` WHERE `username` LIKE '" + username + "'";
    ResultSet rs = DatabaseConnectionService.getInstance().getDBConnection().executeQueryWithRS(query);
    try {
        if (rs.next()) {
            count = rs.getInt(1);
        }
    } catch (SQLException e) {
        Morphy.getInstance().onError(e);
    }

    if (limit > count)
        limit = count;

    query = "SELECT `id` FROM (SELECT `id` FROM `logins` WHERE `username` LIKE '" + username
            + "' ORDER BY `id` DESC) t LIMIT " + limit;
    rs = DatabaseConnectionService.getInstance().getDBConnection().executeQueryWithRS(query);
    int[] arr = new int[limit];
    try {
        int index = 0;
        while (rs.next()) {
            arr[index++] = rs.getInt(1);
        }
        if (index == 0) {
            // this user has never connected it seems.
            if (username.contains("%")) {
                // this is a feature that is NOT part of FICS.
                userSession.send("No usernames matching the pattern " + username.replace("%", "*")
                        + " have ever logged in.");
                return;
            } else {
                userSession.send(username + " has not logged on.");
                return;
            }
        }
    } catch (SQLException e) {
        Morphy.getInstance().onError(e);
    }
    java.util.Arrays.sort(arr);
    StringBuilder queryBuilder = new StringBuilder(125);
    queryBuilder.append("SELECT `id`,`username`,CONVERT_TZ(`timestamp`,'UTC','SYSTEM'),`type`"
            + (isAdmin ? ",`ipAddress`" : "") + " " + "FROM `logins` WHERE `id` IN ("); // WHERE `username` LIKE '" + username + "'
    for (int i = 0; i < arr.length; i++) {
        queryBuilder.append(arr[i]);
        if (i != arr.length - 1)
            queryBuilder.append(",");
    }
    queryBuilder.append(") ORDER BY `id` ASC");
    query = queryBuilder.toString();
    rs = DatabaseConnectionService.getInstance().getDBConnection().executeQueryWithRS(query);
    try {
        while (rs.next()) {
            String line = "";
            if (!isAdmin)
                line = String.format("%26s: %-20s %s", sdf.format(rs.getTimestamp(3).getTime()),
                        rs.getString(2), rs.getString(4));
            if (isAdmin)
                line = String.format("%26s: %-20s %7s from %s", sdf.format(rs.getTimestamp(3).getTime()),
                        rs.getString(2), rs.getString(4), rs.getString(5));
            if (rs.next()) {
                line += "\n";
                rs.previous();
            }
            b.append(line);
        }
    } catch (SQLException e) {
        Morphy.getInstance().onError(e);
    }

    userSession.send(b.toString());
}

From source file:com.intellectualcrafters.plot.flag.AbstractFlag.java

/**
 * AbstractFlag is a parameter used in creating a new Flag
 *
 * @param key The key must be alphabetical characters and <= 16 characters
 *            in length/*from  ww w .  ja  va  2s .c om*/
 */
public AbstractFlag(final String key) {
    if (!StringUtils.isAlpha(key.replaceAll("_", "").replaceAll("-", ""))) {
        throw new IllegalArgumentException("Flag must be alphabetic characters");
    }
    if (key.length() > 16) {
        throw new IllegalArgumentException("Key must be <= 16 characters");
    }
    this.key = key.toLowerCase();
}

From source file:com.liferay.alloy.util.DefaultValueUtil.java

public static boolean isValidStringValue(String value) {
    value = StringUtil.trim(GetterUtil.getString(value));

    if (Validator.isNull(value)) {
        return false;
    }/*from ww  w.  j a v  a2s .c  o  m*/

    if (StringUtils.isAlpha(value) || (!StringUtils.containsIgnoreCase(value, _GENERATED)
            && !StringUtils.isAlpha(value.substring(0, 1))
            && !StringUtils.endsWith(value, StringPool.PERIOD))) {

        return true;
    }

    return false;
}

From source file:morphy.command.ClearmessagesCommand.java

public void process(String arguments, UserSession userSession) {
    /*  clearmessages */*from   w w w .  java  2  s.  c  om*/
      will delete all of your messages.
       clearmessages 2
      will delete your message #2.
       clearmessages DAV
      will delete all of your messages from DAV.
       clearmessages 4-7
      will delete your messages 4 through 7.
     */
    /*   clearmessage 38-40
       Messages 38-40 cleared.
    */
    /*   clearmessages 37-40
       You have no messages 37-40.
     */
    /*   You have 36 messages (1 unread).
       Use "messages u" to view unread messages and "clearmessages *" to clear all.
    */

    arguments = arguments.trim();
    if (arguments.equals("")) {
        userSession.send(getContext().getUsage());
        return;
    } else {
        if (!UserService.getInstance().isRegistered(userSession.getUser().getUserName())) {
            userSession.send("Only registered players can use the clearmessages command.");
            return;
        }

        int numMessages = 0;
        String query = "SELECT COUNT(*) FROM `messages` WHERE `to_user_id` = '"
                + userSession.getUser().getDBID() + "';";
        ResultSet rs = DatabaseConnectionService.getInstance().getDBConnection().executeQueryWithRS(query);
        try {
            if (rs.next()) {
                numMessages = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace(System.err);
        }

        if (numMessages == 0) {
            userSession.send("You have no messages.");
            return;
        }

        if (arguments.equals("*")) {
            // delete all messages

            query = "DELETE FROM `messages` WHERE `to_user_id` = '" + userSession.getUser().getDBID() + "'";
            boolean executed = DatabaseConnectionService.getInstance().getDBConnection().executeQuery(query);
            if (executed) {
                userSession.send("Messages cleared.");
                return;
            }
        }

        if (StringUtils.isNumeric(arguments)) {
            // delete this message

            arguments += "-" + arguments;
            //return;
        }

        if (StringUtils.isAlpha(arguments)) {
            // delete all messages from this user

            int id = UserService.getInstance().getDBID(arguments);
            if (id == 0) { /* something failed */
                userSession.send("There is no player matching the name " + arguments + ".");
                return;
            } else {
                /*   clearmessages outrunyou
                   You have no messages from OUTRUNYOU.
                */

                String username = UserService.getInstance().correctCapsUsername(arguments);

                query = "SELECT `id` FROM `messages` WHERE `from_user_id` = '" + id + "' ORDER BY `id` ASC";
                rs = DatabaseConnectionService.getInstance().getDBConnection().executeQueryWithRS(query);
                try {
                    List<Integer> ids = new ArrayList<Integer>();
                    while (rs.next()) {
                        ids.add(new Integer(rs.getInt(1)));
                    }
                    if (ids.size() == 0) {
                        userSession.send("You have no messages from " + username + ".");
                        return;
                    } else {
                        query = "DELETE FROM `messages` WHERE "
                                + MessagesCommand.formatIdListForQuery("id", ids);
                        boolean executed = DatabaseConnectionService.getInstance().getDBConnection()
                                .executeQuery(query);
                        if (executed) {
                            userSession.send("Messages from " + username + " cleared.");
                            return;
                        }
                    }
                } catch (SQLException e) {
                    e.printStackTrace(System.err);
                }
            }
            return;
        }

        if (arguments.matches("[0-9]+\\-[0-9]+")) {
            // delete this range of messages
            List<Integer> list = MessagesCommand.expandRange(arguments);
            java.util.Collections.sort(list);
            query = "SELECT m.`id`,u1.`username`,`message`,`timestamp`,`read` "
                    + "FROM `messages` m INNER JOIN `users` u1 ON (u1.`id` = m.`from_user_id`) "
                    + "WHERE m.to_user_id = '" + userSession.getUser().getDBID() + "'" + "ORDER BY m.`id` ASC";
            rs = DatabaseConnectionService.getInstance().getDBConnection().executeQueryWithRS(query);
            try {
                // the "ids" variable contains the actual message ids as stored in the database
                // and NOT the psuedo message number as the user thinks.
                List<Integer> ids = new ArrayList<Integer>();
                List<Integer> rownums = new ArrayList<Integer>();
                int rownum = 0;
                while (rs.next()) {
                    rownum++;
                    if (list.contains(rownum)) {
                        ids.add(rs.getInt(1));
                        rownums.add(rownum);
                    }
                }
                if (ids.size() > 0) {
                    query = "DELETE FROM `messages` WHERE " + MessagesCommand.formatIdListForQuery("id", ids);
                    boolean executed = DatabaseConnectionService.getInstance().getDBConnection()
                            .executeQuery(query);
                    if (executed) {
                        userSession.send((rownums.size() == 1 ? "Message" : "Messages") + " "
                                + rownums.toString() + " cleared.");
                        return;
                    }
                } else {
                    userSession.send("You have no message" + (rownums.size() > 1 ? "s" : "") + " "
                            + rownums.toString() + ".");
                    return;
                }
            } catch (SQLException e) {
                e.printStackTrace(System.err);
            }

            return;
        }

        // if we've reached this point, nothing has been deleted, so invalid arguments.
        userSession.send(getContext().getUsage());
        return;
    }
}

From source file:de.xirp.ui.widgets.panels.virtual.MazeComposite.java

/**
 * /*from w w  w  .j a va  2  s .c  om*/
 */
private void init() {
    listener = new ATEAdapter() {

        @Override
        public void classListChanged() {
            classes.removeAll();
            for (String s : ATEManager.getMazeJavaClasses()) {
                classes.add(s);
            }
        }

    };
    ATEManager.addATEListener(listener);

    addDisposeListener(new DisposeListener() {

        public void widgetDisposed(DisposeEvent e) {
            ATEManager.removeATEListener(listener);
        }

    });

    SWTUtil.setGridLayout(this, 5, true);

    mc = new MazeCanvas(this, 10, 10);
    SWTUtil.setGridData(mc, false, false, SWT.FILL, SWT.FILL, 4, 3);

    XGroup constantsGroup = new XGroup(this, SWT.NONE);
    constantsGroup.setText("Constants"); //$NON-NLS-1$
    SWTUtil.setGridData(constantsGroup, true, false, SWT.FILL, SWT.FILL, 1, 1);
    SWTUtil.setGridLayout(constantsGroup, 2, true);

    for (MazeField mf : MazeField.values()) {
        XLabel reward = new XLabel(constantsGroup, SWT.NONE);
        reward.setText(mf.name() + " - Reward:"); //$NON-NLS-1$
        SWTUtil.setGridData(reward, true, false, SWT.FILL, SWT.FILL, 1, 1);

        XStyledSpinner spinner = new XStyledSpinner(constantsGroup, SWT.BORDER, SpinnerStyle.ALL);
        SWTUtil.setGridData(spinner, true, false, SWT.FILL, SWT.FILL, 1, 1);
        spinner.setData("name", mf.name()); //$NON-NLS-1$

        ATEManager.setConstant(mf.name(), 0.0);

        spinner.addValueChangedListener(new ValueChangedListener() {

            public void valueChanged(ValueChangedEvent event) {
                XStyledSpinner sp = (XStyledSpinner) event.getSource();
                ATEManager.setConstant((String) sp.getData("name"), event.getPreciseValue()); //$NON-NLS-1$
            }
        });
    }

    XGroup variablesGroup = new XGroup(this, SWT.NONE);
    variablesGroup.setText("Variables"); //$NON-NLS-1$
    SWTUtil.setGridData(variablesGroup, true, true, SWT.FILL, SWT.FILL, 1, 1);
    SWTUtil.setGridLayout(variablesGroup, 2, true);

    varName = new XTextField(variablesGroup, SWT.NONE);
    SWTUtil.setGridData(varName, true, false, SWT.FILL, SWT.FILL, 2, 1);
    varName.addModifyListener(new ModifyListener() {

        public void modifyText(ModifyEvent e) {
            XTextField tf = (XTextField) e.widget;
            String text = tf.getText();
            if (text.length() > 0 && StringUtils.isAsciiPrintable(text) && StringUtils.isAlpha(text)
                    && !variables.contains(text)) {
                add.setEnabled(true);
            } else {
                add.setEnabled(false);
            }
        }

    });

    add = new XButton(variablesGroup);
    add.setText("Add"); //$NON-NLS-1$
    add.setEnabled(false);
    SWTUtil.setGridData(add, true, false, SWT.FILL, SWT.FILL, 2, 1);
    add.addSelectionListener(new SelectionAdapter() {

        /* (non-Javadoc)
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            XTableItem itm = new XTableItem(table, SWT.NONE);
            String text = varName.getText();

            variables.add(text);
            itm.setText(0, text);
            //TODO
            itm.setText(1, "23.0"); //$NON-NLS-1$

            SWTUtil.packTable(table);
            add.setEnabled(false);

            ATEManager.setVariable(text, 23.0);
        }

    });

    table = new XTable(variablesGroup, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
    table.setLinesVisible(true);
    table.setHeaderVisible(true);

    String[] titles = { "Variable", "Value" }; //$NON-NLS-1$ //$NON-NLS-2$
    for (int i = 0; i < titles.length; i++) {
        XTableColumn column = new XTableColumn(table, SWT.NONE);
        column.setText(titles[i]);
    }

    SWTUtil.packTable(table);
    SWTUtil.setGridData(table, true, true, SWT.FILL, SWT.FILL, 2, 1);

    remove = new XButton(variablesGroup);
    remove.setText("Remove selected"); //$NON-NLS-1$
    SWTUtil.setGridData(remove, true, false, SWT.FILL, SWT.FILL, 2, 1);
    remove.addSelectionListener(new SelectionAdapter() {

        /* (non-Javadoc)
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            try {
                int idx = table.getSelectionIndex();
                String text = table.getItem(idx).getText(0);
                table.remove(idx);
                variables.remove(text);
            } catch (IllegalArgumentException ex) {
            }
        }

    });

    XGroup exeGroup = new XGroup(this, SWT.NONE);
    exeGroup.setText("Execute"); //$NON-NLS-1$
    SWTUtil.setGridData(exeGroup, true, false, SWT.FILL, SWT.FILL, 1, 1);
    SWTUtil.setGridLayout(exeGroup, 2, true);

    classes = new XCombo(exeGroup, SWT.BORDER | SWT.READ_ONLY);
    for (String s : ATEManager.getMazeJavaClasses()) {
        classes.add(s);
    }
    classes.addSelectionListener(new SelectionAdapter() {

        /* (non-Javadoc)
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            XCombo c = (XCombo) e.widget;
            if (!Util.isEmpty(c.getText())) {
                execute.setEnabled(true);
            }
        }

    });
    SWTUtil.setGridData(classes, true, false, SWT.FILL, SWT.FILL, 2, 1);

    execute = new XButton(exeGroup);
    execute.setText("Execute code"); //$NON-NLS-1$
    execute.setEnabled(false);
    SWTUtil.setGridData(execute, true, false, SWT.FILL, SWT.FILL, 2, 1);
    execute.addSelectionListener(new SelectionAdapter() {

        /* (non-Javadoc)
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            ATEManager.execute(classes.getText());
        }

    });
}

From source file:com.voidsearch.voidbase.quant.feed.TokenFrequency.java

/**
 * check whether token is valid//from  w w w  . java 2s . c  o m
 *
 * @param token
 * @return
 */
private boolean isValidToken(String token) {
    // filter empty strings
    //if (token.isEmpty()) {
    if ((token == null) || (token.length() == 0)) {
        return false;
    }
    // filter html tags
    if (token.contains(">") || token.contains("<")) {
        return false;
    }

    // filter min lenght
    if (token.length() < 5) {
        return false;
    }

    if (!StringUtils.isAlpha(token)) {
        return false;
    }

    return true;
}

From source file:com.abstratt.mdd.frontend.textuml.renderer.TextUMLRenderingUtils.java

private static String escapeIdentifierIfNeeded(String identifier) {
    if (StringUtils.isBlank(identifier))
        return "";
    if (!StringUtils.isAlpha(identifier)) {
        StringBuffer result = new StringBuffer(identifier.length());
        char[] chars = identifier.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] != '_'
                    && ((Character.isDigit(chars[i]) && i == 0) || !Character.isLetterOrDigit(chars[i])))
                result.append('\\');
            result.append(chars[i]);/*from   w w w .j a v  a 2 s. c o  m*/
        }
        return result.toString();
    }
    if (Arrays.binarySearch(TextUMLConstants.KEYWORDS, identifier) >= 0)
        return "\\" + identifier;
    return identifier;
}

From source file:com.p5solutions.core.utils.Comparison.java

/**
 * Checks if is alpha.//from  ww w .j av a  2 s.c  o  m
 * 
 * @param value
 *          the value
 * @return true, if is alpha
 */
public static boolean isAlpha(String value) {
    return StringUtils.isAlpha(value);
}