Example usage for java.lang Character isJavaIdentifierStart

List of usage examples for java.lang Character isJavaIdentifierStart

Introduction

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

Prototype

public static boolean isJavaIdentifierStart(int codePoint) 

Source Link

Document

Determines if the character (Unicode code point) is permissible as the first character in a Java identifier.

Usage

From source file:com.mirth.connect.connectors.jms.transformers.AbstractJmsTransformer.java

/**
 * Encode a string so that is is a valid java identifier
 * /*from   w  w w  .  j a v a 2s  .  c  o m*/
 * @param name
 * @return
 */
public static String encodeHeader(String name) {
    StringBuffer sb = new StringBuffer(name.length());
    for (int i = 0; i < name.length(); i++) {
        char c = name.charAt(i);
        if (i == 0) {
            if (!Character.isJavaIdentifierStart(c)) {
                c = REPLACEMENT_CHAR;
            }
        } else {
            if (!Character.isJavaIdentifierPart(c)) {
                c = REPLACEMENT_CHAR;
            }
        }
        sb.append(c);
    }
    return sb.toString();
}

From source file:org.apache.solr.search.SolrReturnFields.java

public static String getFieldName(StrParser sp) {
    sp.eatws();//from   w  ww  .j  a  v  a 2 s. com
    int id_start = sp.pos;
    char ch;
    if (sp.pos < sp.end && (ch = sp.val.charAt(sp.pos)) != '$' && Character.isJavaIdentifierStart(ch)) {
        sp.pos++;
        while (sp.pos < sp.end) {
            ch = sp.val.charAt(sp.pos);
            if (!Character.isJavaIdentifierPart(ch) && ch != '.' && ch != '-') {
                break;
            }
            sp.pos++;
        }
        return sp.val.substring(id_start, sp.pos);
    }

    return null;
}

From source file:org.jbpm.formModeler.core.processing.formRendering.FormRenderingFormatter.java

public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws FormatterException {
    Object formObject = getParameter("form");

    if (formObject != null)
        formToPaint = (Form) formObject;
    else {//  w  w w . j  a va 2  s.c  o  m
        log.error("Form not found");
        return;
    }

    renderMode = (String) getParameter("renderMode"); //Default is form
    String labelMode = (String) getParameter("labelMode"); //Default is before;
    String reusingStatus = (String) getParameter("reuseStatus"); //Default is true;
    String forceLabelModeParam = (String) getParameter("forceLabelMode"); //Default is false
    String displayModeParam = (String) getParameter("displayMode");
    String subForm = (String) getParameter("isSubForm");
    String multiple = (String) getParameter("isMultiple");

    Boolean readonly = (Boolean) getParameter("isReadonly");

    if (readonly != null)
        isReadonly = readonly;

    boolean isSubForm = subForm != null && Boolean.valueOf(subForm).booleanValue();
    boolean isMultiple = multiple != null && Boolean.valueOf(multiple).booleanValue();

    namespace = (String) getParameter("namespace");

    if (StringUtils.isEmpty(namespace)) {
        log.warn(
                "Empty namespace is no longer permitted. Will use a default namespace value, for backwards compatibility",
                new Exception());
        namespace = FormProcessor.DEFAULT_NAMESPACE;
    } else if (!Character.isJavaIdentifierStart(namespace.charAt(0))) {
        log.warn("Namespace " + namespace
                + " starts with an illegal character. It may cause unexpected behaviour of form under IE.");
    }
    Object formValues = getParameter("formValues");
    if (formValues != null) {
        getFormProcessor().clear(formToPaint, namespace);
        getFormProcessor().read(formToPaint, namespace, (Map) formValues);
    }
    // Default render mode is FORM
    renderMode = renderMode == null ? Form.RENDER_MODE_FORM : renderMode;

    //Default label mode depends on render mode
    labelMode = labelMode == null ? Form.LABEL_MODE_BEFORE : labelMode;
    //if (Form.RENDER_MODE_DISPLAY.equals(renderMode)) {
    //    labelMode = Form.LABEL_MODE_HIDDEN;
    //}

    boolean reuseStatus = reusingStatus == null || Boolean.valueOf(reusingStatus).booleanValue();
    boolean forceLabelMode = forceLabelModeParam != null && Boolean.valueOf(forceLabelModeParam).booleanValue();
    namespace = namespace == null ? "" : namespace;

    try {
        if (log.isDebugEnabled()) {
            log.debug("Printing form " + formToPaint.getId() + ". Mode: " + renderMode + ".");
        }
        String formLabelMode = formToPaint.getLabelMode();
        if (formLabelMode != null && !"".equals(formLabelMode)
                && !Form.LABEL_MODE_UNDEFINED.equals(formLabelMode)) {
            if (!forceLabelMode)
                labelMode = formLabelMode;
        }

        if (formValues != null) {
            getFormProcessor().clear(formToPaint, namespace);
            formStatusData = getFormProcessor().read(formToPaint, namespace, (Map) formValues);
        } else {
            formStatusData = getFormProcessor().read(formToPaint, namespace);
        }

        String displayMode = formToPaint.getDisplayMode();
        if (displayModeParam != null)
            displayMode = displayModeParam;
        FormDisplayInfo displayInfo = null;
        if (displayMode != null) {
            for (Iterator it = formToPaint.getFormDisplayInfos().iterator(); it.hasNext();) {
                FormDisplayInfo info = (FormDisplayInfo) it.next();
                if (info.getDisplayMode().equals(displayMode)) {
                    displayInfo = info;
                    break;
                }
            }
        }

        if (log.isDebugEnabled())
            log.debug("About to display form " + formToPaint.getId() + " in namespace " + namespace);
        display(formToPaint, namespace, displayMode, displayInfo, renderMode, labelMode, isSubForm, isMultiple);

    } catch (Exception e) {
        log.error("Error:", e);
        throw new FormatterException("Error", e);
    }
}

