Example usage for java.text CharacterIterator DONE

List of usage examples for java.text CharacterIterator DONE

Introduction

In this page you can find the example usage for java.text CharacterIterator DONE.

Prototype

char DONE

To view the source code for java.text CharacterIterator DONE.

Click Source Link

Document

Constant that is returned when the iterator has reached either the end or the beginning of the text.

Usage

From source file:Characters.java

/**
 * Removes all characters that are not considered <a href="http://www.w3.org/TR/2000/REC-xml-20001006#charsets">XML
 * characters </a> from the input.
 * /*  ww  w . j  av  a 2s. c o m*/
 * @param input the input to filter
 * @return the input with all non-XML characters removed
 */
public static String filterXML(String input) {
    // Null inputs return an empty string.
    if (input == null) {
        return "";
    }

    // trim() removes all whitespace, not only spaces.
    String _input = input.trim();

    // Empty inputs return an empty string.
    if (_input.equals((""))) {
        return "";
    }

    // This StringBuilder will hold the result.
    StringBuilder result = new StringBuilder(_input.length());

    // This StringCharacterIterator will iterate over the input.
    StringCharacterIterator iterator = new StringCharacterIterator(_input);

    // Iterate over the input.
    for (char aChar = iterator.first(); aChar != CharacterIterator.DONE; aChar = iterator.next()) {
        // Determine if this is a valid XML Character.
        if ((aChar == '\u0009') || (aChar == '\n') || (aChar == '\r')
                || (('\u0020' <= aChar) && (aChar <= '\uD7FF'))
                || (('\uE000' <= aChar) && (aChar <= '\uFFFD'))) {
            result.append(aChar);
        }
    }
    if (result.length() > _input.length()) {
        return result.toString();
    }
    // (otherwise...)
    return _input;
}

From source file:info.magnolia.cms.taglibs.util.BaseImageTag.java

/**
 * Replace any special characters that are not letters or numbers with a replacement string. The two exceptions are
 * '-' and '_', which are allowed.//from w ww .jav a2 s.  co  m
 */
public String convertToSimpleString(String string) {

    final StringBuffer result = new StringBuffer();

    final StringCharacterIterator iterator = new StringCharacterIterator(string);
    char character = iterator.current();
    while (character != CharacterIterator.DONE) {
        int charType = Character.getType(character);
        if (charType == Character.SPACE_SEPARATOR) {
            result.append("-");
        } else if ((charType != Character.UPPERCASE_LETTER) && (charType != Character.LOWERCASE_LETTER)
                && (charType != Character.DECIMAL_DIGIT_NUMBER) && (charType != Character.CONNECTOR_PUNCTUATION)
                && (charType != Character.DASH_PUNCTUATION)) {
            result.append("u" + (int) character);

        } else {
            // the char is not a special one
            // add it to the result as is
            result.append(character);
        }
        character = iterator.next();
    }
    return result.toString();
}

From source file:org.mortbay.jetty.load.generator.jenkins.result.LoadResultProjectAction.java

