Example usage for java.lang StringBuilder charAt

List of usage examples for java.lang StringBuilder charAt

Introduction

In this page you can find the example usage for java.lang StringBuilder charAt.

Prototype

char charAt(int index);

Source Link

Document

Returns the char value at the specified index.

Usage

From source file:org.fenixedu.treasury.domain.paymentcodes.PaymentReferenceCode.java

public String getFormattedCode() {
    final StringBuilder result = new StringBuilder();
    int i = 1;/*from   w  w w  . ja  v  a2s .  c  om*/
    for (char character : getReferenceCode().toCharArray()) {
        result.append(character);
        if (i % 3 == 0) {
            result.append(" ");
        }
        i++;
    }

    return result.charAt(result.length() - 1) == ' ' ? result.deleteCharAt(result.length() - 1).toString()
            : result.toString();
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.conll.ConllUReader.java

public void convert(JCas aJCas, BufferedReader aReader) throws IOException {
    if (readPos) {
        try {/*  www  .j  a v a2 s .  c om*/
            posMappingProvider.configure(aJCas.getCas());
        } catch (AnalysisEngineProcessException e) {
            throw new IOException(e);
        }
    }

    JCasBuilder doc = new JCasBuilder(aJCas);

    List<String[]> words;
    while ((words = readSentence(aReader)) != null) {
        if (words.isEmpty()) {
            // Ignore empty sentences. This can happen when there are multiple end-of-sentence
            // markers following each other.
            continue;
        }

        int sentenceBegin = doc.getPosition();
        int sentenceEnd = sentenceBegin;

        int surfaceBegin = -1;
        int surfaceEnd = -1;
        String surfaceString = null;

        // Tokens, Lemma, POS
        Int2ObjectMap<Token> tokens = new Int2ObjectOpenHashMap<>();
        Iterator<String[]> wordIterator = words.iterator();
        while (wordIterator.hasNext()) {
            String[] word = wordIterator.next();
            if (word[ID].contains("-")) {
                String[] fragments = word[ID].split("-");
                surfaceBegin = Integer.valueOf(fragments[0]);
                surfaceEnd = Integer.valueOf(fragments[1]);
                surfaceString = word[FORM];
                continue;
            }

            // Read token
            int tokenIdx = Integer.valueOf(word[ID]);
            Token token = doc.add(word[FORM], Token.class);
            tokens.put(tokenIdx, token);
            if (!StringUtils.contains(word[MISC], "SpaceAfter=No") && wordIterator.hasNext()) {
                doc.add(" ");
            }

            // Read lemma
            if (!UNUSED.equals(word[LEMMA]) && readLemma) {
                Lemma lemma = new Lemma(aJCas, token.getBegin(), token.getEnd());
                lemma.setValue(word[LEMMA]);
                lemma.addToIndexes();
                token.setLemma(lemma);
            }

            // Read part-of-speech tag
            POS pos = null;
            String tag = useCPosAsPos ? word[CPOSTAG] : word[POSTAG];
            if (!UNUSED.equals(tag) && readPos) {
                Type posTag = posMappingProvider.getTagType(tag);
                pos = (POS) aJCas.getCas().createAnnotation(posTag, token.getBegin(), token.getEnd());
                pos.setPosValue(tag.intern());
            }

            // Read coarse part-of-speech tag
            if (!UNUSED.equals(word[CPOSTAG]) && readCPos && pos != null) {
                pos.setCoarseValue(word[CPOSTAG].intern());
            }

            if (pos != null) {
                pos.addToIndexes();
                token.setPos(pos);
            }

            // Read morphological features
            if (!UNUSED.equals(word[FEATS]) && readMorph) {
                MorphologicalFeatures morphtag = new MorphologicalFeatures(aJCas, token.getBegin(),
                        token.getEnd());
                morphtag.setValue(word[FEATS]);
                morphtag.addToIndexes();
                token.setMorph(morphtag);

                // Try parsing out individual feature values. Since the DKPro Core
                // MorphologicalFeatures type is based on the definition from the UD project,
                // we can do this rather straightforwardly.
                Type morphType = morphtag.getType();
                String[] items = word[FEATS].split("\\|");
                for (String item : items) {
                    String[] keyValue = item.split("=");
                    StringBuilder key = new StringBuilder(keyValue[0]);
                    key.setCharAt(0, Character.toLowerCase(key.charAt(0)));
                    String value = keyValue[1];

                    Feature feat = morphType.getFeatureByBaseName(key.toString());
                    if (feat != null) {
                        morphtag.setStringValue(feat, value);
                    }
                }
            }

            // Read surface form
            if (tokenIdx == surfaceEnd) {
                int begin = tokens.get(surfaceBegin).getBegin();
                int end = tokens.get(surfaceEnd).getEnd();
                SurfaceForm surfaceForm = new SurfaceForm(aJCas, begin, end);
                surfaceForm.setValue(surfaceString);
                surfaceForm.addToIndexes();
                surfaceBegin = -1;
                surfaceEnd = -1;
                surfaceString = null;
            }

            sentenceEnd = token.getEnd();
        }

        // Dependencies
        if (readDependency) {
            for (String[] word : words) {
                if (!UNUSED.equals(word[DEPREL])) {
                    int depId = Integer.valueOf(word[ID]);
                    int govId = Integer.valueOf(word[HEAD]);

                    // Model the root as a loop onto itself
                    makeDependency(aJCas, govId, depId, word[DEPREL], DependencyFlavor.BASIC, tokens, word);
                }

                if (!UNUSED.equals(word[DEPS])) {
                    // list items separated by vertical bar
                    String[] items = word[DEPS].split("\\|");
                    for (String item : items) {
                        String[] sItem = item.split(":");

                        int depId = Integer.valueOf(word[ID]);
                        int govId = Integer.valueOf(sItem[0]);

                        makeDependency(aJCas, govId, depId, sItem[1], DependencyFlavor.ENHANCED, tokens, word);
                    }
                }
            }
        }

        // Sentence
        Sentence sentence = new Sentence(aJCas, sentenceBegin, sentenceEnd);
        sentence.addToIndexes();

        // Once sentence per line.
        doc.add("\n");
    }

    doc.close();
}

From source file:com.evolveum.midpoint.tools.ninja.ImportDDL.java

private void readScript(File script, BufferedReader reader, Connection connection) throws IOException {
    System.out.println("Reading DDL script file '" + script.getAbsolutePath() + "'.");
    reader = new BufferedReader(new InputStreamReader(new FileInputStream(script), "utf-8"));
    StringBuilder query = new StringBuilder();
    String line;/*from   www. ja  va 2 s. co m*/
    while ((line = reader.readLine()) != null) {
        //skip comments
        if (line.length() == 0 || line.length() > 0 && line.charAt(0) == '-') {
            continue;
        }

        if (query.length() != 0) {
            query.append(' ');
        }
        query.append(line.trim());

        //If one command complete
        if (query.charAt(query.length() - 1) == ';') {
            query.deleteCharAt(query.length() - 1);
            try {
                String queryStr = query.toString();
                System.out.println("Executing query: " + queryStr);

                Statement stmt = connection.createStatement();
                stmt.execute(queryStr);
                stmt.close();
            } catch (SQLException ex) {
                System.out.println("Exception occurred during SQL statement '" + query.toString()
                        + "' execute, reason: " + ex.getMessage());
            }
            query = new StringBuilder();
        }
    }
}

From source file:com.flexive.shared.FxFormatUtils.java

/**
 * Escape a path to allow only a-zA-Z0-9/ and replace all other letters with underscores (_)
 *
 * @param path the path to escape/*from w w w  . j  a va2s . com*/
 * @return escaped path
 */
public static String escapeTreePath(final String path) {
    if (StringUtils.isEmpty(path))
        return "_";
    StringBuilder sb = new StringBuilder(path.length());
    char c;
    boolean inTag = false;
    for (int i = 0; i < path.length(); i++) {
        c = path.charAt(i);
        if (c == '<' && !inTag) {
            inTag = true;
            continue;
        }
        if (c == '>' && inTag) {
            inTag = false;
            continue;
        }
        if (inTag)
            continue;
        if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '/' || c == '.'
                || c == '-')
            sb.append(c);
        else {
            if ((sb.length() > 0 && sb.charAt(sb.length() - 1) != '_') || sb.length() == 0) {
                sb.append('_');
            }
        }
    }
    if (sb.length() == 0)
        sb.append('_');
    return sb.toString();
}