From source file:com.cloudera.sqoop.orm.ClassWriter.java

/**
 * Coerce a candidate name for an identifier into one which will
 * definitely compile./* ww w.  jav a2s  . c  o  m*/
 *
 * Ensures that the returned identifier matches [A-Za-z_][A-Za-z0-9_]*
 * and is not a reserved word.
 *
 * @param candidate A string we want to use as an identifier
 * @return A string naming an identifier which compiles and is
 *   similar to the candidate.
 */
public static String toIdentifier(String candidate) {
    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (char c : candidate.toCharArray()) {
        if (Character.isJavaIdentifierStart(c) && first) {
            // Ok for this to be the first character of the identifier.
            sb.append(c);
            first = false;
        } else if (Character.isJavaIdentifierPart(c) && !first) {
            // Ok for this character to be in the output identifier.
            sb.append(c);
        } else {
            // We have a character in the original that can't be
            // part of this identifier we're building.
            // If it's just not allowed to be the first char, add a leading '_'.
            // If we have a reasonable translation (e.g., '-' -> '_'), do that.
            // Otherwise, drop it.
            if (first && Character.isJavaIdentifierPart(c) && !Character.isJavaIdentifierStart(c)) {
                sb.append("_");
                sb.append(c);
                first = false;
            } else {
                // Try to map this to a different character or string.
                // If we can't just give up.
                String translated = getIdentifierStrForChar(c);
                if (null != translated) {
                    sb.append(translated);
                    first = false;
                }
            }
        }
    }

    String output = sb.toString();
    if (isReservedWord(output)) {
        // e.g., 'class' -> '_class';
        return "_" + output;
    }

    return output;
}

From source file:org.apache.axis2.jaxws.utility.JavaUtils.java

/**
 * @param Namespace//from w  w  w.  j  a  v a  2  s.  c o  m
 * @param apend underscore to keyword
 * @return String representing Namespace
 */