public static List<RunInformations> searchRunInformations(String jettyVersion, ElasticHost elasticHost,
        int maxResult) throws IOException {

    String originalJettyVersion = jettyVersion;

    // jettyVersion 9.4.9*
    //in case jettyVersion is 9.4.9.v20180320 we need to replace with 9.4.9*
    if (StringUtils.contains(jettyVersion, 'v')) {
        jettyVersion = StringUtils.substringBeforeLast(jettyVersion, ".v");
    }//from   w  ww  .j  a  va 2s.  c o m
    // FIXME investigate elastic but query such 9.4.10-SNAPSHOT doesn't work...
    // so using 9.4.10* then filter response back....
    if (StringUtils.contains(jettyVersion, "-SNAPSHOT")) {
        jettyVersion = StringUtils.substringBeforeLast(jettyVersion, "-SNAPSHOT");
    }

    // in case of 9.4.11-NO-LOGGER-SNAPSHOT still not working with elastic
    // here we must have only number or . so remove everything else

    StringBuilder versionQuery = new StringBuilder();
    CharacterIterator ci = new StringCharacterIterator(jettyVersion);
    for (char c = ci.first(); c != CharacterIterator.DONE; c = ci.next()) {
        if (NumberUtils.isCreatable(Character.toString(c)) || c == '.') {
            versionQuery.append(c);
        }
    }

    jettyVersion = versionQuery.toString() + "*";

    try (ElasticResultStore elasticResultStore = elasticHost.buildElasticResultStore(); //
            InputStream inputStream = LoadResultProjectAction.class
                    .getResourceAsStream("/versionResult.json")) {
        String versionResultQuery = IOUtils.toString(inputStream);
        Map<String, String> map = new HashMap<>(1);
        map.put("jettyVersion", jettyVersion);
        map.put("maxResult", Integer.toString(maxResult));
        versionResultQuery = StrSubstitutor.replace(versionResultQuery, map);

        String results = elasticResultStore.search(versionResultQuery);

        List<LoadResult> loadResults = ElasticResultStore
                .map(new HttpContentResponse(null, results.getBytes(), null, null));

        List<RunInformations> runInformations = //
                loadResults.stream() //
                        .filter(loadResult -> StringUtils.equalsIgnoreCase(originalJettyVersion, //
                                loadResult.getServerInfo().getJettyVersion())) //
                        .map(loadResult -> new RunInformations(
                                loadResult.getServerInfo().getJettyVersion() + ":"
                                        + loadResult.getServerInfo().getGitHash(), //
                                loadResult.getCollectorInformations(),
                                StringUtils.lowerCase(loadResult.getTransport())) //
                                        .jettyVersion(loadResult.getServerInfo().getJettyVersion()) //
                                        .estimatedQps(LoadTestResultBuildAction.estimatedQps(
                                                LoadTestResultBuildAction.getLoaderConfig(loadResult))) //
                                        .serverInfo(loadResult.getServerInfo())) //
                        .collect(Collectors.toList());

        Collections.sort(runInformations, Comparator.comparing(o -> o.getStartTimeStamp()));
        return runInformations;
    }

}

From source file:org.gradle.api.internal.plugins.StartScriptTemplateBindingFactory.java

private String escapeWindowsJvmOpt(String jvmOpts) {
    boolean wasOnBackslash = false;
    StringBuilder escapedJvmOpt = new StringBuilder();
    CharacterIterator it = new StringCharacterIterator(jvmOpts);

    //argument quoting:
    // - " must be encoded as \"
    // - % must be encoded as %%
    // - pathological case: \" must be encoded as \\\", but other than that, \ MUST NOT be quoted
    // - other characters (including ') will not be quoted
    // - use a state machine rather than regexps
    for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
        String repl = Character.toString(ch);

        if (ch == '%') {
            repl = "%%";
        } else if (ch == '"') {
            repl = (wasOnBackslash ? '\\' : "") + "\\\"";
        }//from  www. j a  v a  2s  .c  o m
        wasOnBackslash = ch == '\\';
        escapedJvmOpt.append(repl);
    }

    return escapedJvmOpt.toString();
}

From source file:stg.utils.StringUtils.java

/**
 * Extracts the <i>n</i>th token from the given string after splitting by the given separator char.
 * Example: The String "Kedar#Raybagkar/#Test" with the separator char # and escape char as / then token 2 will return
 * null.//  w ww. j  a  v  a2s.  co m
 * 
 * @param text
 * @param tokenNumber
 * @return String
 */
public static String extractTokenAt(String text, int tokenNumber) {
    return extractTokenAt(text, ' ', CharacterIterator.DONE, tokenNumber);
}

From source file:org.squale.welcom.outils.Util.java

