Example usage for java.lang StringBuilder insert

List of usage examples for java.lang StringBuilder insert

Introduction

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

Prototype

@Override
public StringBuilder insert(int offset, double d) 

Source Link

Usage

From source file:com.evolveum.polygon.scim.SalesforceHandlingStrategy.java

@Override
public Uid groupUpdateProcedure(Integer statusCode, JSONObject jsonObject, String uri, Header authHeader,
        ScimConnectorConfiguration conf) {

    Uid id = null;//from   w w w. j av  a2s  . co m
    HttpClient httpClient = initHttpClient(conf);
    LOGGER.info(
            "Status code from first update query: {0}. Processing trough Salesforce \"group/member update\" workaround. ",
            statusCode);
    HttpGet httpGet = buildHttpGet(uri, authHeader);
    try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpGet);) {
        statusCode = response.getStatusLine().getStatusCode();
        LOGGER.info("status code: {0}", statusCode);
        if (statusCode == 200) {

            String responseString = EntityUtils.toString(response.getEntity());
            if (!responseString.isEmpty()) {

                JSONObject json = new JSONObject(responseString);
                LOGGER.info("Json object returned from service provider: {0}", json);
                for (String attributeName : jsonObject.keySet()) {

                    json.put(attributeName, jsonObject.get(attributeName));
                }

                StringEntity bodyContent = new StringEntity(json.toString(1));
                bodyContent.setContentType(CONTENTTYPE);

                HttpPatch httpPatch = new HttpPatch(uri);
                httpPatch.addHeader(authHeader);
                httpPatch.addHeader(PRETTYPRINTHEADER);
                httpPatch.setEntity(bodyContent);

                try (CloseableHttpResponse secondaryResponse = (CloseableHttpResponse) httpClient
                        .execute(httpPatch)) {
                    responseString = EntityUtils.toString(secondaryResponse.getEntity());
                    statusCode = secondaryResponse.getStatusLine().getStatusCode();
                    LOGGER.info("status code: {0}", statusCode);
                    if (statusCode == 200 || statusCode == 201) {
                        LOGGER.info("Update of resource was successful");

                        json = new JSONObject(responseString);
                        id = new Uid(json.getString(ID));
                        LOGGER.ok("Json response: {0}", json.toString(1));
                        return id;
                    } else {
                        ErrorHandler.onNoSuccess(responseString, statusCode, "updating object");
                    }
                }
            }
        }

    } catch (ClientProtocolException e) {
        LOGGER.error(
                "An protocol exception has occurred while in the process of updating a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}",
                e.getLocalizedMessage());
        LOGGER.info(
                "An protocol exception has occurred while in the process of updating a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}",
                e);
        throw new ConnectionFailedException(
                "An protocol exception has occurred while in the process of updating a resource object, Possible mismatch in the interpretation of the HTTP specification.",
                e);
    } catch (IOException e) {

        StringBuilder errorBuilder = new StringBuilder(
                "Occurrence in the process of creating a resource object");

        if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {
            errorBuilder.insert(0, "The connection timed out. ");
            throw new OperationTimeoutException(errorBuilder.toString(), e);
        } else {

            LOGGER.error(
                    "An error has occurred while processing the http response. Occurrence in the process of updating a resource object: {0}",
                    e.getLocalizedMessage());
            LOGGER.info(
                    "An error has occurred while processing the http response. Occurrence in the process of creating a resource object: {0}",
                    e);

            throw new ConnectorIOException(errorBuilder.toString(), e);
        }
    }
    return id;
}

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

