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:ch.admin.suis.msghandler.util.FileUtils.java

/**
 * Returns a name of the file in the given directory. If the file with the provided name already exists in that
 * directory, this method returns a new name that is formed by adding the current timestamp value in milliseconds to
 * the provided name. Otherwise the name remains unchanged. This method returns the absolute filepath.
 *
 * @param inputDir where the file should be placed
 * @param name     current file name/*from   www .j  a  v a 2s.  co m*/
 * @return the absolute path inclusive filename
 */
public static String getFilename(final File inputDir, String name) {
    Validate.isTrue(inputDir.isDirectory(), inputDir.getAbsolutePath() + NOT_A_DIRECTORY);

    File local = new File(inputDir, name);
    if (local.exists()) {
        int count = COUNTER.incrementAndGet();
        count = count % MAX_FILE_COUNT; //

        int insertPos = name.lastIndexOf('.');
        if (insertPos >= 0) {
            // the dot is there, so replace it
            StringBuilder sb = new StringBuilder(name);
            String uniquePart = "-" + System.currentTimeMillis() + "-" + count;
            sb.insert(insertPos, uniquePart);
            return new File(inputDir, sb.toString()).getAbsolutePath();
        } else {
            // just add to the end
            return new File(inputDir, name + "-" + System.currentTimeMillis() + "-" + count).getAbsolutePath();
        }
    } else {
        // the file does not exist yet and can be written without any change to
        // its name
        return local.getAbsolutePath();
    }
}

From source file:net.certiv.json.util.Strings.java

/**
 * Returns the lines of the block prefixed with the indent string. Ensures a leading EOL
 * sequence and no trailing whitespace./* w w  w . ja  v a2s. c  o m*/
 *
 * @param ci
 * @param block
 * @return
 */
public static String indentBlock(String ci, String block) {
    if (block == null)
        return "<Error: indent include block is null>";
    StringReader sr = new StringReader(block);
    BufferedReader buf = new BufferedReader(sr);
    StringBuilder sb = new StringBuilder();
    String s;
    try {
        while ((s = buf.readLine()) != null) {
            sb.append(ci + s + Strings.eol);
        }
        char c = sb.charAt(0);
        if (c != '\n' && c != '\r') {
            sb.insert(0, eol);
        }
        return trimRight(sb.toString());
    } catch (IOException e) {
        sb.append("<Error indenting block: " + e.getMessage() + ">");
    }
    return sb.toString();
}

From source file:com.indoqa.lang.util.StringUtils.java

public static String escapeSolr(String value) {
    StringBuilder stringBuilder = new StringBuilder(value);

    for (int i = 0; i < stringBuilder.length(); i++) {
        boolean isCharacterToBeEscaped = Arrays.binarySearch(CHARACTERS_TO_BE_ESCAPED_FOR_SOLR,
                stringBuilder.charAt(i)) >= 0;
        if (isCharacterToBeEscaped) {
            stringBuilder.insert(i, '\\');
            i++;//  w w w.j  a va 2 s.com
        }
    }

    return stringBuilder.toString();
}

From source file:com.norconex.importer.ImporterLauncher.java

private static void writeResponse(ImporterResponse response, String outputPath, int depth, int index)
        throws IOException {
    if (!response.isSuccess()) {
        String statusLabel = "REJECTED: ";
        if (response.getImporterStatus().isError()) {
            statusLabel = "   ERROR: ";
        }/*from   ww w .  j  av  a2  s. co  m*/
        System.out.println(statusLabel + response.getReference() + " ("
                + response.getImporterStatus().getDescription() + ")");
    } else {
        ImporterDocument doc = response.getDocument();
        StringBuilder path = new StringBuilder(outputPath);
        if (depth > 0) {
            int pathLength = outputPath.length();
            int extLength = FilenameUtils.getExtension(outputPath).length();
            if (extLength > 0) {
                extLength++;
            }
            String nameSuffix = "_" + depth + "-" + index;
            path.insert(pathLength - extLength, nameSuffix);
        }
        File docfile = new File(path.toString());
        File metafile = new File(path.toString() + ".meta");

        // Write document file
        FileOutputStream docOutStream = new FileOutputStream(docfile);
        CachedInputStream docInStream = doc.getContent();

        FileOutputStream metaOut = null;
        try {
            IOUtils.copy(docInStream, docOutStream);
            IOUtils.closeQuietly(docOutStream);
            IOUtils.closeQuietly(docInStream);

            // Write metadata file
            metaOut = new FileOutputStream(metafile);
            doc.getMetadata().store(metaOut, null);
            System.out.println("IMPORTED: " + response.getReference());
        } catch (IOException e) {
            System.err.println("Could not write: " + doc.getReference());
            e.printStackTrace(System.err);
            System.err.println();
            System.err.flush();
        } finally {
            IOUtils.closeQuietly(metaOut);
        }
    }

    ImporterResponse[] nextedResponses = response.getNestedResponses();
    for (int i = 0; i < nextedResponses.length; i++) {
        ImporterResponse nextedResponse = nextedResponses[i];
        writeResponse(nextedResponse, outputPath, depth + 1, i + 1);
    }
}

