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.smartitengineering.cms.spi.impl.content.search.ContentSearcherImpl.java

public static String generateDateQuery(String fieldName, QueryParameter<Date> creationDateFilter) {
    StringBuilder query = new StringBuilder(fieldName).append(": ");
    String dateQuery = "";
    switch (creationDateFilter.getParameterType()) {
    case PARAMETER_TYPE_PROPERTY:
        if (creationDateFilter instanceof UniOperandQueryParameter) {
            UniOperandQueryParameter<Date> param = (UniOperandQueryParameter<Date>) creationDateFilter;
            switch (param.getOperatorType()) {
            case OPERATOR_EQUAL:
                dateQuery = formatDateInSolrFormat(param.getValue());
                break;
            case OPERATOR_LESSER:
                query.insert(0, "NOT ");
                dateQuery = "[" + formatDateInSolrFormat(param.getValue()) + " TO *]";
                //              dateQuery = "-[" + param.getValue() + " TO *]";
                break;
            case OPERATOR_GREATER_EQUAL:
                dateQuery = "[" + formatDateInSolrFormat(param.getValue()) + " TO *]";
                break;
            case OPERATOR_GREATER:
                query.insert(0, "NOT ");
                dateQuery = "[* TO " + formatDateInSolrFormat(param.getValue()) + "]";
                //              dateQuery = "-[* TO " + param.getValue() + "]";
                break;
            case OPERATOR_LESSER_EQUAL:
                dateQuery = "[* TO " + formatDateInSolrFormat(param.getValue()) + "]";
                break;
            default:
                dateQuery = "[* TO *]";
            }/* ww w  .  jav a 2 s .  c  o  m*/
        }
        if (creationDateFilter instanceof BiOperandQueryParameter) {
            BiOperandQueryParameter<Date> param = (BiOperandQueryParameter<Date>) creationDateFilter;
            if (param.getOperatorType().equals(OperatorType.OPERATOR_BETWEEN)) {
                dateQuery = "[" + formatDateInSolrFormat(param.getFirstValue()) + " TO "
                        + formatDateInSolrFormat(param.getSecondValue()) + "]";
            }
        }
        break;
    default:
        UniOperandQueryParameter<Date> param = (UniOperandQueryParameter<Date>) creationDateFilter;
        dateQuery = param.getPropertyName() + ": [* TO *]";
        break;
    }
    query.append(dateQuery);
    return query.toString();
}

From source file:com.edgenius.wiki.render.RenderUtil.java

/**
 * @param text//from  ww w  .java 2  s  . c  o  m
 * @param key
 * @param regions
 */
public static CharSequence createRegionBorder(CharSequence text, String key, Collection<Region> regions,
        String newlineKey) {
    if (regions == null || regions.size() == 0)
        return text;

    //sort border separators from end to start, so that it can easily insert into whole text from end to start,
    //and need not care about string change

    //the key is border point value, value is Set as it may have duplicated start or end in same point.
    Map<Integer, Set<RegionBorderPoint>> borders = new TreeMap<Integer, Set<RegionBorderPoint>>(
            new CompareToComparator(
                    CompareToComparator.TYPE_OVERWRITE_SAME_VALUE | CompareToComparator.DESCEND));

    int index = 1;
    for (Region region : regions) {
        int start = region.getStart();
        int end = region.getEnd();
        String newlineFix = new StringBuilder(text.subSequence(start, end)).indexOf("\n") == -1 ? ""
                : newlineKey;
        String regionKey = key + index + newlineFix;
        region.setKey(index + newlineFix);
        region.setKeyIndex(index);
        //~~~~~~~~~ start
        Set<RegionBorderPoint> list = borders.get(start);
        if (list == null) {
            list = new TreeSet<RegionBorderPoint>(new RegionBorderPointComparator());
            list.add(new RegionBorderPoint(start, true, end, regionKey, index));
            borders.put(start, list);
        } else {
            list.add(new RegionBorderPoint(start, true, end, regionKey, index));
        }
        //~~~~~~~~~ end
        list = borders.get(end);
        if (list == null) {
            list = new TreeSet<RegionBorderPoint>(new RegionBorderPointComparator());
            list.add(new RegionBorderPoint(end, false, start, regionKey, index));
            borders.put(end, list);
        } else {
            list.add(new RegionBorderPoint(end, false, start, regionKey, index));
        }
        index++;
    }

    //ok, here will do insert border key into original string 
    StringBuilder sb = new StringBuilder(text);
    //on behalf of above sort result, insert is simple, just looping borderPoint one by one as new insert won't impact 
    //the others un-inserted point location.
    for (Set<RegionBorderPoint> set : borders.values()) {
        for (RegionBorderPoint point : set) {
            String regionKey = point.getRegionKey() + (point.isStart() ? "S" : "E");
            sb.insert(point.getPoint(), regionKey);
        }
    }
    return sb;

}

