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:com.g3net.tool.StringUtils.java

/**
 * str0?//ww w .  ja v a 2  s.  c om
 * 
 * @param str
 * @param defaultValue
 * @return
 */
public static String trimWhitespace(String str, String defaultValue) {

    if (!hasLength(str)) {
        return defaultValue;
    }
    StringBuilder buf = new StringBuilder(str);
    while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) {
        buf.deleteCharAt(0);
    }
    while (buf.length() > 0 && Character.isWhitespace(buf.charAt(buf.length() - 1))) {
        buf.deleteCharAt(buf.length() - 1);
    }
    return buf.toString();
}

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

/**
 * The main job of this method is to terminate RTF control words with {}
 * instead of a space./*from  ww w  .  j ava 2s  . c o  m*/
 */
// Not all cases are handled correctly in the current code.
// For example, text with \bin might not always give correct results
// A few other things, such as \'xx, should perhaps also be given
// explicit treatment, but should not substantially affect the outcome.
public static String despaceRtf(String text, boolean quoteDelims) {
    if (StringUtils.isEmpty(text)) {
        return "";
    }
    int srcPos;
    boolean inRTF = false;
    boolean inParam = false;
    boolean inUnicode = false;
    boolean bracketed = text.charAt(0) == '<' && text.charAt(text.length() - 1) == '>';

    StringBuilder outputText = new StringBuilder(text);
    if (bracketed) // If a "comment", temporarily chop off the terminating
                   // bracket
        outputText.setLength(outputText.length() - 1);
    for (srcPos = 0; srcPos < outputText.length(); ++srcPos) {
        char ch = outputText.charAt(srcPos);
        // Always convert a tab character into a \tab control word
        if (ch == '\t') {
            outputText.replace(srcPos, srcPos + 1, "\\tab{}");
            ch = '\\';
        }
        if (inRTF) {
            if (Character.isDigit(ch) || (!inParam && ch == '-')) {
                if (!inParam && outputText.charAt(srcPos - 1) == 'u' && outputText.charAt(srcPos - 2) == '\\')
                    inUnicode = true;
                inParam = true;
            } else if (inParam || !Character.isLetter(ch)) {
                boolean wasInUnicode = inUnicode;
                inUnicode = inParam = inRTF = false;
                if (Character.isSpaceChar(ch)) {
                    // Check for the absence of a control; when this
                    // happens,
                    // the terminating character IS the control word!
                    if (srcPos > 0 && outputText.charAt(srcPos - 1) == '\\') {
                        // \<NEWLINE> is treated as a \par control. We make
                        // this
                        // change here explicitly, to make it more apparent.
                        // But should we keep the <NEWLINE> character around
                        // as well,
                        // as a clue for breaking lines during output?
                        if (ch == '\n' || ch == '\r') {
                            // text.replace(--srcPos, 2, "\\par{}");
                            outputText.insert(srcPos, "par{}");
                            srcPos += 5;
                        }
                        // (Note that if we don't catch this here, replacing
                        // "\ " could yield
                        // "\{}" which is WRONG. But rather than just get
                        // rid of this, it
                        // is probably better to replace with {} to ensure
                        // that any preceding
                        // RTF is terminated)
                        else if (ch == ' ') {
                            outputText.replace(srcPos - 1, 2, "{}");
                        }
                    }
                    // This is the chief condition we are trying to fix.
                    // Terminate the RTF
                    // control phrase with {} instead of white space...
                    // But if the terminator is a new line, we keep it
                    // around
                    // for assistance in wrapping output lines.
                    // else if (ch == '\n')
                    // {
                    // text.insert(srcPos, "{}");
                    // srcPos += 2;
                    // }
                    else if (ch != '\n') {
                        outputText.setCharAt(srcPos, '{');
                        outputText.insert(++srcPos, '}');
                    }
                }
                // No reason to do the following. Probably better to leave
                // the
                // character quoted.
                // Reinstated 8 December 1999 because we need to be sure
                // all text is in a consistent state when linking characters
                // One exception - if the quoted character is a Unicode
                // "replacement"
                // character, we'd better leave it quoted.
                else if (ch == '\'' && !wasInUnicode && srcPos + 2 < outputText.length()) {
                    char[] buff = new char[3];
                    buff[0] = outputText.charAt(srcPos + 1);
                    buff[1] = outputText.charAt(srcPos + 2);
                    buff[2] = 0;

                    int[] endPos = new int[1];
                    int value = strtol(new String(buff), endPos, 16);
                    if ((endPos[0] == 2) && value > 127 && outputText.charAt(srcPos - 1) == '\\') {

                        srcPos--;
                        outputText.replace(srcPos, srcPos + 4, new String(new char[] { (char) value }));

                    }
                } else if (ch == '\\' && outputText.charAt(srcPos - 1) != '\\') // Terminates
                                                                                // RTF,
                                                                                // but
                                                                                // starts
                                                                                // new
                                                                                // RTF
                {
                    inRTF = true;
                    if (wasInUnicode && srcPos + 1 < outputText.length()
                            && outputText.charAt(srcPos + 1) == '\'')
                        inUnicode = true;
                } else if (ch == '>') {
                    // Append a space after the RTF (it was probably
                    // stripped by the attribute parsing)
                    outputText.insert(srcPos, "{}");
                }
            }
        } else if (ch == '\\')
            inRTF = true;
        // TEST - to allow outputting of a "*" or "#" character in arbitrary
        // text...
        else if (quoteDelims && (ch == '*' || ch == '#')
                && (srcPos == 0 || Character.isSpaceChar(outputText.charAt(srcPos - 1)))) {
            // //char buffer[5];
            // Always build a 4-character replacement string, like:
            // \'20
            // //sprintf(buffer, "\\\'%2.2x", (int)ch);
            // //text.replace(srcPos, buffer, 4);
            // //srcPos += 3;
            outputText.insert(srcPos, "{}");
            srcPos += 2;
        }
    }
    if (inRTF)
        outputText.append("{}");
    if (bracketed)
        outputText.append('>');
    return outputText.toString();
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.pdf.Pdf2CasConverter.java

private StringBuilder sanitize(final StringBuilder aContent) {
    int i = 0;/* w  ww . ja  va 2  s  .c  o m*/
    int lastBreak = 0;
    while (i < aContent.length()) {
        // Check valid unicode char
        if (!isValidXMLChar(aContent.codePointAt(i))) {
            aContent.setCharAt(i, ' ');
            i++;
            continue;
        }

        // Set up how many characters we want to skip
        int seek = i + 1;

        // Do we maybe have an entity?
        if (aContent.charAt(i) == '&') {
            // REC 2006-10-21 Some PDFs seem to have entities and others
            // don't
            // so we may encounter &'s that do not introduce an entity and
            // just ignore them.
            final int end = aContent.indexOf(";", i);
            if (end != -1) {
                final String cand = aContent.substring(i, end + 1);
                String r = null;
                try {
                    if (cand.startsWith("&#x")) {
                        final int cp = Integer.parseInt(cand.substring(2, cand.length() - 1), 16);
                        r = isValidXMLChar(cp) ? String.valueOf(Character.toChars(cp)) : " ";
                    } else if (cand.startsWith("&#")) {
                        final int cp = Integer.parseInt(cand.substring(2, cand.length() - 1));
                        r = isValidXMLChar(cp) ? String.valueOf(Character.toChars(cp)) : " ";
                    } else {
                        // RE 2006-10-22 The chance that there is a & and a
                        // ;
                        // together in a string is quite big. Let's be
                        // tolerant.
                    }
                } catch (final NumberFormatException e) {
                    log.warn("Invalid numeric entity in fragment [" + cand + "] - Dropping it.");
                }

                // Expand the entity and set proper skip (if found)
                if (r != null) {
                    aContent.replace(i, i + cand.length(), r);
                    seek = i + r.length();
                }
            }
        }

        // Match against the Trie after numeric entity expansion is over
        if (substitutionTable != null) {
            final Trie<String>.Node match = substitutionTable.getNode(aContent, i);
            if (match != null) {
                aContent.replace(i, i + match.level, match.value);
                seek = i + match.value.length();
            }
        }

        // Check line breaks
        while (i < seek) {
            if (aContent.charAt(i) == '\n') {
                lastBreak = i;
            } else if (Character.isWhitespace(aContent.codePointAt(i)) && (i > (lastBreak + 79))) {
                lastBreak = i;
                aContent.replace(i, i + 1, "\n");
            }
            i++;
        }
    }

    return aContent;
}

From source file:net.hasor.search.utils.DateUtil.java

/** Formats the date and returns the calendar instance that was used (which may be reused) */
public static Calendar formatDate(Date date, Calendar cal, Appendable out) throws IOException {
    // using a stringBuilder for numbers can be nice since
    // a temporary string isn't used (it's added directly to the
    // builder's buffer.
    StringBuilder sb = out instanceof StringBuilder ? (StringBuilder) out : new StringBuilder();
    if (cal == null)
        cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.ROOT);
    cal.setTime(date);//  w  w  w  . ja  v a 2 s.c o m
    int i = cal.get(Calendar.YEAR);
    sb.append(i);
    sb.append('-');
    i = cal.get(Calendar.MONTH) + 1; // 0 based, so add 1
    if (i < 10)
        sb.append('0');
    sb.append(i);
    sb.append('-');
    i = cal.get(Calendar.DAY_OF_MONTH);
    if (i < 10)
        sb.append('0');
    sb.append(i);
    sb.append('T');
    i = cal.get(Calendar.HOUR_OF_DAY); // 24 hour time format
    if (i < 10)
        sb.append('0');
    sb.append(i);
    sb.append(':');
    i = cal.get(Calendar.MINUTE);
    if (i < 10)
        sb.append('0');
    sb.append(i);
    sb.append(':');
    i = cal.get(Calendar.SECOND);
    if (i < 10)
        sb.append('0');
    sb.append(i);
    i = cal.get(Calendar.MILLISECOND);
    if (i != 0) {
        sb.append('.');
        if (i < 100)
            sb.append('0');
        if (i < 10)
            sb.append('0');
        sb.append(i);
        // handle canonical format specifying fractional
        // seconds shall not end in '0'.  Given the slowness of
        // integer div/mod, simply checking the last character
        // is probably the fastest way to check.
        int lastIdx = sb.length() - 1;
        if (sb.charAt(lastIdx) == '0') {
            lastIdx--;
            if (sb.charAt(lastIdx) == '0') {
                lastIdx--;
            }
            sb.setLength(lastIdx + 1);
        }
    }
    sb.append('Z');
    if (out != sb)
        out.append(sb);
    return cal;
}