From source file:org.beangle.struts2.convention.route.Profile.java

public String getSimpleName(String className) {
    String postfix = getActionSuffix();
    String simpleName = className.substring(className.lastIndexOf('.') + 1);
    if (StringUtils.contains(simpleName, postfix)) {
        simpleName = StringUtils.uncapitalize(simpleName.substring(0, simpleName.length() - postfix.length()));
    } else {/* w  w w .  ja v a 2  s .  c  o m*/
        simpleName = StringUtils.uncapitalize(simpleName);
    }

    StringBuilder infix = new StringBuilder();
    infix.append(StringUtils.substringBeforeLast(className, "."));
    if (infix.length() == 0)
        return simpleName;
    infix.append('.');
    infix.append(simpleName);
    // .??/
    for (int i = 0; i < infix.length(); i++) {
        if (infix.charAt(i) == '.') {
            infix.setCharAt(i, '/');
        }
    }
    return infix.toString();
}

From source file:nl.b3p.viewer.stripes.LayarActionBean.java

/**
 * Replace all the [attributename] in the given string with the values in the SimpleFeature
 * @param string/*  w w w.  j a  v  a2s  .  c  o m*/
 * @param f
 * @return
 * @throws Exception 
 */
private String replaceValuesInString(String string, SimpleFeature f) throws Exception {
    if (string == null) {
        return null;
    }
    if (!string.contains("[") && !string.contains("]")) {
        return string;
    }
    StringBuilder url = new StringBuilder(string);

    int begin = -1;
    int end = -1;
    for (int i = 0; i < url.length(); i++) {
        char c = url.charAt(i);
        if (c == '[') {
            if (begin == -1) {
                begin = i;
            } else {
                throw new Exception("Configuration of \"" + string + "\" not correct. ']' missing .");
            }
        } else if (c == ']') {
            end = i;
            if (begin != -1 && end != -1) {
                String attribName = url.substring(begin + 1, end);
                Object value = null;
                if (attribName == null || attribName.length() == 0) {
                    value = "";
                } else {
                    value = f.getAttribute(attribName);
                }
                if (value == null) {
                    value = "";
                }
                url.replace(begin, end + 1, value.toString().trim());
                i = begin;
                begin = -1;
                end = -1;
            } else {
                throw new Exception("Configuration of \"" + string + "\" not correct. Missing '[' .");
            }
        } else if (i == url.length() - 1 && begin != -1) {
            throw new Exception("Configuration of \"" + string + "\" not correct. Missing ']' .");
        }
    }
    return url.toString();
}

