Example usage for java.lang Character isLetterOrDigit

List of usage examples for java.lang Character isLetterOrDigit

Introduction

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

Prototype

public static boolean isLetterOrDigit(int codePoint) 

Source Link

Document

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

Usage

From source file:com.redhat.rhn.common.util.StringUtil.java

/**
 * Convert the passed in string to a valid java method name. This basically
 * capitalizes each word and removes all word delimiters.
 * @param strIn The string to convert//from  w w w . j a v  a  2s  . c om
 * @return The converted string
 */
public static String beanify(String strIn) {
    String str = strIn.trim();
    StringBuilder result = new StringBuilder(str.length());
    boolean wasWhitespace = false;

    for (int i = 0, j = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (Character.isLetterOrDigit(c)) {
            if (wasWhitespace) {
                c = Character.toUpperCase(c);
                wasWhitespace = false;
            }
            result.insert(j, c);
            j++;
            continue;
        }
        wasWhitespace = true;
    }
    return result.toString();
}

From source file:org.chililog.server.common.TextTokenizer.java

/**
 * <p>//  www . j a v  a 2s.  c o  m
 * Tokenizes text to get keywords
 * </p>
 * <p>
 * We use lucene <code>StandardAnalyzer</code> with a bit of spice. We want to break up domain names, class names
 * and emails so we have to do some extra parsing.
 * </p>
 * <p>
 * Lucene parsing:
 * <ul>
 * <li>"email@address.com" = ["email@address", "com"]</li>
 * <li>"com.chililog.server.common.ChiliLogExceptionTest" = ["com.chililog.server.common", "chililogexceptiontest"]</li>
 * </ul>
 * </p>
 * <p>
 * We have not used regular expression because it is slow. We have implemented this as a singleton so that in the
 * future we can allow user customization.
 * </p>
 * 
 * @param text
 *            Text to extract keywords
 * @param maxKeywords
 *            Maximum number of keywords to extract. If < 0, then no limit will be used.
 * @return Array of keywords
 * @throws IOException
 */
public ArrayList<String> tokenize(String text, long maxKeywords) throws IOException {
    ArrayList<String> tokens = new ArrayList<String>();

    if (StringUtils.isEmpty(text) || maxKeywords == 0) {
        return tokens;
    }

    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
    HashMap<String, String> lookup = new HashMap<String, String>();
    TokenStream stream = analyzer.tokenStream("field", new StringReader(text));

    StringBuilder sb = new StringBuilder();
    TermAttribute termAttribute = stream.getAttribute(TermAttribute.class);
    while (stream.incrementToken()) {
        char[] termBuffer = termAttribute.termBuffer();
        int length = termAttribute.termLength();

        boolean doSplit = true;

        // Check if we want to split
        if (Character.isDigit(termBuffer[0])) {
            doSplit = false;
        } else {
            for (int j = 0; j < length; j++) {
                char c = termBuffer[j];
                if (!Character.isLetterOrDigit(c) && c != '.' && c != '@') {
                    doSplit = false;
                    break;
                }
            }
        }

        if (doSplit) {
            sb.setLength(0);
            for (int i = 0; i < length; i++) {
                char c = termBuffer[i];
                if (c == '.' || c == '@') {
                    if (!addToken(tokens, lookup, sb.toString(), maxKeywords)) {
                        return tokens;
                    }
                    sb.setLength(0);
                } else {
                    sb.append(c);
                }
            }

            // Add last part
            if (!addToken(tokens, lookup, sb.toString(), maxKeywords)) {
                return tokens;
            }
        } else {
            // No splitting, just add term
            if (!addToken(tokens, lookup, termAttribute.term(), maxKeywords)) {
                return tokens;
            }
        }
    }

    return tokens;
}

From source file:org.getobjects.foundation.NSPropertyListGenerator.java

