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:au.org.ala.delta.directives.args.DirectiveArgsParser.java

protected String readItemDescription() throws ParseException {
    expect(MARK_IDENTIFIER);/*from ww  w . j  a v  a  2 s .  c  o m*/

    readNext();
    char previousChar = (char) 0;
    StringBuilder id = new StringBuilder();
    while (!(previousChar == '/' && (_currentChar == ' ' || _currentChar == '\r' || _currentChar == '\n'))) {
        id.append(_currentChar);
        previousChar = _currentChar;
        readNext();
    }
    // Delete the '/'
    if (id.charAt(id.length() - 1) != '/') {
        throw DirectiveError.asException(DirectiveError.Error.ITEM_NAME_MISSING_SLASH, _position);
    }
    id.deleteCharAt(id.length() - 1);

    return id.toString().trim();
}

From source file:net.yacy.cora.language.phonetic.Metaphone.java

private boolean isNextChar(StringBuilder string, int index, char c) {
    boolean matches = false;
    if (index >= 0 && index < string.length() - 1) {
        matches = string.charAt(index + 1) == c;
    }// w ww. jav  a 2s.  co m
    return matches;
}

From source file:com.sindicetech.siren.search.node.NodePhraseQuery.java

/**
 * Prefix with a backslash any unescaped double quote
 *//*from ww  w .j  av  a  2 s .com*/
private void escapeDoubleQuote(final StringBuilder buffer, final String s) {
    int index = 0;
    int prevIndex = 0;

    while ((index = s.indexOf('"', prevIndex)) != -1) {
        buffer.append(s, prevIndex, index);
        if (buffer.charAt(buffer.length() - 1) != '\\') {
            buffer.append('\\');
        }
        buffer.append('"');
        prevIndex = index + 1;
    }
    buffer.append(s, prevIndex, s.length());
}

From source file:de.itsvs.cwtrpc.controller.CacheControlFilter.java