public static String getPackageFromNamespace(String namespace, boolean appendUnderscoreToKeyword) {
    // The following steps correspond to steps described in the JAXB Specification

    if (log.isDebugEnabled()) {
        log.debug("namespace (" + namespace + ")");
    }
    // Step 1: Scan off the host name
    String hostname = null;
    String path = null;
    try {
        URL url = new URL(namespace);
        hostname = url.getHost();
        path = url.getPath();
    } catch (MalformedURLException e) {
        // No FFDC code needed
        // If a MalformedURLException occurs, then
        // just simply get one string and put it in the hostname.
        // In such cases the path will remain empty.
        // This code is necessary so that we can process namespaces
        // like "urn:acme" or simply "sampleNamespace"
        if (namespace.indexOf(":") > -1) {
            // Brain-dead code to skip over the protocol
            hostname = namespace.substring(namespace.indexOf(":") + 1);
        } else {
            hostname = namespace;
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("hostname (" + hostname + ")");
        log.debug("path (" + path + ")");
    }

    // Step 3: Tokenize the host name using ":" and "/"
    StringTokenizer st = new StringTokenizer(hostname, ":/");

    ArrayList<String> wordList = new ArrayList<String>();

    //Read Hostname first.
    while (st != null && st.hasMoreTokens()) {
        wordList.add(st.nextToken());
    }
    //Read rest Of the path now
    if (path != null) {
        StringTokenizer pathst = new StringTokenizer(path, "/");
        while (pathst != null && pathst.hasMoreTokens()) {
            wordList.add(pathst.nextToken());
        }
    }
    String[] words = wordList.toArray(new String[0]);

    // Now do step 2: Strip off the trailing "." (i.e. strip off .html)
    if (words != null && words.length > 1) {
        String lastWord = words[words.length - 1];
        int index = lastWord.lastIndexOf('.');
        if (index > 0) {
            words[words.length - 1] = lastWord.substring(0, index);
        }
    }

    // Step 4: Unescape each escape sequence
    // TODO I don't know what to do here.

    // Step 5: If protocol is urn, replace - with . in the first word
    if (namespace.startsWith("urn:")) {
        words[0] = replace(words[0], "-", ".");
    }

    // Step 6: Tokenize the first word with "." and reverse the order. (the www is also removed).
    // TODO This is not exactly equivalent to the JAXB Rule.
    ArrayList<String> list = new ArrayList<String>();
    if (words.length > 0) {
        StringTokenizer st2 = new StringTokenizer(words[0], ".");

        while (st2.hasMoreTokens()) {
            // Add the strings so they are in reverse order
            list.add(0, st2.nextToken());
        }
    }

    // Remove www
    if (list.size() > 0) {
        String last = list.get(list.size() - 1);
        if (last.equals("www")) {
            list.remove(list.size() - 1);
        }
    }
    // Now each of words is represented by list
    for (int i = 1; i < words.length; i++) {
        list.add(words[i]);
    }

    // Step 7: lowercase each word
    for (int i = 0; i < list.size(); i++) {
        String word = list.remove(i);
        word = word.toLowerCase();
        list.add(i, word);
    }

    // Step 8: make into and an appropriate java word
    for (int i = 0; i < list.size(); i++) {
        String word = list.get(i);

        // 8a: Convert special characters to underscore
        // Convert non-java words to underscore.
        // TODO: Need to do this for all chars..not just hyphens
        word = replace(word, "-", "_");

        // 8b: Append _ to java keywords
        if (JavaUtils.isJavaKeyword(word)) {
            if (appendUnderscoreToKeyword) {
                word = word + "_"; // This is defined by the JAXB Spec
            } else {
                word = "_" + word; // Apparently wsimport can generate this style
            }
        }
        // 8c: prepend _ if first character cannot be the first character of a java identifier
        if (!Character.isJavaIdentifierStart(word.charAt(0))) {
            word = "_" + word;
        }

        list.set(i, word);
    }

    // Step 9: Concatenate and return
    String name = "";
    for (int i = 0; i < list.size(); i++) {
        if (i == 0) {
            name = list.get(0);
        } else {
            name = name + "." + list.get(i);
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("package name (" + name + ")");
    }
    return name;
}

From source file:org.apache.solr.search.ReturnFields.java

String getFieldName(QueryParsing.StrParser sp) throws ParseException {
    sp.eatws();/* w w w .  jav a  2  s  . c o m*/
    int id_start = sp.pos;
    char ch;
    if (sp.pos < sp.end && (ch = sp.val.charAt(sp.pos)) != '$' && Character.isJavaIdentifierStart(ch)) {
        sp.pos++;
        while (sp.pos < sp.end) {
            ch = sp.val.charAt(sp.pos);
            if (!Character.isJavaIdentifierPart(ch) && ch != '.' && ch != '-') {
                break;
            }
            sp.pos++;
        }
        return sp.val.substring(id_start, sp.pos);
    }

    return null;
}

From source file:com.wavemaker.commons.util.StringUtils.java

public static String toJavaIdentifier(String s, CharSequence prefixReplacementChar, char replacementChar,
        boolean checkKeyword) {

    if (ObjectUtils.isNullOrEmpty(s)) {
        throw new IllegalArgumentException("input cannot be null or empty");
    }//from  w w w  .j  a  v  a2 s.  c  o m

    String unquoted = unquote(s);
    if (!unquoted.isEmpty()) {
        s = unquoted;
    }

    // although '$' is ok, it causes issues with type generation
    // because of inner class confusion
    s = s.replace("$", "");

    if (s.isEmpty()) {
        s = "" + replacementChar;
    }

    StringBuilder rtn = new StringBuilder();

    if ((checkKeyword && (JAVA_KEYWORDS.contains(s.toLowerCase()) || HQL_KEYWORDS.contains(s.toLowerCase())))
            || !Character.isJavaIdentifierStart(s.charAt(0))) {
        rtn.append(prefixReplacementChar);
    }

    if (s.length() == 1) {
        if (rtn.length() > 0) {
            return rtn.toString();
        } else {
            return s;
        }
    }

    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (!Character.isJavaIdentifierPart(c)) {
            c = replacementChar;
        }
        rtn.append(c);
    }

    return rtn.toString();
}

From source file:org.apache.sqoop.orm.ClassWriter.java

/**
 * Attempt to coerce a candidate name that is not valid Java or Avro into validity based on a prefix.
 *
 * This does not ensure that the result will be Java or Avro compatible if the prefix is not a valid Java or Avro
 * character./* w  w w.  ja va  2 s. com*/
 *
 * @param candidate A string we want to use as an identifier
 * @param prefix A string which is added as a prefix
 * @return A string naming an identifier which compiles and is
 *   similar to the candidate.
 */
public static String toIdentifier(String candidate, String prefix) {
    StringBuilder sb = new StringBuilder();
    // boolean first = true;
    //sb.append("_");
    boolean first = true;
    for (char c : candidate.toCharArray()) {
        if (Character.isJavaIdentifierStart(c) && first) {
            // Ok for this to be the first character of the identifier.
            sb.append(c);
            first = false;
        } else if (Character.isJavaIdentifierPart(c) && !first) {
            // Ok for this character to be in the output identifier.
            sb.append(c);
        } else {
            // We have a character in the original that can't be
            // part of this identifier we're building.
            // If it's just not allowed to be the first char, add a leading '_'.
            // If we have a reasonable translation (e.g., '-' -> '_'), do that.
            // Otherwise, drop it.
            if (first && Character.isJavaIdentifierPart(c) && !Character.isJavaIdentifierStart(c)) {
                sb.append(prefix);
                sb.append(c);
                first = false;
            } else {
                // Try to map this to a different character or string.
                // If we can't just give up.
                String translated = getIdentifierStrForChar(c);
                if (null != translated) {
                    sb.append(translated);
                    first = false;
                }
            }
        }
    }
    return sb.toString();
}

From source file:org.jboss.forge.roaster.model.impl.PropertyImpl.java

@Override
public PropertySource<O> setName(final String name) {
    if (StringUtils.isBlank(name)) {
        throw new IllegalStateException("Property name cannot be null/empty/blank");
    }//from   www .j a  va2s .  c  om

    if (hasField()) {
        getField().setName(name);
    }

    final String oldName = this.name;
    final boolean visitDocTags = true;

    final ASTVisitor renameVisitor = new ASTVisitor(visitDocTags) {
        @Override
        public boolean visit(SimpleName node) {
            if (Objects.equals(oldName, node.getIdentifier())) {
                node.setIdentifier(name);
            }
            return super.visit(node);
        }

        @Override
        public boolean visit(TextElement node) {
            final String text = node.getText();
            if (!text.contains(oldName)) {
                return super.visit(node);
            }
            final int matchLength = oldName.length();
            final int textLength = text.length();
            final StringBuilder buf = new StringBuilder(text.length());
            final ParsePosition pos = new ParsePosition(0);

            while (pos.getIndex() < textLength) {
                final int index = pos.getIndex();
                final char c = text.charAt(index);
                if (Character.isJavaIdentifierStart(c)) {
                    final int next = index + matchLength;

                    if (next <= textLength && Objects.equals(oldName, text.substring(index, next))) {
                        buf.append(name);
                        pos.setIndex(next);
                        continue;
                    }
                }
                buf.append(c);
                pos.setIndex(index + 1);
            }

            node.setText(buf.toString());
            return super.visit(node);
        }
    };

    if (isAccessible()) {
        final MethodSource<O> accessor = getAccessor();
        final String prefix = accessor.getReturnType().isType(boolean.class) ? "is" : "get";
        accessor.setName(methodName(prefix, name));
        ((MethodDeclaration) accessor.getInternal()).accept(renameVisitor);
    }

    if (isMutable()) {
        final MethodSource<O> mutator = getMutator();
        mutator.setName(methodName("set", name));
        ((MethodDeclaration) mutator.getInternal()).accept(renameVisitor);
    }

    this.name = name;

    return this;
}