From source file:au.org.ala.delta.util.Utils.java

/**
 * Removes DELTA style <> comments from the supplied string.
 * /*from   www . j  a v a 2s .c om*/
 * @param text
 *            the string to remove comments from.
 * @param level
 *            0 = don't remove, 1 = remove all, 2 = remove only if other
 *            text, 3 = same as 2, but outer brackets are removed if
 *            commented text is used.
 * @return the string with comments removed
 */
public static String removeComments(String text, int level, boolean convertCommentsToBrackets,
        boolean removeInnerComments, boolean stripSpaces, boolean removeBrackets) {

    int mode = level;

    int commentLevel = 0;
    boolean hasText = mode == 1;
    boolean hadInner = false;
    char ch;
    int i, curStart = -1, start = -1, end = -1;
    int innerStart = -1;
    boolean wasSpace = true;
    boolean wasBrace = false;
    // TODO despaceRTF(text);
    if (stripSpaces) {
        text = stripExtraSpaces(text);
    }
    StringBuilder result = new StringBuilder(text);

    for (i = 0; i < result.length(); ++i) { // Work through string
        // Is character an opening bracket?
        if (result.charAt(i) == '<'
                && (wasSpace || wasBrace || (ch = result.charAt(i - 1)) == ' ' || ch == '<' || ch == '>')) {
            wasBrace = true;
            if (convertCommentsToBrackets) {
                result.setCharAt(i, ')');
            }
            if (removeBrackets || (mode == 3 && commentLevel == 0)) {
                result.deleteCharAt(i--);
            }
            if (commentLevel == 0) {
                curStart = i;
                if (start == -1)
                    start = i;
            } else if (commentLevel == 1) {
                innerStart = i;
                hadInner = true;
            }
            // Keep track of nesting level
            commentLevel++;
        }
        // Was it a closing bracket?
        else if (result.charAt(i) == '>' && commentLevel > 0 && result.charAt(i - 1) != '|'
                && (i + 1 == result.length() || (ch = result.charAt(i + 1)) == ' ' || ch == '<' || ch == '>')) {
            // Keep track of nesting level
            commentLevel--;
            wasBrace = true;
            if (convertCommentsToBrackets)
                result.setCharAt(i, ')');
            if (removeBrackets || (mode == 3 && commentLevel == 0))
                result.deleteCharAt(i--);
            if (commentLevel == 0) {
                if (start != -1) {
                    end = i;
                    if (removeInnerComments && hadInner) // In this case,
                                                         // check for
                                                         // and remove an empty
                                                         // comment...
                    {
                        int leng = end - curStart - 1;
                        String contents = result.substring(curStart + 1, end - 1);
                        contents = stripExtraSpaces(contents);
                        if (contents.isEmpty() || contents == " ") {
                            result.delete(curStart, end - 1);
                            i = curStart;
                        } else if (stripSpaces && contents.length() != leng) {
                            result.replace(curStart + 1, curStart + leng, contents);
                            i -= leng - contents.length();
                        }
                    }
                }
                hadInner = false;
            } else if (commentLevel == 1 && removeInnerComments) {
                // If we're removing inner comments, get rid of this
                // part of the string, and any space before it.
                int leng = i - innerStart + 1;
                result.delete(innerStart, innerStart + leng);
                i = innerStart - 1;
                while (result.length() > i && result.charAt(i) == ' ')
                    result.deleteCharAt(i--);
            }
        } else if (commentLevel == 0 && (hasText || result.charAt(i) != ' ')) {
            hasText = true;
            wasBrace = false;
            wasSpace = (end == i - 1 && i > 0);
            if (end != -1 && mode > 0) {
                result.delete(start, end + 1);
                i -= end - start + 2;
                // Hmm. How SHOULD spaces around the removed comments
                // be treated? This erases the spaces BEFORE the comment
                while (i >= 0 && result.length() > i && result.charAt(i) == ' ')
                    result.deleteCharAt(i--);
                start = -1;
                end = -1;
            }
        } else
            wasBrace = false;
    }
    if (end != -1 && hasText && mode > 0) {
        result.delete(start, end + 1);
        for (i = result.length() - 1; i >= 0 && result.charAt(i) == ' '; --i)
            result.deleteCharAt(i);
    }
    return result.toString();
}