From source file:TextUtils.java

/**
 * Wraps the input string in {@code <html></html>} and breaks it up into
 * lines with {@code <br>} elements. Useful for making multi-line tootips
 * and the like./*w  w  w .j  a v a2  s  .com*/
 * 
 * @param s
 *            The input String
 * @param lineLength
 *            The desired length of the output lines.
 * @return The HTMLised string
 */
public static String HTMLiseString(String s, int lineLength) {
    if (s != null) {
        StringBuilder buff = new StringBuilder(s);

        int lineStart = 0;

        while (lineStart + lineLength < s.length()) {
            // find the first whitespace after the linelength
            int firstSpaceIndex = buff.indexOf(" ", lineStart + lineLength);
            // replace it with a <br>
            if (firstSpaceIndex != -1) {
                buff.deleteCharAt(firstSpaceIndex);
                buff.insert(firstSpaceIndex, "<br>");
                lineStart = firstSpaceIndex + 4;
            } else {
                lineStart = s.length();
            }
        }

        buff.insert(0, "<html>");
        buff.append("</html>");

        return buff.toString();
    }

    return null;
}

From source file:com.hmsinc.epicenter.surveillance.notification.EventNotifierUtils.java

public static String makeAgeGroupAndGenderString(final Anomaly anomaly) {

    // Just do this in Java because it's too goofy in Velocity
    final String genders = StringUtils.trimToNull(makeAttributeString(
            anomaly.getSet().getAttribute(com.hmsinc.epicenter.model.attribute.Gender.class)));
    final String ageGroups = StringUtils.trimToNull(makeAttributeString(
            anomaly.getSet().getAttribute(com.hmsinc.epicenter.model.attribute.AgeGroup.class)));

    final StringBuilder sb = new StringBuilder();
    if (genders != null || ageGroups != null) {
        if (ageGroups != null) {
            sb.append("grouped by age as ").append(ageGroups);
        }//from   w ww  .  ja  v a 2s .c om
        if (genders != null) {
            if (sb.length() > 0) {
                sb.append("; and ");
            }
            sb.append("grouped by gender as ").append(genders);
        }
        sb.append(") ");
        sb.insert(0, "(for patients ");
    }

    return sb.toString();
}

From source file:com.jaspersoft.jasperserver.core.util.StringUtil.java

/**
 * Replaces all occurrences of a string in a buffer with another.
 *
 * @param buf String buffer to act on/*from   w w w. jav  a  2s  .  c  om*/
 * @param start Ordinal within <code>find</code> to start searching
 * @param find String to find
 * @param replace String to replace it with
 * @return The string buffer
 */
public static StringBuilder replace(StringBuilder buf, int start, String find, String replace) {
    // Search and replace from the end towards the start, to avoid O(n ^ 2)
    // copying if the string occurs very commonly.
    int findLength = find.length();
    if (findLength == 0) {
        // Special case where the seek string is empty.
        for (int j = buf.length(); j >= 0; --j) {
            buf.insert(j, replace);
        }
        return buf;
    }
    int k = buf.length();
    while (k > 0) {
        int i = buf.lastIndexOf(find, k);
        if (i < start) {
            break;
        }
        buf.replace(i, i + find.length(), replace);
        // Step back far enough to ensure that the beginning of the section
        // we just replaced does not cause a match.
        k = i - findLength;
    }
    return buf;
}