private void writeElement(String name, Map<?, ?> props, XMLStreamWriter out, boolean close)
        throws XMLStreamException {
    out.writeStartElement(name);/*  w w  w.  j  a  v a 2  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:com.ewcms.core.site.model.Channel.java

private void constructPubPath() {
    StringBuilder builder = new StringBuilder();
    for (Channel channel = this; channel != null; channel = channel.parent) {
        if (StringUtils.isBlank(channel.getDir())) {
            break;
        }//from w w w.j av a  2  s .  co  m
        String dir = removeStartAndEndPathSeparator(channel.getDir());
        builder.insert(0, dir);
        builder.insert(0, PATH_SEPARATOR);
    }
    pubPath = removeStartAndEndPathSeparator(builder.toString());
}

From source file:com.nebkat.plugin.text.TextPlugin.java

@EventHandler
@CommandFilter("text")
public void onCommand(CommandEvent e) {
    if (e.getParams().length < 2) {
        e.showUsage(getBot());/*from w w w .  ja  va2  s.c om*/
        return;
    }
    String action = e.getParams()[0];
    String text = e.getRawParams().substring(action.length() + 1);
    String result = "Algorithm unsupported";
    if (action.equalsIgnoreCase("invert")) {
        result = new StringBuilder(text).reverse().toString();
    } else if (action.equalsIgnoreCase("wordinvert")) {
        String[] words = text.split(" ");
        for (int i = 0; i < words.length; i++) {
            words[i] = new StringBuilder(words[i]).reverse().toString();
        }
        result = Utils.implode(words, " ");
    } else if (action.equalsIgnoreCase("upsidedown")) {
        StringBuilder upside = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            String character = text.substring(i, i + 1);
            character = UPSIDE_DOWN_MAP.getOrDefault(character, character);
            upside.insert(0, character);
        }
        result = upside.toString();
    } else if (action.equalsIgnoreCase("bubble")) {
        StringBuilder bubble = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            String character = text.substring(i, i + 1);
            character = BUBBLE_MAP.getOrDefault(character, character);
            bubble.append(character);
        }
        result = bubble.toString();
    } else if (action.equals("uppercase") || action.equals("upper")) {
        result = text.toUpperCase();
    } else if (action.equals("lowercase") || action.equals("lower")) {
        result = text.toLowerCase();
    } else if (action.equals("randcase")) {
        StringBuilder randcase = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            randcase.append(Math.random() < 0.5 ? text.substring(i, i + 1).toLowerCase()
                    : text.substring(i, i + 1).toUpperCase());
        }
        result = randcase.toString();
    } else if (action.equalsIgnoreCase("switchcase")) {
        StringBuilder switchcase = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            switchcase.append(Character.isUpperCase(text.charAt(i)) ? text.substring(i, i + 1).toLowerCase()
                    : text.substring(i, i + 1).toUpperCase());
        }
        result = switchcase.toString();
    } else if (action.equalsIgnoreCase("wordcapitalise")) {
        String[] words = text.split(" ");
        for (int i = 0; i < words.length; i++) {
            if (words[i].length() > 0) {
                words[i] = words[i].substring(0, 1).toUpperCase() + words[i].substring(1).toLowerCase();
            }
        }
        result = Utils.implode(words, " ");
        Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": " + Utils.implode(words, " "));
    }
    Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": " + result);
}

From source file:net.sf.jabref.gui.autocompleter.AutoCompleteListener.java

/**
 * Start a new completion attempt (instead of treating a continuation of an existing word or an interrupt of the
 * current word)/*from w w  w .  j  a va2s. c  o m*/
 */
private void startCompletion(StringBuffer currentword, KeyEvent e) {
    JTextComponent comp = (JTextComponent) e.getSource();

    List<String> completed = findCompletions(currentword.toString());
    String prefix = completer.getPrefix();
    String cWord = (prefix != null) && (!prefix.isEmpty()) ? currentword.toString().substring(prefix.length())
            : currentword.toString();

    LOGGER.debug("StartCompletion currentword: >" + currentword + "'<' prefix: >" + prefix + "'<' cword: >"
            + cWord + '<');

    int no = 0; // We use the first word in the array of completions.
    if ((completed != null) && (!completed.isEmpty())) {
        lastShownCompletion = 0;
        lastCompletions = completed;
        String sno = completed.get(no);

        // these two lines obey the user's input
        //toSetIn = Character.toString(ch);
        //toSetIn = toSetIn.concat(sno.substring(cWord.length()));
        // BUT we obey the completion
        toSetIn = sno.substring(cWord.length() - 1);

        LOGGER.debug("toSetIn: >" + toSetIn + '<');

        StringBuilder alltext = new StringBuilder(comp.getText());
        int cp = comp.getCaretPosition();
        alltext.insert(cp, toSetIn);
        comp.setText(alltext.toString());
        comp.setCaretPosition(cp);
        comp.select(cp + 1, (cp + 1 + sno.length()) - cWord.length());
        e.consume();
        lastCaretPosition = comp.getCaretPosition();
        char ch = e.getKeyChar();

        LOGGER.debug("Appending >" + ch + '<');

        if (cWord.length() <= 1) {
            lastBeginning = Character.toString(ch);
        } else {
            lastBeginning = cWord.substring(0, cWord.length() - 1).concat(Character.toString(ch));
        }
    }

}