From source file:com.google.api.server.spi.config.jsonwriter.JsonConfigWriter.java

/**
 * Adds a schema for a type into an output node. For arrays, this generates nested schemas inline
 * for however many dimensions are necessary.
 *
 * @return an appropriate name for the schema if one isn't already assigned
 *//*  w  w  w.j  a v  a 2 s  . c  o m*/
private String addTypeToNode(ObjectNode schemasNode, TypeToken<?> type, TypeToken<?> enclosingType,
        ObjectNode node, ApiConfig apiConfig, List<ApiParameterConfig> parameterConfigs)
        throws ApiConfigException {
    TypeToken<?> itemType = Types.getArrayItemType(type);

    if (typeLoader.isSchemaType(type)) {
        String basicTypeName = typeLoader.getSchemaType(type);
        addElementTypeToNode(schemasNode, type, basicTypeName, node, apiConfig);
        return basicTypeName;
    } else if (itemType != null) {
        ObjectNode items = objectMapper.createObjectNode();
        node.put("type", "array");
        node.set(Constant.ITEMS, items);

        String itemTypeName = addTypeToNode(schemasNode, itemType, enclosingType, items, apiConfig,
                parameterConfigs);
        String arraySuffix = "Collection";
        StringBuilder sb = new StringBuilder(itemTypeName.length() + arraySuffix.length());
        sb.append(itemTypeName).append(arraySuffix);
        sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
        return sb.toString();
    } else if (type instanceof TypeVariable) {
        throw new IllegalArgumentException(String.format("Object type %s not supported.", type));
    } else {
        String typeName = addTypeToSchema(schemasNode, type, enclosingType, apiConfig, parameterConfigs);
        addElementTypeToNode(schemasNode, type, typeName, node, apiConfig);
        return typeName;
    }
}

