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:com.phoenixnap.oss.ramlapisync.naming.NamingHelper.java

/**
 * Utility method to check if a string can be used as a valid class name
 * /*  w w  w  . j  a v a  2s.  c o  m*/
 * @param input String to check
 * @return true if valid
 */
public static boolean isValidJavaClassName(String input) {
    if (!StringUtils.hasText(input)) {
        return false;
    }
    if (!Character.isJavaIdentifierStart(input.charAt(0))) {
        return false;
    }
    if (input.length() > 1) {
        for (int i = 1; i < input.length(); i++) {
            if (!Character.isJavaIdentifierPart(input.charAt(i))) {
                return false;
            }
        }
    }
    return true;
}

From source file:com.google.testing.pogen.generator.test.java.NameConverter.java

/**
 * Converts the specified string to a proper Java identifier.
 * // w w w.  j a v  a  2 s.  co  m
 * @param str the string to be converted
 * @return the Java identifier converted from the specified string
 */
public static String getJavaIdentifier(String str) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(str));

    StringBuilder result = new StringBuilder();
    char ch = str.charAt(0);
    result.append(Character.isJavaIdentifierStart(ch) ? ch : REPLACE);

    for (int i = 1; i < str.length(); i++) {
        ch = str.charAt(i);
        result.append(Character.isJavaIdentifierPart(ch) ? ch : REPLACE);
    }
    return result.toString();
}

From source file:org.gradle.groovy.scripts.UriScriptSource.java

/**
 * Returns the class name for use for this script source.  The name is intended to be unique to support mapping
 * class names to source files even if many sources have the same file name (e.g. build.gradle).
 *//*from   w ww.ja  v a 2  s.  com*/
public String getClassName() {
    if (className == null) {
        URI sourceUri = resource.getURI();
        String name = StringUtils.substringBeforeLast(StringUtils.substringAfterLast(sourceUri.toString(), "/"),
                ".");
        StringBuilder className = new StringBuilder(name.length());
        for (int i = 0; i < name.length(); i++) {
            char ch = name.charAt(i);
            if (Character.isJavaIdentifierPart(ch)) {
                className.append(ch);
            } else {
                className.append('_');
            }
        }
        if (!Character.isJavaIdentifierStart(className.charAt(0))) {
            className.insert(0, '_');
        }
        className.setLength(Math.min(className.length(), 30));
        className.append('_');
        String path = sourceUri.toString();
        className.append(HashUtil.createCompactMD5(path));

        this.className = className.toString();
    }

    return className;
}

From source file:org.apache.qpid.server.util.StringUtil.java

/**
 * Builds a legal java name, based on manager name if possible,
 * this is unique for the given input.//from   ww w  . ja va 2s. c o  m
 *
 * @param managerName
 * @return unique java name
 */
public String createUniqueJavaName(String managerName) {
    StringBuilder builder = new StringBuilder();
    boolean initialChar = true;
    for (int i = 0; i < managerName.length(); i++) {
        char c = managerName.charAt(i);
        if ((initialChar && Character.isJavaIdentifierStart(c))
                || (!initialChar && Character.isJavaIdentifierPart(c))) {
            builder.append(c);
            initialChar = false;
        }
    }
    if (builder.length() > 0) {
        builder.append("_");
    }
    builder.append(DigestUtils.md5Hex(managerName));
    return builder.toString();
}

From source file:de.jcup.egradle.core.util.GradleResourceLinkCalculator.java