public final static String formatFile(String st) {
    // Transforme les lettres accentues
    st = Util.formatAccent(st);//from  w  ww. ja v a  2  s . co m

    final StringCharacterIterator iter = new StringCharacterIterator(st);
    final StringBuffer sb = new StringBuffer();

    for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
        if (!(((c >= '0') && (c <= '9')) || ((c >= 'a') && (c <= 'z'))
                || (((c >= 'A') && (c <= 'Z')) || (c == '.')))) {
            sb.append('_');
        } else {
            sb.append(c);
        }
    }

    return sb.toString();
}

From source file:net.issarlk.androbunny.inkbunny.API.java

public static String extractTree(Pattern pattern, String data) {
    Matcher matches = pattern.matcher(data);
    if (matches.matches()) {
        data = matches.group(1);/* w  w w. j a  v  a 2  s . c o m*/
        StringBuilder result = new StringBuilder();
        //Extract
        int taglevel = 0;

        CharacterIterator it = new StringCharacterIterator(data);
        int mode = 0;
        int inparamname = 0;
        int inparamvalue = 0;
        int outsidetags = 0;
        int intagname = 0;
        char paramvaluechar = '"';
        HashMap<String, String> params = new HashMap<String, String>();
        StringBuilder tagname = new StringBuilder();
        StringBuilder paramname = new StringBuilder();
        StringBuilder paramvalue = new StringBuilder();
        StringBuilder text = new StringBuilder();
        for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {

            if (c == '<') {
                //start of tag
                c = it.next();
                params.clear();
                outsidetags = 0;
                //Output text
                //Log.d(TAG, repeat(' ', taglevel) + text.toString());
                result.append(text);
                if (c == '/') {
                    //Start of closing tag
                    mode = 3;
                    intagname = 1;
                    c = it.next();
                } else {
                    //Start of openning tag
                    mode = 2;
                    intagname = 1;
                }
                tagname = new StringBuilder();
            }
            if (intagname == 1) {
                if (c < 'a' || c > 'z') {
                    intagname = 0;
                } else {
                    tagname.append(c);
                }
            }
            if ((mode == 2 || mode == 3) && intagname == 0 && inparamname == 0 && inparamvalue == 0 && c >= 'a'
                    && c <= 'z') {
                inparamname = 1;
                paramname = new StringBuilder();
            }
            if (inparamname == 1) {
                if (c == '=') {
                    inparamname = 0;
                    inparamvalue = 1;
                    paramvaluechar = it.next();
                    paramvalue = new StringBuilder();
                    continue;
                } else if (c != ' ') {
                    paramname.append(c);
                }
            }
            if (inparamvalue == 1) {
                if (c == paramvaluechar) {
                    //End of value
                    inparamvalue = 0;
                    params.put(paramname.toString(), paramvalue.toString());
                } else {
                    paramvalue.append(c);
                }
            }
            if (mode == 2 && inparamvalue == 0 && c == '/') {
                c = it.next();
                if (c == '>') {
                    //tag closed at its end
                    mode = 4;
                    if (tagname.toString().equals("br")) {
                        result.append("<br/>");
                    }
                } else {
                    c = it.previous();
                }
            }
            if (c == '>') {
                if (mode == 2) {
                    //openning
                    taglevel += 1;
                    outsidetags = 1;
                    text = new StringBuilder();
                    String paramstr = "";
                    for (String key : params.keySet()) {
                        paramstr += " " + key + "=\"" + params.get(key) + "\"";
                    }
                    //Log.d(TAG, repeat(' ', taglevel - 1) + "<" + tagname.toString() + paramstr + ">");
                    result.append("<" + tagname.toString() + paramstr + ">");
                    mode = 0;
                    continue;
                } else if (mode == 3) {
                    //Closing
                    taglevel -= 1;
                    outsidetags = 1;
                    text = new StringBuilder();
                    //Log.d(TAG, repeat(' ', taglevel) + "</" + tagname.toString() + ">");
                    result.append("</" + tagname.toString() + ">\n");
                    mode = 0;
                    if (taglevel <= 0) {
                        break;
                    }
                    continue;
                } else if (mode == 4) {
                    //closed at end
                    outsidetags = 1;
                    text = new StringBuilder();
                    //Log.d(TAG, repeat(' ', taglevel) + "<" + tagname.toString() + "/>");
                    result.append("<" + tagname.toString() + "/>\n");
                    mode = 0;
                    continue;
                }
            }
            if (outsidetags == 1) {
                //Append char
                text.append(c);
            }
        }

        String res = result.toString();
        return res;
    }
    return null;
}

