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:self.philbrown.javaQuery.$.java

/** 
 * Capitalizes the first letter of the given string.
 * @param string the string whose first letter should be capitalized
 * @return the given string with its first letter capitalized
 * @throws NullPointerException if the string is null or empty
 *///ww w  .ja v a  2  s. co m
public static String capitalize(String string) {
    if (string == null || string.trim().length() == 0)
        throw new NullPointerException("Cannot handle null or empty string");

    StringBuilder strBuilder = new StringBuilder(string);
    strBuilder.setCharAt(0, Character.toUpperCase(strBuilder.charAt(0)));
    return strBuilder.toString();
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.hplus.HPlusSupport.java

private void showIncomingCall(String name, String rawNumber) {
    try {/*from   ww w .  j  av  a2 s. c  o  m*/
        StringBuilder number = new StringBuilder();

        //Clean up number as the device only accepts digits
        for (char c : rawNumber.toCharArray()) {
            if (Character.isDigit(c)) {
                number.append(c);
            }
        }

        TransactionBuilder builder = performInitialized("incomingCall");

        //Enable call notifications
        builder.write(ctrlCharacteristic, new byte[] { HPlusConstants.CMD_ACTION_INCOMING_CALL, 1 });

        //Show Call Icon
        builder.write(ctrlCharacteristic,
                new byte[] { HPlusConstants.CMD_SET_INCOMING_CALL, HPlusConstants.ARG_INCOMING_CALL });

        byte[] msg = new byte[13];

        //Show call name

        for (int i = 0; i < msg.length; i++)
            msg[i] = ' ';

        byte[] nameBytes = encodeStringToDevice(name);
        for (int i = 0; i < nameBytes.length && i < (msg.length - 1); i++)
            msg[i + 1] = nameBytes[i];

        msg[0] = HPlusConstants.CMD_ACTION_DISPLAY_TEXT_NAME;
        builder.write(ctrlCharacteristic, msg);

        msg[0] = HPlusConstants.CMD_ACTION_DISPLAY_TEXT_NAME_CN;
        builder.write(ctrlCharacteristic, msg);

        builder.wait(200);
        msg = msg.clone();

        //Show call number
        for (int i = 0; i < msg.length; i++)
            msg[i] = ' ';

        for (int i = 0; i < number.length() && i < (msg.length - 1); i++)
            msg[i + 1] = (byte) number.charAt(i);

        msg[0] = HPlusConstants.CMD_SET_INCOMING_CALL_NUMBER;

        builder.write(ctrlCharacteristic, msg);

        builder.queue(getQueue());
    } catch (IOException e) {
        GB.toast(getContext(), "Error showing incoming call: " + e.getLocalizedMessage(), Toast.LENGTH_LONG,
                GB.ERROR);

    }
}

From source file:com.sun.socialsite.business.DefaultURLStrategy.java

/**
 * Get the appropriate Gadget Server URL for the specified request.
 * The returned URL will not end with a trailing slash.  If the
 * "socialsite.gadgets.server.url" property is populated and contains
 * any wildcards ("*"), they will be replaced with the specified
 * replacementValue./*w  w w .j ava  2 s  .  co  m*/
 */
public String getGadgetServerURL(HttpServletRequest request, String replacementValue) {

    StringBuilder sb = new StringBuilder();

    try {

        String propVal = Config.getProperty("socialsite.gadgets.server.url");
        if (propVal != null) {
            String actualValue = propVal.replace("*", replacementValue);
            sb.append(actualValue);
        } else {
            if (Config.getBooleanProperty("socialsite.gadgets.use-cookie-jail")) {
                // For now, we'll use an IP-based URL to provide a cookie jail
                InetAddress addr = InetAddress.getByName(request.getServerName());
                if (addr instanceof Inet6Address) {
                    sb.append(request.getScheme()).append("://[").append(addr.getHostAddress()).append("]");
                } else {
                    sb.append(request.getScheme()).append("://").append(addr.getHostAddress());
                }
            } else {
                sb.append(request.getScheme()).append("://").append(request.getServerName());
            }
            switch (request.getServerPort()) {
            case 80:
                if (!(request.getScheme().equalsIgnoreCase("http"))) {
                    sb.append(":").append(request.getServerPort());
                }
                break;
            case 443:
                if (!(request.getScheme().equalsIgnoreCase("https"))) {
                    sb.append(":").append(request.getServerPort());
                }
                break;
            default:
                sb.append(":").append(request.getServerPort());
            }
            sb.append(request.getContextPath());
            sb.append("/gadgets");
        }

    } catch (Exception e) {
        log.warn(e);
    }

    // We don't want our result to end with a slash
    while (sb.charAt(sb.length() - 1) == '/') {
        sb.deleteCharAt(sb.length() - 1);
    }

    return sb.toString();

}

From source file:com.eucalyptus.objectstorage.pipeline.handlers.S3Authentication.java

/**
 * AWS S3-spec address string, which includes the query parameters
 *
 * @param httpRequest/*from   ww  w  .  j av a2s . co  m*/
 * @param removeServicePath if true, removes the service path from the address string if found and if the request is path-style
 * @return
 * @throws com.eucalyptus.objectstorage.exceptions.s3.AccessDeniedException
 */
static String getS3AddressString(MappingHttpRequest httpRequest, boolean removeServicePath) throws S3Exception {
    /*
     * There are two modes: dns-style and path-style. dns-style has the bucket name in the HOST header path-style has the bucket name in the request
     * path.
     * 
     * If using DNS-style, we assume the key is the path, no service path necessary or allowed If using path-style, there may be service path as well
     * that prefixes the bucket name (e.g. /services/objectstorage/bucket/key)
     */
    try {
        String addr = httpRequest.getUri();
        String osgServicePath = ComponentIds.lookup(ObjectStorage.class).getServicePath();
        String bucket, key;

        StringBuilder addrString = new StringBuilder();

        // Normalize the URI
        boolean foundName = false;
        String hostBucket = null;
        if ((hostBucket = OSGUtil.getBucketFromHostHeader(httpRequest)) != null) {
            // dns-style request
            foundName = true;
            addrString.append("/" + hostBucket);
        }

        if (!foundName) {
            // path-style request (or service request that won't have a bucket anyway)
            if (removeServicePath) {
                if (addr.startsWith(osgServicePath)) {
                    addr = addr.substring(osgServicePath.length(), addr.length());
                } else if (addr.startsWith(ObjectStorageProperties.LEGACY_WALRUS_SERVICE_PATH)) {
                    addr = addr.substring(ObjectStorageProperties.LEGACY_WALRUS_SERVICE_PATH.length(),
                            addr.length());
                }
            }
        }

        // Get the path part, up to the ?
        key = addr.split("\\?", 2)[0];
        if (!Strings.isNullOrEmpty(key)) {
            addrString.append(key);
        } else {
            addrString.append("/");
        }

        List<String> canonicalSubresources = new ArrayList<>();
        for (String queryParam : httpRequest.getParameters().keySet()) {
            try {
                if (ObjectStorageProperties.SubResource.valueOf(queryParam) != null) {
                    canonicalSubresources.add(queryParam);
                }
            } catch (IllegalArgumentException e) {
                // Skip. Not in the set.
            }
            try {
                if (ObjectStorageProperties.ResponseHeaderOverrides.fromString(queryParam) != null) {
                    canonicalSubresources.add(queryParam);
                }
            } catch (IllegalArgumentException e) {
                // Skip. Not in the set.
            }
        }

        if (canonicalSubresources.size() > 0) {
            Collections.sort(canonicalSubresources);
            String value;
            addrString.append("?");
            // Add resources to canonical string
            for (String subResource : canonicalSubresources) {
                value = httpRequest.getParameters().get(subResource);
                addrString.append(subResource);
                // Query values are not URL-decoded, the signature should have them exactly as in the URI
                if (!Strings.isNullOrEmpty(value)) {
                    addrString.append("=").append(value);
                }
                addrString.append("&");
            }

            // Remove trailng '&' if found
            if (addrString.charAt(addrString.length() - 1) == '&') {
                addrString.deleteCharAt(addrString.length() - 1);
            }
        }

        return addrString.toString();
    } catch (S3Exception e) {
        throw e;
    } catch (Exception e) {
        // Anything unexpected...
        throw new InternalErrorException(e);
    }
}

From source file:tr.edu.gsu.nerwip.retrieval.reader.wikipedia.WikipediaReader.java

/**
 * Retrieve the text located in a table (TABLE) HTML element.
 * <br/>/*from  w ww .ja v a 2  s.com*/
 * We process each cell in the table as a text element. 
 * Some tables are ignored: infoboxes, wikitables, navboxes,
 * metadata, persondata, etc. 
 * 
 * @param element
 *       Element to be processed.
 * @param rawStr
 *       Current raw text string.
 * @param linkedStr
 *       Current text with hyperlinks.
 * @return
 *       {@code true} iff the element was processed.
 */
private boolean processTableElement(Element element, StringBuilder rawStr, StringBuilder linkedStr) {
    boolean result;
    String eltClass = element.attr(XmlNames.ATT_CLASS);

    if (eltClass == null ||
    // we ignore infoboxes
            (!eltClass.contains(CLASS_INFORMATIONBOX)
                    // and wikitables
                    && !eltClass.contains(CLASS_WIKITABLE)
                    // navigation boxes
                    && !eltClass.contains(CLASS_NAVIGATIONBOX)
                    // navigation boxes, WP warnings (incompleteness, etc.)
                    && !eltClass.contains(CLASS_METADATA)
                    // personal data box (?)
                    && !eltClass.contains(CLASS_PERSONDATA)))

    {
        result = true;
        Element tbodyElt = element.children().get(0);

        for (Element rowElt : tbodyElt.children()) {
            for (Element colElt : rowElt.children()) { // process cell content
                processTextElement(colElt, rawStr, linkedStr);

                // possibly add final dot and space. 
                if (rawStr.charAt(rawStr.length() - 1) != ' ') {
                    if (rawStr.charAt(rawStr.length() - 1) == '.') {
                        rawStr.append(" ");
                        linkedStr.append(" ");
                    } else {
                        rawStr.append(". ");
                        linkedStr.append(". ");
                    }
                }
            }
        }
    }

    else
        result = false;

    return result;
}

From source file:net.sourceforge.processdash.ev.ui.EVReport.java

private String fixChartHelpContent(String helpContent, String helpBaseUri, Map<String, String> chartHelp) {

    // discard headers and footers from the help content
    int cutStart = helpContent.indexOf("</h1>");
    if (cutStart != -1)
        helpContent = helpContent.substring(cutStart + 5);
    int cutEnd = helpContent.lastIndexOf("</body");
    if (cutEnd != -1)
        helpContent = helpContent.substring(0, cutEnd);

    // create a map of the chart help topics
    Map<String, String> chartUrls = new HashMap<String, String>();
    for (Map.Entry<String, String> e : chartHelp.entrySet()) {
        String chartId = e.getKey();
        String chartUrl = getChartDrillDownUrl(chartId);
        String helpUri = e.getValue();
        String helpName = hrefFileName(helpUri);
        chartUrls.put(helpName, chartUrl);
    }// www . j av  a2 s .com

    // find and fix all the hrefs in this help topic:
    //   * If any hrefs point to the help topic for a different chart,
    //     rewrite the href so it actually loads the "drill-down page"
    //     for that chart instead.
    //   * For links that point to some non-chart help topic, rewrite the
    //     href to be absolute (so the help-relative URI won't break)

    StringBuilder html = new StringBuilder(helpContent);
    int pos = 0;
    while (true) {
        // find the next href in the document.
        pos = html.indexOf("href=", pos);
        if (pos == -1)
            break; // no more hrefs to fix

        pos += 6;
        int beg = pos; // the first character of the href value itself
        char delim = html.charAt(beg - 1);
        int end = html.indexOf(String.valueOf(delim), beg);
        if (end == -1)
            continue; // invalid href syntax.  Skip to the next one.

        // extract the href value
        String oneHref = html.substring(beg, end);
        // extract the final portion of the path name
        String oneName = hrefFileName(oneHref);
        // see if that name refers to one of the charts we can display
        String chartUrl = chartUrls.get(oneName);
        if (chartUrl != null) {
            // replace the href with a chart drill-down URL
            html.replace(beg, end, chartUrl);
            pos = beg + chartUrl.length();
        } else {
            try {
                // make the URL absolute, and set a "target" attribute
                // so it will open in another window.
                URI base = new URI(helpBaseUri);
                URI target = base.resolve(oneHref);
                String newUri = target.toString();
                html.replace(beg, end, newUri);
                html.insert(beg - 6, "target='evHelp' ");
                pos = beg + newUri.length() + 16;
            } catch (Exception e) {
                // problems resolving the URI?  Turn the link into an
                // anchor so it can't be clicked on anymore.
                html.replace(beg - 6, beg - 2, "name");
            }
        }
    }

    return html.toString();
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlPage.java

/**
 * If a refresh has been specified either through a meta tag or an HTTP
 * response header, then perform that refresh.
 * @throws IOException if an IO problem occurs
 *//*  w  w  w .ja  v a  2  s  . co  m*/
private void executeRefreshIfNeeded() throws IOException {
    // If this page is not in a frame then a refresh has already happened,
    // most likely through the JavaScript onload handler, so we don't do a
    // second refresh.
    final WebWindow window = getEnclosingWindow();
    if (window == null) {
        return;
    }

    final String refreshString = getRefreshStringOrNull();
    if (refreshString == null || refreshString.isEmpty()) {
        return;
    }

    final double time;
    final URL url;

    int index = StringUtils.indexOfAnyBut(refreshString, "0123456789");
    final boolean timeOnly = index == -1;

    if (timeOnly) {
        // Format: <meta http-equiv='refresh' content='10'>
        try {
            time = Double.parseDouble(refreshString);
        } catch (final NumberFormatException e) {
            LOG.error("Malformed refresh string (no ';' but not a number): " + refreshString, e);
            return;
        }
        url = getUrl();
    } else {
        // Format: <meta http-equiv='refresh' content='10;url=http://www.blah.com'>
        try {
            time = Double.parseDouble(refreshString.substring(0, index).trim());
        } catch (final NumberFormatException e) {
            LOG.error("Malformed refresh string (no valid number before ';') " + refreshString, e);
            return;
        }
        index = refreshString.toLowerCase(Locale.ROOT).indexOf("url=", index);
        if (index == -1) {
            LOG.error("Malformed refresh string (found ';' but no 'url='): " + refreshString);
            return;
        }
        final StringBuilder buffer = new StringBuilder(refreshString.substring(index + 4));
        if (StringUtils.isBlank(buffer.toString())) {
            //content='10; URL=' is treated as content='10'
            url = getUrl();
        } else {
            if (buffer.charAt(0) == '"' || buffer.charAt(0) == 0x27) {
                buffer.deleteCharAt(0);
            }
            if (buffer.charAt(buffer.length() - 1) == '"' || buffer.charAt(buffer.length() - 1) == 0x27) {
                buffer.deleteCharAt(buffer.length() - 1);
            }
            final String urlString = buffer.toString();
            try {
                url = getFullyQualifiedUrl(urlString);
            } catch (final MalformedURLException e) {
                LOG.error("Malformed URL in refresh string: " + refreshString, e);
                throw e;
            }
        }
    }

    final int timeRounded = (int) time;
    getWebClient().getRefreshHandler().handleRefresh(this, url, timeRounded);
}

From source file:com.wabacus.WabacusFacade.java

public static String getAutoCompleteColValues(HttpServletRequest request, HttpServletResponse response) {
    StringBuilder resultBuf = new StringBuilder();
    ReportRequest rrequest = null;/*from   ww  w .j  a  v  a  2  s  . co  m*/
    try {
        rrequest = new ReportRequest(request, -1);
        WabacusResponse wresponse = new WabacusResponse(response);
        rrequest.setWResponse(wresponse);
        rrequest.initGetAutoCompleteColValues();
        ReportBean rbean = rrequest.getLstAllReportBeans().get(0);
        String conditionparams = request.getParameter("AUTOCOMPLETE_COLCONDITION_VALUES");
        List<Map<String, String>> lstConditionParamsValue = EditableReportAssistant.getInstance()
                .parseSaveDataStringToList(conditionparams);
        if (lstConditionParamsValue == null || lstConditionParamsValue.size() == 0)
            return "";
        rrequest.setAttribute("COL_CONDITION_VALUES", lstConditionParamsValue.get(0));
        AutoCompleteBean accbean = rrequest.getAutoCompleteSourceInputBoxObj().getAutoCompleteBean();
        Map<String, String> mAutoCompleteData = accbean.getDatasetProvider()
                .getAutoCompleteColumnsData(rrequest, lstConditionParamsValue.get(0));
        if (rbean.getInterceptor() != null) {
            mAutoCompleteData = (Map<String, String>) rbean.getInterceptor().afterLoadData(rrequest, rbean,
                    accbean, mAutoCompleteData);
        }
        if (mAutoCompleteData == null || mAutoCompleteData.size() == 0)
            return "";
        resultBuf.append("{");
        String propTmp, valueTmp;
        for (ColBean cbTmp : accbean.getLstAutoCompleteColBeans()) {
            propTmp = cbTmp.getProperty();
            valueTmp = mAutoCompleteData.get(propTmp);
            if (valueTmp == null)
                valueTmp = "";
            resultBuf.append(propTmp).append(":\"").append(valueTmp).append("\",");
            mAutoCompleteData.remove(propTmp);
        }
        for (Entry<String, String> entryTmp : mAutoCompleteData.entrySet()) {//mColData??????
            resultBuf.append(entryTmp.getKey()).append(":\"").append(entryTmp.getValue()).append("\",");
        }
        if (resultBuf.charAt(resultBuf.length() - 1) == ',')
            resultBuf.deleteCharAt(resultBuf.length() - 1);
        resultBuf.append("}");
    } catch (Exception e) {
        throw new WabacusRuntimeException("?", e);
    } finally {
        if (rrequest != null)
            rrequest.destroy(false);
    }
    return resultBuf.toString();
}

From source file:com.greenlaw110.rythm.toString.ToStringStyle.java

/**
 * <p>Remove the last field separator from the buffer.</p>
 *
 * @param buffer  the <code>StringBuilder</code> to populate
 * @since 2.0/*from  ww  w .  j  a v a  2  s .c  o  m*/
 */
protected void removeLastFieldSeparator(StringBuilder buffer) {
    int len = buffer.length();
    int sepLen = fieldSeparator.length();
    if (len > 0 && sepLen > 0 && len >= sepLen) {
        boolean match = true;
        for (int i = 0; i < sepLen; i++) {
            if (buffer.charAt(len - 1 - i) != fieldSeparator.charAt(sepLen - 1 - i)) {
                match = false;
                break;
            }
        }
        if (match) {
            buffer.setLength(len - sepLen);
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XMLSerializer.java

private void toXml(final int indent, final DomNode node, final StringBuilder buffer) {
    final String nodeName = node.getNodeName();
    buffer.append('<').append(nodeName);

    final String optionalPrefix = "";
    final String namespaceURI = node.getNamespaceURI();
    final String prefix = node.getPrefix();
    if (namespaceURI != null && prefix != null) {
        boolean sameNamespace = false;
        for (DomNode parentNode = node
                .getParentNode(); parentNode instanceof DomElement; parentNode = parentNode.getParentNode()) {
            if (namespaceURI.equals(parentNode.getNamespaceURI())) {
                sameNamespace = true;/*  w  w  w  . j a v  a2  s  .  co  m*/
            }
        }
        if (node.getParentNode() == null || !sameNamespace) {
            ((DomElement) node).setAttribute("xmlns:" + prefix, namespaceURI);
        }
    }

    final NamedNodeMap attributesMap = node.getAttributes();
    for (int i = 0; i < attributesMap.getLength(); i++) {
        final DomAttr attrib = (DomAttr) attributesMap.item(i);
        buffer.append(' ').append(attrib.getQualifiedName()).append('=').append('"').append(attrib.getValue())
                .append('"');
    }
    boolean startTagClosed = false;
    for (final DomNode child : node.getChildren()) {
        if (!startTagClosed) {
            buffer.append(optionalPrefix).append('>');
            startTagClosed = true;
        }
        switch (child.getNodeType()) {
        case Node.ELEMENT_NODE:
            toXml(indent + 1, child, buffer);
            break;

        case Node.TEXT_NODE:
            String value = child.getNodeValue();
            value = StringUtils.escapeXmlChars(value);
            if (preserveWhiteSpace_) {
                buffer.append(value.replace("\n", "\r\n"));
            } else if (org.apache.commons.lang3.StringUtils.isBlank(value)) {
                buffer.append("\r\n");
                final DomNode sibling = child.getNextSibling();
                if (sibling != null && sibling.getNodeType() == Node.ELEMENT_NODE) {
                    for (int i = 0; i < indent; i++) {
                        buffer.append('\t');
                    }
                }
            } else {
                buffer.append(value.replace("\n", "\r\n"));
            }
            break;

        case Node.CDATA_SECTION_NODE:
        case Node.COMMENT_NODE:
            if (!preserveWhiteSpace_ && buffer.charAt(buffer.length() - 1) == '\n') {
                for (int i = 0; i < indent; i++) {
                    buffer.append('\t');
                }
            }
            buffer.append(child.asXml());
            break;

        default:

        }
    }
    if (!startTagClosed) {
        buffer.append(optionalPrefix).append("/>");
    } else {
        if (!preserveWhiteSpace_ && buffer.charAt(buffer.length() - 1) == '\n') {
            for (int i = 0; i < indent - 1; i++) {
                buffer.append('\t');
            }
        }
        buffer.append('<').append('/').append(nodeName).append('>');
    }
}