private GradleHyperLinkResult internalCreateLink(String line, int offsetInLine) {
    /* e.g. abc defg Test abc */
    /* ^-- Test must be identified */
    String rightSubString = line.substring(offsetInLine);
    StringBuilder content = new StringBuilder();
    for (char c : rightSubString.toCharArray()) {
        if (Character.isWhitespace(c)) {
            break;
        }//from  w  w w .jav  a 2  s  .  c  om
        if (c == '{') {
            break;
        }
        if (c == ',') {
            break;
        }
        if (c == '(') {
            break;
        }
        if (c == ')') {
            break;
        }
        if (c == '[') {
            break;
        }
        if (c == '<') {
            break;
        }
        if (c == '>') {
            break;
        }
        if (c == '.') {
            break;
        }
        if (!Character.isJavaIdentifierPart(c)) {
            return null;
        }
        content.append(c);
    }
    if (StringUtils.isBlank(content)) {
        return null;
    }
    String leftSubString = line.substring(0, offsetInLine);
    char[] leftCharsArray = leftSubString.toCharArray();

    ArrayUtils.reverse(leftCharsArray);
    int startPos = offsetInLine;
    for (char c : leftCharsArray) {
        if (c == '(') {
            break;
        }
        if (c == '<') {
            break;
        }
        if (c == '.') {
            break;
        }
        if (Character.isWhitespace(c)) {
            break;
        }
        if (!Character.isJavaIdentifierPart(c)) {
            return null;
        }
        startPos--;
        content.insert(0, c);
    }
    String linkContent = content.toString();

    char firstChar = linkContent.charAt(0);
    if (!Character.isJavaIdentifierStart(firstChar)) {
        return null;
    }
    /*
     * currently this calculator only supports correct Type syntax means
     * first char MUST be upper cased
     */
    if (!Character.isUpperCase(firstChar)) {
        return null;
    }
    GradleHyperLinkResult result = new GradleHyperLinkResult();
    result.linkOffsetInLine = startPos;
    result.linkContent = linkContent;
    result.linkLength = linkContent.length();
    return result;
}

From source file:Strings.java

public static String getJavaIdentifier(String candidateID) {
    int len = candidateID.length();
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < len; i++) {
        char ch = candidateID.charAt(i);
        boolean good = i == 0 ? Character.isJavaIdentifierStart(ch) : Character.isJavaIdentifierPart(ch);
        if (good) {
            buf.append(ch);/*from ww w  .j a v  a2 s  .  c  o m*/
        } else {
            buf.append('_');
        }
    }
    return buf.toString();
}

From source file:org.talend.dataprep.api.dataset.row.RowMetadataUtils.java

private static String toAvroFieldName(ColumnMetadata column) {
    final char[] chars = column.getName().toCharArray();
    final StringBuilder columnName = new StringBuilder();
    for (int i = 0; i < chars.length; i++) {
        final char currentChar = chars[i];
        if (i == 0) {
            if (!Character.isLetter(currentChar)) {
                columnName.append(DATAPREP_FIELD_PREFIX);
            }//from w w w. jav a2s  . c  o  m
            columnName.append(currentChar);
        }
        if (i > 0) {
            if (!Character.isJavaIdentifierPart(currentChar)) {
                columnName.append('_');
            } else {
                columnName.append(currentChar);
            }
        }
    }
    return columnName.toString();
}

From source file:org.openmrs.module.reporting.report.util.SqlUtils.java

/**
 * Binds the given paramMap to the query by replacing all named parameters (e.g. :paramName)
 * with their corresponding values in the parameter map. TODO copied from
 * HibernateCohortQueryDAO/*from ww  w  .  j  av  a2  s. c  o m*/
 * 
 * @param connection
 * @param query
 * @param paramMap
 * @throws SQLException 
 */