From source file:Main.java

public static Pair<String, String> ReorderRTLTextForPebble(String source, int charLimit) {
    if (source == null || source.equals(""))
        return new Pair<>("", "");

    if (!hebrewPattern.matcher(source).find()) {
        return new Pair<>(source, "");
    } else {//from   w  ww .ja  v a  2s .  c  o m

        StringBuilder sbResult = new StringBuilder();
        StringBuilder sbExtraResult = new StringBuilder();
        StringBuilder sbTemp = new StringBuilder();
        String[] words = source.split(" ");
        int charCount = 0;

        for (int wordIndex = 0; wordIndex < words.length; wordIndex++, sbTemp.setLength(0)) {
            sbTemp.append(words[wordIndex]);
            charCount += sbTemp.length();
            Matcher hebrewWord = hebrewPattern.matcher(words[wordIndex]);

            if (hebrewWord.find()) {
                sbTemp.reverse();
                if (sbTemp.charAt(0) == ')') {
                    sbTemp.replace(0, 1, "(");
                }
                if (sbTemp.charAt(sbTemp.length() - 1) == '(') {
                    sbTemp.replace(sbTemp.length() - 1, sbTemp.length(), ")");
                }
            }

            if (charCount <= charLimit) {
                sbResult.insert(0, sbTemp + " ");
            } else {
                sbExtraResult.insert(0, sbTemp + " ");
            }

            charCount++;
        }

        if (sbExtraResult.length() > charLimit) {
            sbExtraResult.replace(0, sbExtraResult.length() - charLimit, "...");
        }

        return new Pair<>(sbResult.toString().trim(), sbExtraResult.toString().trim());
    }
}

From source file:net.netheos.pcsapi.providers.hubic.Swift.java

static Date parseLastModified(JSONObject json) {
    try {/*  ww w  . j ava2s  .  co  m*/
        String lm = json.optString("last_modified", null); // "2014-02-12T16:13:49.346540"
        if (lm == null) {
            return null;
        }

        // Date format
        if (!lm.contains("+")) {
            lm += "+0000";
        }

        // Normalize millis and remove microseconds, if any:
        StringBuilder builder = new StringBuilder(lm);
        int dotPos = lm.indexOf('.');
        int plusPos = lm.indexOf('+');
        if (dotPos > 0) {
            if (plusPos - dotPos > 4) {
                builder.delete(dotPos + 4, plusPos); // remove microsec
            } else
                while (plusPos - dotPos < 4) { // complete millis : ".3" -> ".300"
                    builder.insert(plusPos, '0');
                    plusPos++;
                }
        } else { // no milliseconds ? defensive code
            builder.insert(plusPos, ".000");
        }
        DateFormat lastModifiedDateFormat = new SimpleDateFormat(DF_LAST_MODIFIED_PATTERN, Locale.ENGLISH);
        return lastModifiedDateFormat.parse(builder.toString());

    } catch (ParseException ex) {
        LOGGER.warn("Error parsing date", ex);
        return null;
    }
}

From source file:com.p000ison.dev.simpleclans2.api.chat.ChatBlock.java

/**
 * Pads the string left in the {@link StringBuilder}.
 *
 * @param text   The message to pad left.
 * @param length The lenght it of the section it should be pad left.
 *//*from w  w w. j a va 2s .  c o m*/