public boolean appendString(String _s, StringBuilder _sb, int _indent) {
    if (_s == null)
        return false;

    int len = _s.length();
    if (len == 0) {
        _sb.append("\"\"");
        return true;
    }//from w ww.j av a2  s .  c o m

    /* special processing for special plist identifiers */

    if (len == 2 && _s.equals("NO")) {
        _sb.append("\"NO\"");
        return true;
    } else if (len == 3 && (_s.equals("YES") || _s.equals("nil"))) {
        _sb.append('"');
        _sb.append(_s);
        _sb.append('"');
        return true;
    } else if (len == 4 && (_s.equals("true") || _s.equals("null"))) {
        _sb.append('"');
        _sb.append(_s);
        _sb.append('"');
        return true;
    }

    /* regular processing, scan for string which do not require quoting */

    boolean didQuote = false;

    if (Character.isDigit(_s.charAt(0))) {
        didQuote = true;
        _sb.append('"');
    }

    int i;
    for (i = 0; i < len; i++) {
        char c = _s.charAt(i);

        /* we just consider ASCII alnum */
        if (!didQuote && (c < 256 && Character.isLetterOrDigit(c)))
            continue; /* we are still valid w/o quotes */

        /* OK, we need to quote or we are already quoting */

        if (!didQuote) {
            /* add stuff which was OK so far */
            _sb.append('"');
            if (i > 0)
                _sb.append(_s.substring(0, i));
            didQuote = true;
        }

        /* process character */

        switch (c) {
        case '\n':
            _sb.append("\\n");
            break;
        case '\t':
            _sb.append("\\t");
            break;
        case '\r':
            _sb.append("\\r");
            break;
        case '\\':
            _sb.append("\\\\");
            break;
        case '"':
            _sb.append("\\\"");
            break;
        case '\'':
            _sb.append("\\'");
            break;
        default:
            _sb.append(c);
            break;
        }
    }

    if (didQuote)
        _sb.append('"');
    else
        _sb.append(_s);

    return true;
}

From source file:org.radeox.filter.LinkTestFilter.java