From source file:net.ymate.framework.core.taglib.bootstrap.FormTag.java

@Override
protected StringBuilder __doTagContent(StringBuilder tagContent, StringBuilder bodyContent) {
    if (fieldset || disabled || StringUtils.isNotBlank(legend)) {
        StringBuilder _tmpSB = new StringBuilder("<fieldset");
        if (disabled) {
            _tmpSB.append(" disabled");
        }//from   w ww.j  a  va  2s. co  m
        _tmpSB.append(">");
        if (StringUtils.isNotBlank(legend)) {
            _tmpSB.append("<legend>").append(legend).append("</legend>");
        }
        bodyContent.insert(0, _tmpSB).append("</fieldset>");
    }
    return super.__doTagContent(tagContent, bodyContent);
}

From source file:net.sf.jabref.gui.AutoCompleteListener.java

/**
 * Start a new completion attempt//from   w w  w. j a va 2  s.c o  m
 * (instead of treating a continuation of an existing word or an interrupt of the current word)
 */
private void startCompletion(StringBuffer currentword, KeyEvent e) {
    JTextComponent comp = (JTextComponent) e.getSource();

    String[] completed = findCompletions(currentword.toString(), comp);
    String prefix = completer.getPrefix();
    String cWord = (prefix != null) && (!prefix.isEmpty()) ? currentword.toString().substring(prefix.length())
            : currentword.toString();

    LOGGER.debug("StartCompletion currentword: >" + currentword + "'<' prefix: >" + prefix + "'<' cword: >"
            + cWord + '<');

    int no = 0; // We use the first word in the array of completions.
    if ((completed != null) && (completed.length > 0)) {
        lastShownCompletion = 0;
        lastCompletions = completed;
        String sno = completed[no];

        // these two lines obey the user's input
        //toSetIn = Character.toString(ch);
        //toSetIn = toSetIn.concat(sno.substring(cWord.length()));
        // BUT we obey the completion
        toSetIn = sno.substring(cWord.length() - 1);

        LOGGER.debug("toSetIn: >" + toSetIn + '<');

        StringBuilder alltext = new StringBuilder(comp.getText());
        int cp = comp.getCaretPosition();
        alltext.insert(cp, toSetIn);
        comp.setText(alltext.toString());
        comp.setCaretPosition(cp);
        comp.select(cp + 1, (cp + 1 + sno.length()) - cWord.length());
        e.consume();
        lastCaretPosition = comp.getCaretPosition();
        char ch = e.getKeyChar();

        LOGGER.debug("Appending >" + ch + '<');

        if (cWord.length() <= 1) {
            lastBeginning = Character.toString(ch);
        } else {
            lastBeginning = cWord.substring(0, cWord.length() - 1).concat(Character.toString(ch));
        }
    }

}

From source file:com.forerunnergames.tools.common.Strings.java

/**
 * Converts a collection of list elements to a string list, separated by separator, in case letterCase.
 *
 * @param <T>/*w w  w.  jav a  2 s. c  o m*/
 *          The type of the list elements.
 * @param listElements
 *          The collection of list elements to convert, must not be null, must not contain any null elements.
 * @param separator
 *          The separator that should be added between list elements, must not be null.
 * @param letterCase
 *          The desired letter case of the list elements, must not be null, choose LetterCase.NONE to leave the list
 *          elements as-is.
 * @param hasAnd
 *          Whether or not to insert the word 'and ' between the last two elements in the list, one space after the
 *          last separator.
 *
 * @return A string list of listElements, separated by separator, in case letterCase, with an optional 'and '
 *         occurring between the last two elements of the list.
 */
