Example usage for java.lang Character isJavaIdentifierPart

List of usage examples for java.lang Character isJavaIdentifierPart

Introduction

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

Prototype

public static boolean isJavaIdentifierPart(int codePoint) 

Source Link

Document

Determines if the character (Unicode code point) may be part of a Java identifier as other than the first character.

Usage

From source file:org.pentaho.di.ui.i18n.MessagesSourceCrawler.java

/**
 * Look for additional occurrences of keys in the specified file.
 *
 * @param sourceFolder//from w ww  . j  a v a2 s.  com
 *          The folder the java file and messages files live in
 *
 * @param javaFile
 *          The java source file to examine
 * @throws IOException
 *           In case there is a problem accessing the specified source file.
 */
public void lookForOccurrencesInFile(String sourceFolder, FileObject javaFile) throws IOException {

    BufferedReader reader = new BufferedReader(new InputStreamReader(KettleVFS.getInputStream(javaFile)));

    String messagesPackage = null;
    int row = 0;
    String classPackage = null;

    Map<String, String> importedClasses = new Hashtable<String, String>(); // Remember the imports we do...

    String line = reader.readLine();
    while (line != null) {
        row++;
        String line2 = line;
        boolean extraLine;
        do {
            extraLine = false;
            for (String scanPhrase : scanPhrases) {
                if (line2.endsWith(scanPhrase)) {
                    extraLine = true;
                    break;
                }
            }
            if (extraLine) {
                line2 = reader.readLine();
                line += line2;
            }
        } while (extraLine);

        // Examine the line...

        // What we first look for is the import of the messages package.
        //
        // "package org.pentaho.di.trans.steps.sortedmerge;"
        //
        if (packagePattern.matcher(line).matches()) {
            int beginIndex = line.indexOf("org.pentaho.");
            int endIndex = line.indexOf(';');
            if (beginIndex >= 0 && endIndex >= 0) {
                messagesPackage = line.substring(beginIndex, endIndex); // this is the default
                classPackage = messagesPackage;
            }
        }

        // Remember all the imports...
        //
        if (importPattern.matcher(line).matches()) {
            int beginIndex = line.indexOf("import") + "import".length() + 1;
            int endIndex = line.indexOf(";", beginIndex);
            String expression = line.substring(beginIndex, endIndex);
            // The last word is the Class imported...
            // If it's * we ignore it.
            //
            int lastDotIndex = expression.lastIndexOf('.');
            if (lastDotIndex > 0) {
                String packageName = expression.substring(0, lastDotIndex);
                String className = expression.substring(lastDotIndex + 1);
                if (!"*".equals(className)) {
                    importedClasses.put(className, packageName);
                }
            }
        }

        // This is the alternative location of the messages package:
        //
        // "import org.pentaho.di.trans.steps.sortedmerge.Messages;"
        //
        if (importMessagesPattern.matcher(line).matches()) {
            int beginIndex = line.indexOf("org.pentaho.");
            int endIndex = line.indexOf(".Messages;");
            messagesPackage = line.substring(beginIndex, endIndex); // if there is any specified, we take this one.
        }

        // Look for the value of the PKG value...
        //
        // private static String PKG = "org.pentaho.foo.bar.somepkg";
        //
        if (stringPkgPattern.matcher(line).matches()) {
            int beginIndex = line.indexOf('"') + 1;
            int endIndex = line.indexOf('"', beginIndex);
            messagesPackage = line.substring(beginIndex, endIndex);
        }

        // Look for the value of the PKG value as a fully qualified class...
        //
        // private static Class<?> PKG = Abort.class;
        //
        if (classPackage != null && classPkgPattern.matcher(line).matches()) {

            int fromIndex = line.indexOf('=') + 1;
            int toIndex = line.indexOf(".class", fromIndex);
            String expression = Const.trim(line.substring(fromIndex, toIndex));
            // System.out.println("expression : "+expression);

            // If the expression doesn't contain any package, we'll look up the package in the imports. If not found there,
            // it's a local package.
            //
            if (expression.contains(".")) {
                int lastDotIndex = expression.lastIndexOf('.');
                messagesPackage = expression.substring(0, lastDotIndex);
            } else {
                String packageName = importedClasses.get(expression);
                if (packageName == null) {
                    messagesPackage = classPackage; // Local package
                } else {
                    messagesPackage = packageName; // imported
                }
            }

        }

        // Now look for occurrences of "Messages.getString(", "BaseMessages.getString(PKG", ...
        //
        for (String scanPhrase : scanPhrases) {
            int index = line.indexOf(scanPhrase);
            while (index >= 0) {
                // see if there's a character [a-z][A-Z] before the search string...
                // Otherwise we're looking at BaseMessages.getString(), etc.
                //
                if (index == 0 || (index > 0 & !Character.isJavaIdentifierPart(line.charAt(index - 1)))) {
                    addLineOccurrence(sourceFolder, javaFile, messagesPackage, line, row, index, scanPhrase);
                }
                index = line.indexOf(scanPhrase, index + 1);
            }
        }

        line = reader.readLine();
    }

    reader.close();
}