@SuppressWarnings("unchecked")
public static PreparedStatement prepareStatement(Connection connection, String query,
        Map<String, Object> paramMap) throws SQLException {

    PreparedStatement statement;
    if (!isSelectQuery(query)) {
        throw new IllegalDatabaseAccessException();
    }
    boolean containParams = query.indexOf(":") > 0;
    if (containParams) {

        // the first process is replacing the :paramName with ?
        // implementation taken from: http://www.javaworld.com/javaworld/jw-04-2007/jw-04-jdbc.html?page=2
        Map<String, List<Integer>> params = new HashMap<String, List<Integer>>();
        StringBuffer parsedQuery = new StringBuffer();

        int index = 1;
        for (int i = 0; i < query.length(); i++) {

            // we can use charAt here, but we might need to append "(?, ?, ?)" when the where parameter is a list
            // http://stackoverflow.com/questions/178479/alternatives-for-java-sql-preparedstatement-in-clause-issue
            // http://www.javaranch.com/journal/200510/Journal200510.jsp#a2
            String s = query.substring(i, i + 1);

            if (StringUtils.equals(s, ":") && i + 1 < query.length()
                    && Character.isJavaIdentifierStart(query.charAt(i + 1))) {
                // we already make sure that (i + 1) is a valid character, now check the next one after (i + 1)
                int j = i + 2;
                while (j < query.length() && Character.isJavaIdentifierPart(query.charAt(j)))
                    j++;

                String name = query.substring(i + 1, j);
                Object paramValue = paramMap.get(name);

                // are we dealing with collection or not
                int size = 1;
                if (paramValue != null)
                    if (Cohort.class.isAssignableFrom(paramValue.getClass()))
                        size = ((Cohort) paramValue).getSize();
                    else if (Collection.class.isAssignableFrom(paramValue.getClass()))
                        size = ((Collection<?>) paramValue).size();

                // skip until the end of the param name
                i += name.length();

                String[] sqlParams = new String[size];
                for (int k = 0; k < sqlParams.length; k++) {
                    sqlParams[k] = "?";
                    // record the location of the parameter in the sql statemet
                    List<Integer> indexList = params.get(name);
                    if (indexList == null) {
                        indexList = new LinkedList<Integer>();
                        params.put(name, indexList);
                    }
                    indexList.add(new Integer(index));
                    index++;
                }
                s = StringUtils.join(sqlParams, ",");

                // for the "IN" query, we need to add bracket
                if (size > 1)
                    s = "(" + s + ")";
            }

            parsedQuery.append(s);
        }

        // the query string contains parameters, re-create the prepared statement with the new parsed query string
        statement = connection.prepareStatement(parsedQuery.toString());

        // Iterate over parameters and bind them to the Query object
        for (String paramName : paramMap.keySet()) {

            Object paramValue = paramMap.get(paramName);

            // Indicates whether we should bind this parameter in the query 
            // Make sure parameter value is not null
            if (paramValue == null) {
                // TODO Should try to convert 'columnName = null' to 'columnName IS NULL'  
                throw new ParameterException("Cannot bind an empty value to parameter " + paramName + ". "
                        + "Please provide a real value or use the 'IS NULL' constraint in your query (e.g. 'table.columnName IS NULL').");
            }

            int i = 0;
            List<Integer> positions = params.get(paramName);
            if (positions != null) {
                // Cohort (needs to be first, otherwise it will resolve as OpenmrsObject)
                if (Cohort.class.isAssignableFrom(paramValue.getClass())) {
                    Cohort cohort = (Cohort) paramValue;
                    for (Integer patientId : cohort.getMemberIds()) {
                        statement.setInt(positions.get(i++), patientId);
                    }
                }
                // OpenmrsObject (e.g. Location)
                else if (OpenmrsObject.class.isAssignableFrom(paramValue.getClass())) {
                    for (Integer position : positions) {
                        statement.setInt(position, ((OpenmrsObject) paramValue).getId());
                    }
                }
                // List<OpenmrsObject> (e.g. List<Location>)
                else if (List.class.isAssignableFrom(paramValue.getClass())) {
                    // If first element in the list is an OpenmrsObject
                    if (OpenmrsObject.class.isAssignableFrom(((List<?>) paramValue).get(0).getClass())) {
                        List<Integer> openmrsObjectIds = SqlUtils
                                .openmrsObjectIdListHelper((List<OpenmrsObject>) paramValue);
                        for (Integer openmrsObjectId : openmrsObjectIds) {
                            statement.setInt(positions.get(i++), openmrsObjectId);
                        }
                    }
                    // a List of Strings, Integers?
                    else {
                        List<String> strings = SqlUtils.objectListHelper((List<Object>) paramValue);
                        for (String string : strings) {
                            statement.setString(positions.get(i++), string);
                        }
                    }
                }
                // java.util.Date and subclasses
                else if (paramValue instanceof Date) {
                    for (Integer position : positions) {
                        statement.setDate(position, new java.sql.Date(((Date) paramValue).getTime()));
                    }
                } else if (paramValue instanceof Integer || paramValue instanceof Long) {
                    for (Integer position : positions) {
                        statement.setLong(position, (Integer) paramValue);
                    }
                } else if (paramValue instanceof Boolean) {
                    for (Integer position : positions) {
                        statement.setBoolean(position, (Boolean) paramValue);
                    }
                }
                // String, et al (this might break since this is a catch all for all other classes)
                else {
                    for (Integer position : positions) {
                        statement.setString(position, new String(paramValue.toString()));
                    }
                }
            }
        }
    } else
        statement = connection.prepareStatement(query);

    return statement;
}