public static <T> String toStringList(final Collection<T> listElements, final String separator,
        final LetterCase letterCase, final boolean hasAnd) {
    Arguments.checkIsNotNull(listElements, "listElements");
    Arguments.checkHasNoNullElements(listElements, "listElements");
    Arguments.checkIsNotNull(separator, "separator");
    Arguments.checkIsNotNull(letterCase, "letterCase");

    final ImmutableList.Builder<T> printableListElementsBuilder = ImmutableList.builder();

    for (final T element : listElements) {
        if (isPrintable(element.toString()))
            printableListElementsBuilder.add(element);
    }

    final ImmutableList<T> printableListElements = printableListElementsBuilder.build();

    // Handle the first three special cases
    if (printableListElements.isEmpty()) {
        return "";
    } else if (printableListElements.size() == 1) {
        return toCase(Iterables.getOnlyElement(printableListElements).toString(), letterCase);
    } else if (printableListElements.size() == 2) {
        final Iterator<T> iterator = printableListElements.iterator();

        // Here, if the separator is a comma, for example, it's either:
        // "item1 and item2" or "item1,item2" (if no "and" is desired)
        // because "item1, and item2" doesn't make sense grammatically, which is
        // what would happen if we didn't treat this as a special case
        return toCase(iterator.next().toString() + (hasAnd ? " and " : separator) + iterator.next().toString(),
                letterCase);
    }

    final StringBuilder s = new StringBuilder();

    for (final T element : printableListElements) {
        final String elementString = toCase(element.toString(), letterCase);

        s.append(elementString).append(separator);
    }

    try {
        // Delete the extra comma at the end of the last element in the list.
        s.delete(s.length() - separator.length(), s.length());

        if (hasAnd && s.lastIndexOf(separator) >= 0) {
            // Insert the word 'and' between the last two elements in the list,
            // after the last comma.
            s.insert(s.lastIndexOf(separator) + 1, "and ");
        }
    } catch (final StringIndexOutOfBoundsException ignored) {
    }

    return s.toString();
}

From source file:net.sourceforge.fenixedu.util.UniqueAcronymCreator.java

private static void appendLast(StringBuilder acronym) {
    if (logger.isDebugEnabled()) {
        logger.info("appendLast, called with " + acronym);
    }/*  w w w .j a v  a2  s .com*/

    for (int i = splitsName.length - 1; i > -1; i--) {
        if (!isValidAcception(splitsName[i]) && splitsName[i].length() >= 3
                && !isValidNumeration(splitsName[i])) {
            String toAppend = splitsName[i].substring(1, 3);
            toAppend = (toLowerCase) ? toAppend.toLowerCase() : toAppend.toUpperCase();

            if (acronym.toString().contains("-")) {
                int hiffen = acronym.toString().indexOf("-");
                if ((hiffen + 1 < acronym.toString().length())
                        && (isValidNumeration(String.valueOf(acronym.charAt(hiffen + 1)))
                                || hasNumber(String.valueOf(acronym.charAt(hiffen + 1))))) {
                    acronym.insert(hiffen, toAppend);
                    if (logger.isDebugEnabled()) {
                        logger.info("appendLast, found a '-', appending before hiffen " + toAppend);
                    }
                } else {
                    acronym.append(toAppend);
                    if (logger.isDebugEnabled()) {
                        logger.info("appendLast, found a '-', appending in end " + toAppend);
                    }
                }

            } else {
                if (logger.isDebugEnabled()) {
                    logger.info("appendLast, appending " + toAppend);
                }
                acronym.append(toAppend);
            }

            break;
        }
    }
}

From source file:net.ymate.platform.webmvc.support.WebCacheProcessor.java

private String __doBuildCacheKey(HttpServletRequest request, ResponseCache responseCache) {
    // KEY//  w w w .jav a 2 s. com
    StringBuilder _keyBuilder = new StringBuilder().append(ResponseCache.class.getName())
            .append(I18N.current());
    if (StringUtils.isNotBlank(responseCache.key())) {
        _keyBuilder.append(":").append(responseCache.key());
    } else {
        _keyBuilder.append(":").append(request.getMethod()).append(":").append(request.getRequestURI())
                .append(":").append(request.getQueryString());
    }
    if (responseCache.scope().equals(ICaches.Scope.SESSION)) {
        _keyBuilder.insert(0, "|").insert(0, request.getSession().getId());
    }
    return DigestUtils.md5Hex(_keyBuilder.toString());
}