From source file:org.connectbot.util.TerminalTextViewOverlay.java

public void refreshTextFromBuffer() {
    VDUBuffer vb = terminalView.bridge.getVDUBuffer();
    int numRows = vb.getBufferSize();
    int numCols = vb.getColumns() - 1;
    oldBufferHeight = numRows;// ww w. j av a 2 s  .  co m

    StringBuilder buffer = new StringBuilder();
    int previousTotalLength = 0;

    for (int r = 0; r < numRows && vb.charArray[r] != null; r++) {
        for (int c = 0; c < numCols; c++) {
            buffer.append(vb.charArray[r][c]);
        }

        // Truncate all the new whitespace without removing the old data.
        while (buffer.length() > previousTotalLength
                && Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
            buffer.setLength(buffer.length() - 1);
        }

        // Make sure each line ends with a carriage return and then remember the buffer
        // at that length.
        buffer.append('\n');
        previousTotalLength = buffer.length();
    }

    oldScrollY = vb.getWindowBase() * getLineHeight();

    setText(buffer);
}

From source file:org.apache.olingo.client.core.uri.AbstractURIBuilder.java

@Override
public URI build() {
    final StringBuilder segmentsBuilder = new StringBuilder();
    for (Segment seg : segments) {
        if (segmentsBuilder.length() > 0 && seg.getType() != SegmentType.KEY) {
            switch (seg.getType()) {
            case BOUND_OPERATION:
                segmentsBuilder.append(getBoundOperationSeparator());
                break;

            default:
                if (segmentsBuilder.length() > 0
                        && segmentsBuilder.charAt(segmentsBuilder.length() - 1) != '/') {
                    segmentsBuilder.append('/');
                }// w  w w.  j av  a2s  .com
            }
        }

        if (seg.getType() == SegmentType.ENTITY) {
            segmentsBuilder.append(seg.getType().getValue());
        } else {
            segmentsBuilder.append(seg.getValue());
        }
        if (seg.getType() == SegmentType.BOUND_OPERATION || seg.getType() == SegmentType.UNBOUND_OPERATION) {
            segmentsBuilder.append(getOperationInvokeMarker());
        }
    }

    try {
        StringBuilder sb = segmentsBuilder;
        if ((queryOptions.size() + parameters.size()) > 0) {
            sb.append("?");
            List<NameValuePair> list1 = new LinkedList<NameValuePair>();
            for (Map.Entry<String, String> option : queryOptions.entrySet()) {
                list1.add(new BasicNameValuePair("$" + option.getKey(), option.getValue()));
            }
            for (Map.Entry<String, String> parameter : parameters.entrySet()) {
                list1.add(new BasicNameValuePair("@" + parameter.getKey(), parameter.getValue()));
            }

            // don't use UriBuilder.build():
            // it will try to call URLEncodedUtils.format(Iterable<>,Charset) method,
            // which works in desktop java application, however, throws NoSuchMethodError in android OS,
            // so here manually construct the URL by its overload URLEncodedUtils.format(List<>,String).
            String queryStr = URLEncodedUtils.format(list1, "UTF-8");
            sb.append(queryStr);
        }

        return URI.create(sb.toString());
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("Could not build valid URI", e);
    }
}