From source file:com.tripit.auth.OAuthCredential.java

private static void jsonEncodeString(String string, StringBuilder sb) {
    CharacterIterator ci = new StringCharacterIterator(string);
    sb.append('"');
    for (char c = ci.first(); c != CharacterIterator.DONE; c = ci.next()) {
        switch (c) {
        case '\"':
            sb.append("\\\"");
            break;
        case '\\':
            sb.append("\\\\");
            break;
        case '\b':
            sb.append("\\b");
            break;
        case '\f':
            sb.append("\\f");
            break;
        case '\n':
            sb.append("\\n");
            break;
        case '\r':
            sb.append("\\r");
            break;
        case '\t':
            sb.append("\\t");
            break;
        default:/*from  www .j  ava2  s  .  c  o m*/
            sb.append(c);
            break;
        }
    }
    sb.append('"');
}

From source file:Base64.java

public static byte[] decodeBase64(String s) {
    CharacterIterator it = new StringCharacterIterator(s.trim());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int i = 0, j = 0;
    for (char ch = it.first(); ch != CharacterIterator.DONE && ch != '='; ch = it.next()) {
        int v = b64d(ch);
        if (v >= 0) {
            i = (i << 6) | v;//from   w  w w .  j a va  2s .c  om
            j++;
            if (j >= 4) {
                out.write(i >> 16);
                out.write(i >> 8);
                out.write(i);
                i = 0;
                j = 0;
            }
        }
    }
    switch (j) {
    case 3:
        out.write(i >> 10);
        out.write(i >> 2);
        break;
    case 2:
        out.write(i >> 4);
        break;
    }
    return out.toByteArray();
}

From source file:org.intermine.common.swing.text.RestrictedInputDocument.java

/**
 * Insert the given text into this document, as long as it leaves the document valid.
 * //from ww  w.  j a  v  a 2s . c  o m
 * @param offset The starting offset &gt;= 0.
 * @param str The string to insert; does nothing with null/empty strings.
 * @param attr The attributes for the inserted content.
 * 
 * @throws BadLocationException if the given insert position is not a valid
 * position within the document.
 *   
 * @see javax.swing.text.Document#insertString
 */
@Override
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
    if (str == null) {
        return;
    }

    if (limit < 0 || getLength() + str.length() <= limit) {
        if (convertArray == null || convertArray.length < str.length()) {
            convertArray = new char[str.length()];
        }

        CharacterIterator iter = new StringCharacterIterator(str);
        char c = iter.first();
        int index;
        for (index = 0; c != CharacterIterator.DONE; c = iter.next()) {
            if (!overrideChecks && !StringUtils.contains(allowableCharacters, c)) {

                // At this point, c is invalid. See if a case change remedies this.

                if (caseConvert && Character.isLetter(c)) {
                    if (Character.isLowerCase(c)) {
                        c = Character.toUpperCase(c);
                    } else if (Character.isUpperCase(c)) {
                        c = Character.toLowerCase(c);
                    }
                    if (!StringUtils.contains(allowableCharacters, c)) {
                        // Don't insert but otherwise ignore.
                        return;
                    }
                } else {
                    return;
                }
            }
            convertArray[index++] = c;

        }
        super.insertString(offset, new String(convertArray, 0, index), attr);
    }
}