public void handleMatch(StringBuffer buffer, MatchResult result, FilterContext context) {
    RenderEngine engine = context.getRenderContext().getRenderEngine();

    if (engine instanceof WikiRenderEngine) {
        WikiRenderEngine wikiEngine = (WikiRenderEngine) engine;
        Writer writer = new StringBufferWriter(buffer);

        String name = result.group(1);
        if (name != null) {
            // User probably wrote [http://radeox.org] instead of
            // http://radeox.org
            if (name.indexOf("http://") != -1) //$NON-NLS-1$
            {//from   w  ww.  j  a  v  a  2s .c o m
                try {
                    writer.write(Messages.getString("LinkTestFilter.2")); //$NON-NLS-1$
                } catch (IOException e) {
                    // Do nothing. Give up.
                }
                return;
            }

            // Is there an alias like [alias|link] ?
            int pipeIndex = name.indexOf('|');
            String alias = ""; //$NON-NLS-1$
            if (-1 != pipeIndex) {
                alias = Encoder.unescape(name.substring(0, pipeIndex).trim());
                name = name.substring(pipeIndex + 1).trim();
            }

            Pattern p = Pattern.compile("(.*)(?<!\\&)\\#(.*)"); //$NON-NLS-1$
            Matcher m = p.matcher(name);
            String hash = ""; //$NON-NLS-1$

            if (m.matches()) {
                hash = Encoder.unescape(m.group(2));
                char[] hashChars = hash.toCharArray();
                int end = 0;
                for (int i = 0; i < hashChars.length; i++) {
                    if (Character.isLetterOrDigit(hashChars[i])) {
                        hashChars[end++] = hashChars[i];
                    }
                }
                if (end > 0) {
                    hash = new String(hashChars, 0, end);
                }

                name = m.group(1);
            }

            int colonIndex = name.indexOf(':');
            // typed link ?
            if (-1 != colonIndex) {
                // for now throw away the type information
                name = name.substring(colonIndex + 1);
            }

            int atIndex = name.lastIndexOf('@');
            // InterWiki link ?
            if (-1 != atIndex) {
                String extSpace = Encoder.unescape(name.substring(atIndex + 1));
                // known external space ?
                InterWiki interWiki = InterWiki.getInstance();
                if (interWiki.contains(extSpace)) {

                    name = Encoder.unescape(name.substring(0, atIndex));
                    String view;
                    if (-1 != pipeIndex) {
                        view = alias;
                    } else {
                        view = name + "@" + extSpace; //$NON-NLS-1$
                    }

                    try {
                        if (name.indexOf('@') > -1) {
                            addAtSignError(buffer);
                        } else if (hash.length() > 0) {
                            interWiki.expand(writer, extSpace, name, view, hash);
                        } else {
                            interWiki.expand(writer, extSpace, name, view);
                        }
                    } catch (IOException e) {
                        log.debug("InterWiki " + extSpace + " not found."); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                } else {
                    buffer.append("&#91;<span class=\"error\">"); //$NON-NLS-1$
                    buffer.append(result.group(1));
                    buffer.append("?</span>&#93;"); //$NON-NLS-1$
                }
            } else {
                // internal link

                name = Encoder.unescape(name);

                if (name.indexOf('@') > -1) {
                    addAtSignError(buffer);
                } else if (wikiEngine.exists(name) || ("".equals(name) && !("".equals(hash)))) //$NON-NLS-1$ //$NON-NLS-2$
                {
                    if ("".equals(name) && !("".equals(hash))) { //$NON-NLS-1$ //$NON-NLS-2$
                        name = (String) context.getRenderContext()
                                .get("uk.ac.cam.caret.sakai.rwiki.service.api.model.RWikiObject.name"); //$NON-NLS-1$
                    }

                    String view = getWikiView(name, hash);
                    if (-1 != pipeIndex) {
                        view = alias;
                    }

                    // Do not add hash if an alias was given
                    if (hash.length() > 0) {
                        wikiEngine.appendLink(buffer, name, view, hash);
                    } else {
                        wikiEngine.appendLink(buffer, name, view);
                    }
                } else if (wikiEngine.showCreate()) {

                    String view = getWikiView(name, ""); //$NON-NLS-1$
                    if (-1 != pipeIndex) {
                        view = alias;
                    }
                    wikiEngine.appendCreateLink(buffer, name, view);
                } else {
                    // cannot display/create wiki, so just display the text
                    buffer.append(Encoder.escape(name));
                }
            }
        } else {
            buffer.append(Encoder.escape(result.group(0)));
        }
    }
}

From source file:net.sf.jasperreports.engine.util.JRResourcesUtil.java

private static boolean protocolValid(String protocol) {
    int length = protocol.length();
    if (length < 1) {
        return false;
    }//w  w  w. j  av a2  s . co  m

    if (!Character.isLetter(protocol.charAt(0))) {
        return false;
    }

    for (int i = 1; i < length; ++i) {
        char c = protocol.charAt(i);
        if (!(Character.isLetterOrDigit(c) || c == '+' || c == '-' || c == '.')) {
            return false;
        }
    }

    return true;
}

From source file:io.github.marktony.espresso.mvp.addpackage.AddPackageFragment.java

@Nullable
@Override// w ww.j a  v a 2s .  co  m
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_add_package, container, false);

    initViews(view);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            hideImm();

            String name = editTextName.getText().toString();
            String number = editTextNumber.getText().toString().replaceAll("\\s*", "");

            // Check the length of the input number
            if (number.length() < 5 || number.replace(" ", "").isEmpty()) {
                showNumberError();
                return;
            }

            // Check the number if only contains numbers and characters.
            for (char c : number.toCharArray()) {
                if (!Character.isLetterOrDigit(c)) {
                    showNumberError();
                    return;
                }
            }

            // If the user has not input anything, just use the default name:
            // (Package(In default language environment) / (In Chinese environment))
            // + the beginning 4 chars of the package number
            if (name.isEmpty()) {
                name = getString(R.string.package_name_default_pre) + number.substring(0, 4);
            }

            editTextName.setText(name);
            // Set a random color as avatar background
            presenter.savePackage(editTextNumber.getText().toString(), name,
                    colorRes[new Random().nextInt(colorRes.length)]);
        }
    });

    textViewScanCode.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkPermissionOrToScan();
        }
    });

    String action = getActivity().getIntent().getAction();
    if (action != null && action.equals(ACTION_SCAN_CODE)) {
        checkPermissionOrToScan();
    }

    setHasOptionsMenu(true);

    return view;
}

From source file:de.micromata.genome.gwiki.plugin.keywordsmarttags_1_0.GWikiFragmentKeywordHtml.java

protected void patch(KeyWordRanges kranges, String html,
        Map.Entry<String, Pair<Pattern, List<GWikiElementInfo>>> me) {
    if (StringUtils.isBlank(html) == true) {
        return;/*from   w ww .  ja  v a 2 s  .co m*/
    }
    Matcher m = me.getValue().getFirst().matcher(html);
    while (m.find() == true) {
        int sidx = m.start();
        int eidx = m.end();
        if (sidx != 0) {
            if (Character.isLetterOrDigit(html.charAt(sidx - 1)) == true) {
                continue;
            }
        }
        if (eidx < html.length() - 1) {
            if (Character.isLetterOrDigit(html.charAt(eidx)) == true) {
                continue;
            }
        }
        kranges.addIntersect(sidx, eidx, me.getValue().getSecond());
    }
}

From source file:com.xie.javacase.json.XMLTokener.java