From source file:org.apache.solr.common.util.DateUtil.java

/** Formats the date and returns the calendar instance that was used (which may be reused) */
public static Calendar formatDate(Date date, Calendar cal, Appendable out) throws IOException {
    // using a stringBuilder for numbers can be nice since
    // a temporary string isn't used (it's added directly to the
    // builder's buffer.

    StringBuilder sb = out instanceof StringBuilder ? (StringBuilder) out : new StringBuilder();
    if (cal == null)
        cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
    cal.setTime(date);//ww w  .  jav  a 2  s .  c  om

    int i = cal.get(Calendar.YEAR);
    sb.append(i);
    sb.append('-');
    i = cal.get(Calendar.MONTH) + 1; // 0 based, so add 1
    if (i < 10)
        sb.append('0');
    sb.append(i);
    sb.append('-');
    i = cal.get(Calendar.DAY_OF_MONTH);
    if (i < 10)
        sb.append('0');
    sb.append(i);
    sb.append('T');
    i = cal.get(Calendar.HOUR_OF_DAY); // 24 hour time format
    if (i < 10)
        sb.append('0');
    sb.append(i);
    sb.append(':');
    i = cal.get(Calendar.MINUTE);
    if (i < 10)
        sb.append('0');
    sb.append(i);
    sb.append(':');
    i = cal.get(Calendar.SECOND);
    if (i < 10)
        sb.append('0');
    sb.append(i);
    i = cal.get(Calendar.MILLISECOND);
    if (i != 0) {
        sb.append('.');
        if (i < 100)
            sb.append('0');
        if (i < 10)
            sb.append('0');
        sb.append(i);

        // handle canonical format specifying fractional
        // seconds shall not end in '0'.  Given the slowness of
        // integer div/mod, simply checking the last character
        // is probably the fastest way to check.
        int lastIdx = sb.length() - 1;
        if (sb.charAt(lastIdx) == '0') {
            lastIdx--;
            if (sb.charAt(lastIdx) == '0') {
                lastIdx--;
            }
            sb.setLength(lastIdx + 1);
        }

    }
    sb.append('Z');

    if (out != sb)
        out.append(sb);

    return cal;
}