From source file:ca.uhn.fhir.rest.method.MethodUtil.java

private static void parseTagValue(TagList theTagList, String theCompleteHeaderValue, StringBuilder theBuffer) {
    int firstSemicolon = theBuffer.indexOf(";");
    int deleteTo;
    if (firstSemicolon == -1) {
        firstSemicolon = theBuffer.indexOf(",");
        if (firstSemicolon == -1) {
            firstSemicolon = theBuffer.length();
            deleteTo = theBuffer.length();
        } else {//  ww w .  ja va2  s  . co  m
            deleteTo = firstSemicolon;
        }
    } else {
        deleteTo = firstSemicolon + 1;
    }

    String term = theBuffer.substring(0, firstSemicolon);
    String scheme = null;
    String label = null;
    if (isBlank(term)) {
        return;
    }

    theBuffer.delete(0, deleteTo);
    while (theBuffer.length() > 0 && theBuffer.charAt(0) == ' ') {
        theBuffer.deleteCharAt(0);
    }

    while (theBuffer.length() > 0) {
        boolean foundSomething = false;
        if (theBuffer.length() > SCHEME.length() && theBuffer.substring(0, SCHEME.length()).equals(SCHEME)) {
            int closeIdx = theBuffer.indexOf("\"", SCHEME.length());
            scheme = theBuffer.substring(SCHEME.length(), closeIdx);
            theBuffer.delete(0, closeIdx + 1);
            foundSomething = true;
        }
        if (theBuffer.length() > LABEL.length() && theBuffer.substring(0, LABEL.length()).equals(LABEL)) {
            int closeIdx = theBuffer.indexOf("\"", LABEL.length());
            label = theBuffer.substring(LABEL.length(), closeIdx);
            theBuffer.delete(0, closeIdx + 1);
            foundSomething = true;
        }
        // TODO: support enc2231-string as described in
        // http://tools.ietf.org/html/draft-johnston-http-category-header-02
        // TODO: support multiple tags in one header as described in
        // http://hl7.org/implement/standards/fhir/http.html#tags

        while (theBuffer.length() > 0 && (theBuffer.charAt(0) == ' ' || theBuffer.charAt(0) == ';')) {
            theBuffer.deleteCharAt(0);
        }

        if (!foundSomething) {
            break;
        }
    }

    if (theBuffer.length() > 0 && theBuffer.charAt(0) == ',') {
        theBuffer.deleteCharAt(0);
        while (theBuffer.length() > 0 && theBuffer.charAt(0) == ' ') {
            theBuffer.deleteCharAt(0);
        }
        theTagList.add(new Tag(scheme, term, label));
        parseTagValue(theTagList, theCompleteHeaderValue, theBuffer);
    } else {
        theTagList.add(new Tag(scheme, term, label));
    }

    if (theBuffer.length() > 0) {
        ourLog.warn("Ignoring extra text at the end of " + Constants.HEADER_CATEGORY + " tag '"
                + theBuffer.toString() + "' - Complete tag value was: " + theCompleteHeaderValue);
    }

}