/**
 * Return the next entity. These entities are translated to Characters:
 *     <code>&amp;  &apos;  &gt;  &lt;  &quot;</code>.
 * @param a An ampersand character./*from w  w w .ja  v a  2  s . com*/
 * @return  A Character or an entity String if the entity is not recognized.
 * @throws org.json.JSONException If missing ';' in XML entity.
 */
public Object nextEntity(char a) throws JSONException {
    StringBuffer sb = new StringBuffer();
    for (;;) {
        char c = next();
        if (Character.isLetterOrDigit(c) || c == '#') {
            sb.append(Character.toLowerCase(c));
        } else if (c == ';') {
            break;
        } else {
            throw syntaxError("Missing ';' in XML entity: &" + sb);
        }
    }
    String s = sb.toString();
    Object e = entity.get(s);
    return e != null ? e : a + s + ";";
}

From source file:stanford.androidlib.xml.XMLTokener.java

/**
 * Return the next entity. These entities are translated to Characters:
 *     ... ./*from   w  w  w.j a  v a 2  s .c om*/
 * @param ampersand An ampersand character.
 * @return  A Character or an entity String if the entity is not recognized.
 * @throws JSONException If missing ';' in XML entity.
 */
public Object nextEntity(char ampersand) throws JSONException {
    StringBuffer sb = new StringBuffer();
    for (;;) {
        char c = next();
        if (Character.isLetterOrDigit(c) || c == '#') {
            sb.append(Character.toLowerCase(c));
        } else if (c == ';') {
            break;
        } else {
            throw syntaxError("Missing ';' in XML entity: &" + sb);
        }
    }
    String string = sb.toString();
    Object object = entity.get(string);
    return object != null ? object : ampersand + string + ";";
}

From source file:org.apache.maven.shared.osgi.DefaultMaven2OsgiConverter.java

/**
 * Get the symbolic name as groupId + "." + artifactId, with the following exceptions
 * <ul>/*  w  w  w.j a va2s . co  m*/
 * <li>if artifact.getFile is not null and the jar contains a OSGi Manifest with
 * Bundle-SymbolicName property then that value is returned</li>
 * <li>if groupId has only one section (no dots) and artifact.getFile is not null then the
 * first package name with classes is returned. eg. commons-logging:commons-logging ->
 * org.apache.commons.logging</li>
 * <li>if artifactId is equal to last section of groupId then groupId is returned. eg.
 * org.apache.maven:maven -> org.apache.maven</li>
 * <li>if artifactId starts with last section of groupId that portion is removed. eg.
 * org.apache.maven:maven-core -> org.apache.maven.core</li>
 * </ul>
 */
public String getBundleSymbolicName(Artifact artifact) {
    if ((artifact.getFile() != null) && artifact.getFile().isFile()) {
        Analyzer analyzer = new Analyzer();

        JarFile jar = null;
        try {
            jar = new JarFile(artifact.getFile(), false);

            if (jar.getManifest() != null) {
                String symbolicNameAttribute = jar.getManifest().getMainAttributes()
                        .getValue(Analyzer.BUNDLE_SYMBOLICNAME);
                Map bundleSymbolicNameHeader = analyzer.parseHeader(symbolicNameAttribute);

                Iterator it = bundleSymbolicNameHeader.keySet().iterator();
                if (it.hasNext()) {
                    return (String) it.next();
                }
            }
        } catch (IOException e) {
            throw new ManifestReadingException(
                    "Error reading manifest in jar " + artifact.getFile().getAbsolutePath(), e);
        } finally {
            if (jar != null) {
                try {
                    jar.close();
                } catch (IOException e) {
                }
            }
        }
    }

    int i = artifact.getGroupId().lastIndexOf('.');
    if ((i < 0) && (artifact.getFile() != null) && artifact.getFile().isFile()) {
        String groupIdFromPackage = getGroupIdFromPackage(artifact.getFile());
        if (groupIdFromPackage != null) {
            return groupIdFromPackage;
        }
    }
    String lastSection = artifact.getGroupId().substring(++i);
    if (artifact.getArtifactId().equals(lastSection)) {
        return artifact.getGroupId();
    }
    if (artifact.getArtifactId().startsWith(lastSection)) {
        String artifactId = artifact.getArtifactId().substring(lastSection.length());
        if (Character.isLetterOrDigit(artifactId.charAt(0))) {
            return getBundleSymbolicName(artifact.getGroupId(), artifactId);
        } else {
            return getBundleSymbolicName(artifact.getGroupId(), artifactId.substring(1));
        }
    }
    return getBundleSymbolicName(artifact.getGroupId(), artifact.getArtifactId());
}