From source file:de.micromata.genome.gwiki.page.gspt.ExtendedTemplate.java

/**
 * Compress ws string.//from w w  w .ja  v  a 2  s .  com
 *
 * @param text the text
 */
private void compressWsString(StringBuilder text) {
    char lastChar = 0;
    for (int i = 0; i < text.length(); ++i) {
        char cc = text.charAt(i);
        if (lastChar == ' ' && cc == ' ') {
            text.deleteCharAt(i);
            --i;
            continue;
        }
        lastChar = cc;
    }
}

From source file:org.fao.geonet.utils.Xml.java

private static boolean doCreateXpathExpr(Object content, StringBuilder builder) {
    if (builder.length() > 0) {
        builder.insert(0, "/");
    }//from   ww  w.  jav a 2 s  .c  om

    Element parentElement;
    if (content instanceof Element) {
        Element element = (Element) content;
        final List<Attribute> attributes = element.getAttributes();
        doCreateAttributesXpathExpr(builder, attributes);
        final String textTrim = element.getTextTrim();
        if (!textTrim.isEmpty()) {
            boolean addToCondition = builder.length() > 0 && builder.charAt(0) == '[';

            if (!addToCondition) {
                builder.insert(0, "']");
            } else {
                builder.deleteCharAt(0);
                builder.insert(0, "' and ");
            }

            builder.insert(0, textTrim).insert(0, "[normalize-space(text()) = '");

        }
        builder.insert(0, element.getName());
        if (element.getNamespacePrefix() != null && !element.getNamespacePrefix().trim().isEmpty()) {
            builder.insert(0, ':').insert(0, element.getNamespacePrefix());
        }
        parentElement = element.getParentElement();
    } else if (content instanceof Text) {
        final Text text = (Text) content;
        builder.insert(0, "text()");
        parentElement = text.getParentElement();
    } else if (content instanceof Attribute) {
        Attribute attribute = (Attribute) content;
        builder.insert(0, attribute.getName());
        if (attribute.getNamespacePrefix() != null && !attribute.getNamespacePrefix().trim().isEmpty()) {
            builder.insert(0, ':').insert(0, attribute.getNamespacePrefix());
        }
        builder.insert(0, '@');
        parentElement = attribute.getParent();
    } else {
        parentElement = null;
    }

    if (parentElement != null && parentElement.getParentElement() != null) {
        return doCreateXpathExpr(parentElement, builder);
    }
    return true;
}