From source file:org.jboss.tools.maven.gstring.ProcessTemplateFilesMojo.java

public void execute() throws MojoExecutionException {
    if ((this.files == null || this.files.isEmpty()) && (this.resources == null || this.resources.isEmpty())) {
        return;/*from www  . ja  v a  2  s  . com*/
    }

    if (this.symbols == null) {
        this.symbols = new HashMap<String, Object>();
    }
    if (this.symbols.containsKey("project")) {
        throw new MojoExecutionException(
                "'project' is a protected symbol (set to ${project}). Please use something else.");
    }
    this.symbols.put("project", this.project);

    List<String> badSymbols = new ArrayList<String>();
    for (String symbol : this.symbols.keySet()) {
        if (!Character.isJavaIdentifierStart(symbol.charAt(0))) {
            badSymbols.add(symbol);
            break;
        }
        for (int i = 1; i < symbol.length(); i++) {
            if (!Character.isJavaIdentifierPart(symbol.charAt(i))) {
                badSymbols.add(symbol);
                break;
            }
        }
    }
    if (!badSymbols.isEmpty()) {
        throw new MojoExecutionException("symbols have to be valid Java qualifiers " + badSymbols);
    }

    if (!this.outputDirectory.exists()) {
        this.outputDirectory.mkdirs();
    }

    GStringTemplateEngine templateEngine = new GStringTemplateEngine();
    if (this.files != null) {
        for (String path : this.files) {
            File file = new File(path);
            if (!file.exists()) {
                throw new MojoExecutionException("File " + file + " does not exist.");
            }

            if (!file.isFile()) {
                throw new MojoExecutionException("File " + file + " is not a valid template file.");
            }

            FileInputStream inputStream = null;
            try {
                inputStream = new FileInputStream(file);
                processInput(templateEngine, path, file.getName(), inputStream);
            } catch (FileNotFoundException e) {
                throw new MojoExecutionException("Can't read file " + file, e);
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        }
    }

    if (this.resources != null) {
        for (String resourcePath : this.resources) {
            String fileName = new File(resourcePath).getName();
            final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
            if (inputStream == null) {
                throw new MojoExecutionException(resourcePath + " does not exist.");
            }

            try {
                processInput(templateEngine, resourcePath, fileName, inputStream);
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        }
    }
}

From source file:info.novatec.testit.livingdoc.util.NameUtils.java

public static boolean isJavaIdentifier(String s) {
    if (!Character.isJavaIdentifierStart(s.codePointAt(0))) {
        return false;
    }//from  w  ww  .j a  v a2 s  .c  om

    for (int i = 1; i < s.length(); i++) {
        if (!Character.isJavaIdentifierPart(s.codePointAt(i))) {
            return false;
        }
    }
    return true;
}