public static void padLeft(StringBuilder text, double length) {
    if (text == null || text.length() == 0) {
        throw new IllegalArgumentException("The text can not be null or empty!");
    }

    double msgLength = msgLength(text);

    if (msgLength > length) {
        return;
    }

    StringBuilder empty = new StringBuilder();

    while (msgLength < length) {
        msgLength += 4;
        empty.append(' ');
    }

    text.insert(0, empty);
}

From source file:io.github.tavernaextras.biocatalogue.model.Util.java

/**
 * Appends given string at the end of the provided URL just before the list of parameters in the url.
 * /*from   www .  j ava  2  s. c  o m*/
 * For example, appending ".xml" to URL "http://www.sandbox.biocatalogue.org/services?tag=blast" will
 * yield "http://www.sandbox.biocatalogue.org/services.xml?tag=blast".
 * 
 * No duplication checking is made - if the URL is already ending (before parameters) with the value of
 * the string to append, that string will still be appended.
 * 
 * @param url URL to append the string to.
 * @param strToAppend The string to append. The value will be url-encode before appending.
 * @return New string containing modified <code>url</code> with the <code>strToAppend</code> appended
 *         before the "query string" of the URL.
 */
public static String appendStringBeforeParametersOfURL(String url, String strToAppend,
        boolean ignoreURLEncoding) {
    StringBuilder modifiedURL = new StringBuilder(url);

    int iPositionToInsertProvidedString = modifiedURL.indexOf("?");
    if (iPositionToInsertProvidedString == -1)
        iPositionToInsertProvidedString = modifiedURL.length();

    String stringToInsert = (ignoreURLEncoding ? strToAppend : Util.urlEncodeQuery(strToAppend));
    modifiedURL.insert(iPositionToInsertProvidedString, stringToInsert);

    return (modifiedURL.toString());
}

From source file:com.google.gerrit.sshd.SshUtil.java

/**
 * Convert an RFC 4716 style key to an OpenSSH style key.
 *
 * @param keyStr the key string to convert.
 * @return <code>keyStr</code> if conversion failed; otherwise the converted
 *         key, in OpenSSH key format.//from  w  w w .  j  av  a 2  s  .  co m
 */
public static String toOpenSshPublicKey(final String keyStr) {
    try {
        final StringBuilder strBuf = new StringBuilder();
        final BufferedReader br = new BufferedReader(new StringReader(keyStr));
        String line = br.readLine(); // BEGIN SSH2 line...
        if (!line.equals("---- BEGIN SSH2 PUBLIC KEY ----")) {
            return keyStr;
        }

        while ((line = br.readLine()) != null) {
            if (line.indexOf(':') == -1) {
                strBuf.append(line);
                break;
            }
        }

        while ((line = br.readLine()) != null) {
            if (line.startsWith("---- ")) {
                break;
            }
            strBuf.append(line);
        }

        final PublicKey key = new Buffer(Base64.decodeBase64(Constants.encodeASCII(strBuf.toString())))
                .getRawPublicKey();
        if (key instanceof RSAPublicKey) {
            strBuf.insert(0, KeyPairProvider.SSH_RSA + " ");

        } else if (key instanceof DSAPublicKey) {
            strBuf.insert(0, KeyPairProvider.SSH_DSS + " ");

        } else {
            return keyStr;
        }

        strBuf.append(' ');
        strBuf.append("converted-key");
        return strBuf.toString();
    } catch (IOException e) {
        return keyStr;
    } catch (RuntimeException re) {
        return keyStr;
    }
}

From source file:de.weltraumschaf.groundzero.filter.FileNameExtender.java

@Override
public String process(final String input) {
    Validate.notNull(input);/*w ww.jav  a  2 s.c  om*/
    final StringBuilder buffer = new StringBuilder(input);
    buffer.insert(input.lastIndexOf('.'), extension);
    return buffer.toString();
}

From source file:com.untangle.app.web_filter.WebFilterDecisionEngine.java

/**
 * Encode a URL//from w  w w  .  j  a  v a 2s  . c  om
 * 
 * @param domain
 *        The domain
 * @param uri
 *        The URI
 * @return The encoded URL
 */