From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java

public static String generateClassName(String name, String version) {
    StringBuilder nameValue = new StringBuilder();
    nameValue.append(name != null ? name : "").append("_").append(version != null ? version : "_");

    StringBuilder result = new StringBuilder();
    for (Character c : nameValue.toString().toCharArray()) {
        if (Character.isJavaIdentifierPart(c)) {
            result.append(c);//from   w w  w . j  a v a  2s.  c om
        } else {
            result.append("_");
        }
    }
    while (!Character.isJavaIdentifierStart(result.charAt(0))) {
        result.deleteCharAt(0);
    }
    return Character.toUpperCase(result.charAt(0)) + result.substring(1);
}

From source file:stg.utils.StringUtils.java

/**
 * A whole word is identified as a word that does not have a valid {@link Character#isJavaIdentifierPart(char)} before or after the searchStr.
 * /*from w  w  w  .  j  av  a 2  s . c  om*/
 * @param text in which the search and replace is needed. 
 * @param word to be searched for
 * @return total count of whole words found within the text.
 */
public static int countAllWholeWord(String text, String word) {
    StringBuilder sb = new StringBuilder(text);
    int count = 0;
    int index = 0;
    while (sb.indexOf(word, index) > -1) {
        index = sb.indexOf(word, index);
        boolean notAWholeWord = false;
        if (index > 0) {
            char c = sb.charAt(index - 1);
            if (Character.isJavaIdentifierPart(c)) {
                notAWholeWord = true;
            }
            if (index + word.length() < sb.length()) {
                c = sb.charAt(index + word.length());
                if (Character.isJavaIdentifierPart(c)) {
                    notAWholeWord = true;
                }
            }
            if (!notAWholeWord) {
                count++;
            }
        } else if (index == 0) {
            if (index + word.length() < sb.length()) {
                char c = sb.charAt(index + word.length());
                if (Character.isJavaIdentifierPart(c)) {
                    notAWholeWord = true;
                }
            }
            if (!notAWholeWord) {
                count++;
            }
        }
        index++;
    }
    return count;
}

From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java

public static String checkClassName(String name) {
    name = name.replaceAll("\\s+", "").replaceAll("\\W", "");
    StringBuilder result = new StringBuilder();
    for (Character c : name.toCharArray()) {
        if (Character.isJavaIdentifierPart(c)) {
            result.append(c);/*from  w  w  w  .  j  a  va2  s. c  o m*/
        } else {
            result.append("_");
        }
    }
    while (!Character.isJavaIdentifierStart(result.charAt(0))) {
        result.deleteCharAt(0);
    }
    return Character.toUpperCase(result.charAt(0)) + result.substring(1);
}

From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java

public static String generateFieldName(String name) {
    String nameValue = name;/*  w  w  w  .j  a  v a 2  s .  co  m*/
    StringBuilder result = new StringBuilder();
    for (Character c : nameValue.toCharArray()) {
        if (Character.isJavaIdentifierPart(c)) {
            result.append(c);
        } else {
            result.append("");
        }
    }
    while (!Character.isJavaIdentifierStart(result.charAt(0))) {
        result.deleteCharAt(0);
    }
    return Character.toLowerCase(result.charAt(0)) + result.substring(1);
}

From source file:com.netspective.commons.text.TextUtils.java

/**
 * Given a text string, return a string that would be suitable for that string to be used
 * as a Java identifier (as a variable or method name). Depending upon whether ucaseInitial
 * is set, the string starts out with a lowercase or uppercase letter. Then, the rule is
 * to convert all periods into underscores and title case any words separated by
 * underscores. This has the effect of removing all underscores and creating mixed case
 * words. For example, Person_Address becomes personAddress or PersonAddress depending upon
 * whether ucaseInitial is set to true or false. Person.Address would become Person_Address.
 *///from  ww  w.j  a v  a2 s  .  c  o m
public String xmlTextToJavaIdentifier(String xml, boolean ucaseInitial) {
    if (xml == null || xml.length() == 0)
        return xml;

    String translated = (String) JAVA_RESERVED_WORD_TRANSLATION_MAP.get(xml.toString().toLowerCase());
    if (translated != null)
        xml = translated;

    StringBuffer identifier = new StringBuffer();
    char ch = xml.charAt(0);
    if (Character.isJavaIdentifierStart(ch))
        identifier.append(ucaseInitial ? Character.toUpperCase(ch) : Character.toLowerCase(ch));
    else {
        identifier.append('_');
        if (Character.isJavaIdentifierPart(ch))
            identifier.append(ucaseInitial ? Character.toUpperCase(ch) : Character.toLowerCase(ch));
    }

    boolean uCase = false;
    for (int i = 1; i < xml.length(); i++) {
        ch = xml.charAt(i);
        if (ch == '.') {
            identifier.append('_');
        } else if (ch != '_' && Character.isJavaIdentifierPart(ch)) {
            identifier.append(Character.isUpperCase(ch) ? ch
                    : (uCase ? Character.toUpperCase(ch) : Character.toLowerCase(ch)));
            uCase = false;
        } else
            uCase = true;
    }
    return identifier.toString();
}