protected PreparedCacheControlUriConfig getPreparedUriConfig(HttpServletRequest request) {
    final String contextPath;
    final StringBuilder sb;
    final String uri;

    contextPath = request.getContextPath();
    sb = new StringBuilder(request.getRequestURI());
    if ((contextPath.length() > 0) && (sb.indexOf(contextPath) == 0)) {
        sb.delete(0, contextPath.length());
    }//from ww w  .  j  a  va2  s.  c  om
    if ((sb.length() == 0) || (sb.charAt(0) != '/')) {
        sb.insert(0, '/');
    }
    uri = sb.toString();

    if (log.isDebugEnabled()) {
        log.debug("Checked URI is '" + uri + "'");
    }
    for (PreparedCacheControlUriConfig config : getUriConfigs()) {
        if ((config.getMethod() == null) || config.getMethod().name().equals(request.getMethod())) {
            if (config.getValue().matches(uri)) {
                if (log.isDebugEnabled()) {
                    log.debug("Matching configuration for URI '" + uri + "' and method '" + request.getMethod()
                            + "' is " + config);
                }
                return config;
            }
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("No matching configuration for URI '" + uri + "' and method '" + request.getMethod() + "'");
    }
    return null;
}

From source file:com.cloudant.sync.datastore.BasicDatastoreForceInsertTest.java

@Test
public void forceInsert_sameLengthOfPath_remoteRevisionWins() throws ConflictException {
    {/*w  w  w  . j a  va  2s .c  o  m*/
        DocumentRevision rev = createDbObject();
        datastore.forceInsert(rev, "1-rev", "2-rev", "3-rev", "4-rev");

        DocumentRevision insertedObj = datastore.getDocument(OBJECT_ID);
        DocumentRevision updateObj = datastore.updateDocument(insertedObj.getId(), insertedObj.getRevision(),
                bodyTwo);
        DocumentRevision updateObj2 = datastore.updateDocument(updateObj.getId(), updateObj.getRevision(),
                bodyTwo);
        Assert.assertNotNull(updateObj2);

        assertDBObjectIsCorrect(OBJECT_ID, 6, bodyTwo);
    }

    String localRevisionId6 = null;
    String remoteRevisionId6 = null;
    {
        DocumentRevisionTree tree = datastore.getAllRevisionsOfDocument(OBJECT_ID);
        DocumentRevision current = tree.getCurrentRevision();
        List<DocumentRevision> all = tree.getPathForNode(current.getSequence());
        // Make sure the latest revision from remote db has bigger String (in terms of String comparison)
        for (DocumentRevision a : all) {
            int g = CouchUtils.generationFromRevId(a.getRevision());
            if (g == 6) {
                localRevisionId6 = a.getRevision();
                StringBuilder sb = new StringBuilder(localRevisionId6);
                sb.setCharAt(2, (char) (sb.charAt(2) + 1));
                remoteRevisionId6 = sb.toString();
            }
        }

        Assert.assertNotNull(localRevisionId6);
        Assert.assertNotNull(remoteRevisionId6);

        DocumentRevisionBuilder builder = new DocumentRevisionBuilder();
        builder.setDocId(OBJECT_ID);
        builder.setRevId(remoteRevisionId6);
        builder.setDeleted(false);
        builder.setBody(bodyOne);
        DocumentRevision newRev = builder.build();

        datastore.forceInsert(newRev, "1-rev", "2-rev", "3-rev", "4-rev", "5-rev", remoteRevisionId6);
    }

    DocumentRevision obj = datastore.getDocument(OBJECT_ID);
    Assert.assertEquals(remoteRevisionId6, obj.getRevision());
    Assert.assertTrue(Arrays.equals(bodyOne.asBytes(), obj.getBody().asBytes()));
}

From source file:com.cloudant.sync.datastore.BasicDatastoreForceInsertTest.java

@Test
public void forceInsert_sameLengthOfPath_localRevisionWins() throws ConflictException {
    {//from  www.j a  v a2 s  .c o  m
        DocumentRevision rev = createDbObject();
        datastore.forceInsert(rev, "1-rev", "2-rev", "3-rev", "4-rev");

        DocumentRevision insertedObj = datastore.getDocument(OBJECT_ID);
        DocumentRevision updateObj = datastore.updateDocument(insertedObj.getId(), insertedObj.getRevision(),
                bodyTwo);
        DocumentRevision updateObj2 = datastore.updateDocument(updateObj.getId(), updateObj.getRevision(),
                bodyTwo);
        Assert.assertNotNull(updateObj2);

        assertDBObjectIsCorrect(OBJECT_ID, 6, bodyTwo);
    }

    String localRevisionId6 = null;
    String remoteRevisionId6 = null;
    {
        // Make sure the latest revision from remote db has smaller String (in terms of String comparison)
        DocumentRevisionTree tree = datastore.getAllRevisionsOfDocument(OBJECT_ID);
        DocumentRevision current = tree.getCurrentRevision();
        List<DocumentRevision> all = tree.getPathForNode(current.getSequence());
        for (DocumentRevision a : all) {
            int g = CouchUtils.generationFromRevId(a.getRevision());
            if (g == 6) {
                localRevisionId6 = a.getRevision();
                StringBuilder sb = new StringBuilder(localRevisionId6);
                sb.setCharAt(2, (char) (sb.charAt(2) - 1));
                remoteRevisionId6 = sb.toString();
            }
        }

        Assert.assertNotNull(localRevisionId6);
        Assert.assertNotNull(remoteRevisionId6);

        DocumentRevisionBuilder builder = new DocumentRevisionBuilder();
        builder.setDocId(OBJECT_ID);
        builder.setRevId(remoteRevisionId6);
        builder.setDeleted(false);
        builder.setBody(bodyOne);
        DocumentRevision newRev = builder.build();

        datastore.forceInsert(newRev, "1-rev", "2-rev", "3-rev", "4-rev", "5-rev", remoteRevisionId6);
    }

    DocumentRevision obj = datastore.getDocument(OBJECT_ID);
    Assert.assertEquals(localRevisionId6, obj.getRevision());
    Assert.assertTrue(Arrays.equals(bodyTwo.asBytes(), obj.getBody().asBytes()));
}

From source file:net.solarnetwork.util.JavaBeanXmlSerializer.java

private void writeElement(String name, Map<?, ?> props, XMLStreamWriter out, boolean close)
        throws XMLStreamException {
    out.writeStartElement(name);/*  ww  w  .  j ava2  s  .  co m*/
    Map<String, Object> nested = null;
    if (props != null) {
        for (Map.Entry<?, ?> me : props.entrySet()) {
            String key = me.getKey().toString();
            Object val = me.getValue();
            if (propertySerializerRegistrar != null) {
                val = propertySerializerRegistrar.serializeProperty(name, val.getClass(), props, val);
            }
            if (val instanceof Date) {
                SimpleDateFormat sdf = SDF.get();
                // SimpleDateFormat has no way to create xs:dateTime with tz,
                // so use trick here to insert required colon for non GMT dates
                Date date = (Date) val;
                StringBuilder buf = new StringBuilder(sdf.format(date));
                if (buf.charAt(buf.length() - 1) != 'Z') {
                    buf.insert(buf.length() - 2, ':');
                }
                val = buf.toString();
            } else if (val instanceof Collection) {
                if (nested == null) {
                    nested = new LinkedHashMap<String, Object>(5);
                }
                nested.put(key, val);
                val = null;
            } else if (val instanceof Map<?, ?>) {
                if (nested == null) {
                    nested = new LinkedHashMap<String, Object>(5);
                }
                nested.put(key, val);
                val = null;
            } else if (classNamesAllowedForNesting != null && !(val instanceof Enum<?>)) {
                for (String prefix : classNamesAllowedForNesting) {
                    if (val.getClass().getName().startsWith(prefix)) {
                        if (nested == null) {
                            nested = new LinkedHashMap<String, Object>(5);
                        }
                        nested.put(key, val);
                        val = null;
                        break;
                    }
                }
            }

            if (val != null) {
                String attVal = val.toString();
                out.writeAttribute(key, attVal);
            }
        }
    }
    if (nested != null) {
        for (Map.Entry<String, Object> me : nested.entrySet()) {
            outputObject(me.getValue(), me.getKey(), out);
        }
        if (close) {
            out.writeEndElement();
        }
    }
}

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

/**
 * Capitalises the first word in the supplied text (which may contain RTF
 * markup) the first letter of the word is preceded by a '|'.
 * // ww w  . j  a  va  2  s.c om
 * @param text
 *            the text to capitalise.
 * @return the text with the first word capitalised.
 */
public static String capitaliseFirstWord(String text) {
    if (StringUtils.isEmpty(text)) {
        return text;
    }

    StringBuilder tmp = new StringBuilder();
    tmp.append(text);
    int index = 0;
    while (index >= 0 && index < text.length() && !Character.isLetterOrDigit(tmp.charAt(index))) {
        if (tmp.charAt(index) == '\\') {
            index = RTFUtils.skipKeyword(text, index);

            if (index < 0 || index >= tmp.length() || Character.isLetterOrDigit(tmp.charAt(index))) {
                break;
            }
        }
        index++;
    }

    if (index >= 0 && index < text.length() && Character.isLetter(tmp.charAt(index))) {
        if ((index == 0) || (tmp.charAt(index - 1) != '|')) {
            tmp.setCharAt(index, Character.toUpperCase(tmp.charAt(index)));
        } else if (tmp.charAt(index - 1) == '|') {
            tmp.deleteCharAt(index - 1);
        }
    }
    return tmp.toString();
}

From source file:org.overlord.apiman.service.client.http.HTTPServiceClient.java

/** Reads the request URI from {@code servletRequest} and rewrites it, considering {@link
 * #targetUri}. It's used to make the new request.
 *///ww  w.  j  av  a2 s .  c  om
protected String rewriteUrlFromRequest(Request request) {
    StringBuilder uri = new StringBuilder(500);

    uri.append(request.getServiceURI().toString());

    // Append optional operation
    if (request.getOperation() != null) {

        if (uri.charAt(uri.length() - 1) != '/') {
            uri.append('/');
        }

        uri.append(request.getOperation());
    }

    // Handle the query string
    if (request.getParameters().size() > 0) {
        uri.append('?');

        boolean f_first = true;

        for (int i = 0; i < request.getParameters().size(); i++) {
            org.overlord.apiman.NameValuePair nvp = request.getParameters().get(i);

            // Skip api key
            if (nvp.getName().equalsIgnoreCase(APIKEY)) {
                continue;
            }

            if (!f_first) {
                uri.append('&');
            }

            uri.append(nvp.getName());
            uri.append('=');
            uri.append(nvp.getValue().toString());

            f_first = false;
        }
    }
    /*
    String queryString = request.getQueryString();//ex:(following '?'): name=value&foo=bar#fragment
    if (queryString != null && queryString.length() > 0) {
       uri.append('?');
       int fragIdx = queryString.indexOf('#');
       String queryNoFrag = (fragIdx < 0 ? queryString : queryString.substring(0,fragIdx));
       uri.append(encodeUriQuery(queryNoFrag));
       if (fragIdx >= 0) {
    uri.append('#');
    uri.append(encodeUriQuery(queryString.substring(fragIdx + 1)));
       }
    }
    */

    return uri.toString();
}

From source file:org.apache.accumulo.monitor.servlets.ShellServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Verify that this is the active Monitor instance
    if (!isActiveMonitor()) {
        resp.sendError(HttpURLConnection.HTTP_UNAVAILABLE, STANDBY_MONITOR_MESSAGE);
        return;/* w  ww .  j  a  v a  2s .c  o  m*/
    }
    final HttpSession session = req.getSession(true);
    String user = (String) session.getAttribute("user");
    if (user == null || !userShells().containsKey(session.getId())) {
        // no existing shell for user, re-authenticate
        doGet(req, resp);
        return;
    }
    final String CSRF_TOKEN = (String) session.getAttribute(CSRF_KEY);
    if (null == CSRF_TOKEN) {
        // no csrf token, need to re-auth
        doGet(req, resp);
    }
    ShellExecutionThread shellThread = userShells().get(session.getId());
    String cmd = req.getParameter("cmd");
    if (cmd == null) {
        // the command is null, just print prompt
        resp.getWriter().append(shellThread.getPrompt());
        resp.getWriter().flush();
        return;
    }
    shellThread.addInputString(cmd);
    shellThread.waitUntilReady();
    if (shellThread.isDone()) {
        // the command was exit, invalidate session
        userShells().remove(session.getId());
        session.invalidate();
        return;
    }
    // get the shell's output
    StringBuilder sb = new StringBuilder();
    sb.append(shellThread.getOutput().replace("<", "&lt;").replace(">", "&gt;"));
    if (sb.length() == 0 || !(sb.charAt(sb.length() - 1) == '\n'))
        sb.append("\n");
    // check if shell is waiting for input
    if (!shellThread.isWaitingForInput())
        sb.append(shellThread.getPrompt());
    // check if shell is waiting for password input
    if (shellThread.isMasking())
        sb.append("*");
    resp.getWriter().append(sb.toString());
    resp.getWriter().flush();
}