private static String encodeUrl(String domain, String uri) {
    // Remote trailing dots from domain
    Matcher matcher = trailingDotsPattern.matcher(domain);
    domain = matcher.replaceAll("");

    String url = domain + uri;

    // Remote trailing dots or slashes from URL
    matcher = trailingDotsSlashesPattern.matcher(url);
    url = matcher.replaceAll("");

    StringBuilder qBuilder = new StringBuilder(url);

    int i;
    int lastDot = 0;

    for (i = 0; i < qBuilder.length(); i++) {

        int numCharsAfterThisOne = (qBuilder.length() - i) - 1;

        // Must insert a null escape to divide long spans
        if (i > lastDot + 59) {
            qBuilder.insert(i, "_-0.");
            lastDot = i + 3;
            i += 4;
        }

        if (qBuilder.charAt(i) == '.') {
            lastDot = i;
        }
        // Take care of the rare, but possible case of _- being in the string
        else if (qBuilder.charAt(i) == '_' && numCharsAfterThisOne >= 1 && qBuilder.charAt(i + 1) == '-') {
            qBuilder.replace(i, i + 2, "_-_-");
            i += 4;
        }
        // Convert / to rfc compliant characters _-.
        else if (qBuilder.charAt(i) == '/') {
            qBuilder.replace(i, i + 1, "_-.");
            lastDot = i + 2;
            i += 3;
        }
        // Convert any dots next to each other
        else if (qBuilder.charAt(i) == '.' && numCharsAfterThisOne >= 1 && qBuilder.charAt(i + 1) == '.') {
            qBuilder.replace(i, i + 2, "._-2e");
            i += 5;
        }
        // Convert any dots at the end. (these should have already been stripped but the zvelo implementation has this here)
        else if (qBuilder.charAt(i) == '.' && numCharsAfterThisOne == 0) {
            qBuilder.replace(i, i + 1, "_-2e");
            i += 4;
        }
        // Convert : to _--
        else if (qBuilder.charAt(i) == ':') {
            qBuilder.replace(i, i + 1, "_--");
            i += 3;
        }
        // Drop everything after ? or #
        else if (qBuilder.charAt(i) == '?' || qBuilder.charAt(i) == '#') {
            qBuilder.delete(i, qBuilder.length());
            break;
        }
        // Convert %HEXHEX to encoded form
        else if (qBuilder.charAt(i) == '%' && numCharsAfterThisOne >= 2 && _isHex(qBuilder.charAt(i + 1))
                && _isHex(qBuilder.charAt(i + 2))) {
            //String hexString = new String(new char[] {qBuilder.charAt(i+1), qBuilder.charAt(i+2)});
            //char c = (char)( Integer.parseInt( hexString , 16) );
            //System.out.println("HEX: \"" + hexString +"\" -> \"" + Character.toString(c) + "\"");
            qBuilder.replace(i, i + 1, "_-");
            i += 4; // 2 for length of replacement + 2 for the hex characters
        }
        // Convert % charaters to encoded form
        else if (qBuilder.charAt(i) == '%') {
            qBuilder.replace(i, i + 1, "_-25");
            i += 4;
        }
        // Convert any remaining non-RFC characters.
        else if (!_isRfc(qBuilder.charAt(i))) {
            String replaceStr = String.format("_-%02X", ((byte) qBuilder.charAt(i)));
            qBuilder.replace(i, i + 1, replaceStr);
            i += 4;
        }
    }

    return qBuilder.toString();
}

From source file:DOMTreeTest.java

public static String characterString(CharacterData node) {
        StringBuilder builder = new StringBuilder(node.getData());
        for (int i = 0; i < builder.length(); i++) {
            if (builder.charAt(i) == '\r') {
                builder.replace(i, i + 1, "\\r");
                i++;// w ww. ja va2  s.c  om
            } else if (builder.charAt(i) == '\n') {
                builder.replace(i, i + 1, "\\n");
                i++;
            } else if (builder.charAt(i) == '\t') {
                builder.replace(i, i + 1, "\\t");
                i++;
            }
        }
        if (node instanceof CDATASection)
            builder.insert(0, "CDATASection: ");
        else if (node instanceof Text)
            builder.insert(0, "Text: ");
        else if (node instanceof Comment)
            builder.insert(0, "Comment: ");

        return builder.toString();
    }