From source file:Main.java

public static String fillTextBox(TextPaint paint, int fragmentWidth, String source, int start) {
    StringBuilder sb = new StringBuilder();
    final int length = source.length();
    int indexLeft = start;
    int indexRight = start + 1;
    int lastWhiteSpaceL = 0;
    int lastWhiteSpaceR = 0;
    while (paint.measureText(sb.toString()) < fragmentWidth && (indexLeft >= 0 || indexRight < length)) {
        if (indexLeft >= 0) {
            char c = source.charAt(indexLeft);
            if (Character.isWhitespace(c))
                lastWhiteSpaceL = indexLeft;
            sb.insert(0, c);
            indexLeft--;/*from   w ww  . j a  va 2  s  . c o  m*/
        }

        if (indexRight < length) {
            char c = source.charAt(indexRight);
            if (Character.isWhitespace(c))
                lastWhiteSpaceR = indexRight;
            sb.append(c);
            indexRight++;
        }
    }

    if (indexLeft >= 0) {
        // Delete first word part
        sb.delete(0, lastWhiteSpaceL - indexLeft);
        sb.insert(0, "...");
        indexLeft = lastWhiteSpaceL - 3; // Set new index left
    }

    if (indexRight < length) {
        // Delete last word part
        sb.delete(lastWhiteSpaceR - (indexLeft + 1), sb.length());
        sb.append("...");
    }

    return sb.toString();
}

From source file:cc.recommenders.names.CoReNames.java

private static String internal_vm2srcTypeName(final char[] buf, final int off) {
    ensureIsNotNull(buf, "buf");
    ////  www  .  j a  v  a2  s . c  o  m
    int len;
    switch (buf[off]) {
    case 'V':
        return VOID;
    case 'Z':
        return BOOLEAN;
    case 'C':
        return CHAR;
    case 'B':
        return BYTE;
    case 'S':
        return SHORT;
    case 'I':
        return INT;
    case 'F':
        return FLOAT;
    case 'J':
        return LONG;
    case 'D':
        return DOUBLE;
    case '[':
        final StringBuilder sb = new StringBuilder();
        sb.append("[]");
        len = 1;
        while (buf[off + len] == '[') {
            sb.append("[]");
            ++len;
        }
        sb.insert(0, internal_vm2srcTypeName(buf, off + len));
        return sb.toString();
    case 'L':
        len = 1;
        while (off + len < buf.length && buf[off + len] != ';') {
            ++len;
        }
        final String s1 = new String(buf, off + 1, len - 1).replaceAll("/", ".");
        final String s2 = s1.replaceAll("\\$", ".");
        return s2;
    default:
        throw throwUnreachable("couldn't handle '%s'", buf);
    }
}

From source file:com.adaptris.core.marshaller.xstream.XStreamUtils.java

/**
* Converts a camelcase name into a lowercase hyphen separated format for output to XML. Used by the marshalling process to
* convert a java class/field name into an xml element name.
* 
* @param fieldName - Current element name to be processed.
* @return translated name//from  www  .  j  av a  2 s  .c  o  m
*/
public static String toXmlElementName(String fieldName) {
    if (fieldName == null) {
        return null;
    }
    if (fieldName.length() == 0) {
        return fieldName;
    }
    if (fieldName.length() == 1) {
        return fieldName.toLowerCase();
    }

    // -- Follow the Java beans Introspector::decapitalize
    // -- convention by leaving alone String that start with
    // -- 2 uppercase characters.
    if (Character.isUpperCase(fieldName.charAt(0)) && Character.isUpperCase(fieldName.charAt(1))) {
        return fieldName;
    }

    // -- process each character
    StringBuilder cbuff = new StringBuilder(fieldName);
    cbuff.setCharAt(0, Character.toLowerCase(cbuff.charAt(0)));

    boolean ucPrev = false;
    for (int i = 1; i < cbuff.length(); i++) {
        char ch = cbuff.charAt(i);
        if (Character.isUpperCase(ch)) {
            if (ucPrev) {
                continue;
            }
            ucPrev = true;
            cbuff.insert(i, '-');
            ++i;
            cbuff.setCharAt(i, Character.toLowerCase(ch));
        } else {
            ucPrev = false;
        }
    }
    return cbuff.toString();
}