From source file:com.puppycrawl.tools.checkstyle.utils.CommonUtil.java

/**
 * Checks whether the given string is a valid identifier.
 * @param str A string to check./*from   www. jav a2s  .  c o m*/
 * @return true when the given string contains valid identifier.
 */
public static boolean isIdentifier(String str) {
    boolean isIdentifier = !str.isEmpty();

    for (int i = 0; isIdentifier && i < str.length(); i++) {
        if (i == 0) {
            isIdentifier = Character.isJavaIdentifierStart(str.charAt(0));
        } else {
            isIdentifier = Character.isJavaIdentifierPart(str.charAt(i));
        }
    }

    return isIdentifier;
}

From source file:henplus.HenPlus.java

/**
 * substitute the variables in String 'in', that are in the form $VARNAME or ${VARNAME} with the equivalent value that is found
 * in the Map. Return the varsubstituted String.
 * /* w  w  w  .j  av  a  2s .  c om*/
 * @param in
 *            the input string containing variables to be substituted (with leading $)
 * @param variables
 *            the Map containing the mapping from variable name to value.
 */
public String varsubst(final String in, final Map<String, String> variables) {
    int pos = 0;
    int endpos = 0;
    int startVar = 0;
    final StringBuilder result = new StringBuilder();
    String varname;
    boolean hasBrace = false;

    if (in == null) {
        return null;
    }

    if (variables == null) {
        return in;
    }

    while ((pos = in.indexOf('$', pos)) >= 0) {
        startVar = pos;
        if (in.charAt(pos + 1) == '$') { // quoting '$'
            result.append(in.substring(endpos, pos));
            endpos = pos + 1;
            pos += 2;
            continue;
        }

        hasBrace = in.charAt(pos + 1) == '{';

        // text between last variable and here
        result.append(in.substring(endpos, pos));

        if (hasBrace) {
            pos++;
        }

        endpos = pos + 1;
        while (endpos < in.length() && Character.isJavaIdentifierPart(in.charAt(endpos))) {
            endpos++;
        }
        varname = in.substring(pos + 1, endpos);

        if (hasBrace) {
            while (endpos < in.length() && in.charAt(endpos) != '}') {
                ++endpos;
            }
            ++endpos;
        }
        if (endpos > in.length()) {
            if (variables.containsKey(varname)) {
                Logger.info("warning: missing '}' for variable '%s'.", varname);
            }
            result.append(in.substring(startVar));
            break;
        }

        if (variables.containsKey(varname)) {
            result.append(variables.get(varname));
        } else {
            Logger.info("warning: variable '%s' not set.", varname);
            result.append(in.substring(startVar, endpos));
        }

        pos = endpos;
    }
    if (endpos < in.length()) {
        result.append(in.substring(endpos));
    }
    return result.toString();
}

From source file:com.netspective.commons.text.TextUtils.java

/**
 * Given a text string, return a string that would be suitable for that string to be used
 * as a Java constant (public static final XXX). The rule is to basically take every letter
 * or digit and return it in uppercase and every non-letter or non-digit as an underscore.
 *//*from  w w w  .j a  v  a 2s  . co m*/
public String xmlTextToJavaConstant(String xml) {
    if (xml == null || xml.length() == 0)
        return xml;

    StringBuffer constant = new StringBuffer();
    for (int i = 0; i < xml.length(); i++) {
        char ch = xml.charAt(i);
        constant.append(Character.isJavaIdentifierPart(ch) ? Character.toUpperCase(ch) : '_');
    }
    return constant.toString();
}

From source file:org.apache.sqoop.model.ConfigUtils.java

private static void checkForValidConfigName(Set<String> existingConfigNames, String customConfigName) {
    // uniqueness across fields check
    if (existingConfigNames.contains(customConfigName)) {
        throw new SqoopException(ModelError.MODEL_012, "Issue with field config name " + customConfigName);
    }/*ww w  .ja va2 s  . c om*/

    if (!Character.isJavaIdentifierStart(customConfigName.toCharArray()[0])) {
        throw new SqoopException(ModelError.MODEL_013, "Issue with field config name " + customConfigName);
    }
    for (Character c : customConfigName.toCharArray()) {
        if (Character.isJavaIdentifierPart(c))
            continue;
        throw new SqoopException(ModelError.MODEL_013, "Issue with field config name " + customConfigName);
    }

    if (customConfigName.length() > 30) {
        throw new SqoopException(ModelError.MODEL_014, "Issue with field config name " + customConfigName);

    }
}