From source file:org.apache.ws.security.message.ModifiedRequestTest.java

/**
 * Test for when some EncryptedData CipherValue data is modified.
 *//*from   w  w  w  .ja va 2  s.  c om*/
@org.junit.Test
public void testModifiedEncryptedDataCipherValue() throws Exception {
    WSSecEncrypt builder = new WSSecEncrypt();
    builder.setUserInfo("wss40");
    builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
    builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Crypto wssCrypto = CryptoFactory.getInstance("wss40.properties");
    Document encryptedDoc = builder.build(doc, wssCrypto, secHeader);

    Element body = WSSecurityUtil.findBodyElement(doc);
    Element cipherValue = WSSecurityUtil.findElement(body, "CipherValue", WSConstants.ENC_NS);
    String cipherText = cipherValue.getTextContent();

    StringBuilder stringBuilder = new StringBuilder(cipherText);
    int index = stringBuilder.length() / 2;
    char ch = stringBuilder.charAt(index);
    if (ch != 'A') {
        ch = 'A';
    } else {
        ch = 'B';
    }
    stringBuilder.setCharAt(index, ch);
    cipherValue.setTextContent(stringBuilder.toString());

    String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
    if (LOG.isDebugEnabled()) {
        LOG.debug(outputString);
    }

    WSSecurityEngine newEngine = new WSSecurityEngine();
    try {
        newEngine.processSecurityHeader(doc, null, new KeystoreCallbackHandler(), wssCrypto);
        fail("Failure expected on a modified EncryptedData CipherValue");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == 6);
        assertTrue(ex.getMessage().startsWith("The signature or decryption was invalid"));
    }
}

From source file:org.apache.ws.security.message.ModifiedRequestTest.java

/**
 * Test for when some EncryptedKey CipherValue data is modified.
 *//* w  w  w .j a  va 2 s.co m*/
@org.junit.Test
public void testModifiedEncryptedKeyCipherValue() throws Exception {
    WSSecEncrypt builder = new WSSecEncrypt();
    builder.setUserInfo("wss40");
    builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
    builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Crypto wssCrypto = CryptoFactory.getInstance("wss40.properties");
    Document encryptedDoc = builder.build(doc, wssCrypto, secHeader);

    Element encryptedKey = WSSecurityUtil.findElement(doc.getDocumentElement(), "EncryptedKey",
            WSConstants.ENC_NS);
    Element cipherValue = WSSecurityUtil.findElement(encryptedKey, "CipherValue", WSConstants.ENC_NS);
    String cipherText = cipherValue.getTextContent();

    StringBuilder stringBuilder = new StringBuilder(cipherText);
    int index = stringBuilder.length() / 2;
    char ch = stringBuilder.charAt(index);
    if (ch != 'A') {
        ch = 'A';
    } else {
        ch = 'B';
    }
    stringBuilder.setCharAt(index, ch);
    cipherValue.setTextContent(stringBuilder.toString());

    String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
    if (LOG.isDebugEnabled()) {
        LOG.debug(outputString);
    }

    WSSecurityEngine newEngine = new WSSecurityEngine();
    try {
        newEngine.processSecurityHeader(doc, null, new KeystoreCallbackHandler(), wssCrypto);
        fail("Failure expected on a modified EncryptedData CipherValue");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == 6);
        assertTrue(ex.getMessage().startsWith("The signature or decryption was invalid"));
    }
}