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:brut.androlib.res.xml.ResXmlEncoders.java

public static String encodeAsXmlValue(String str) {
    if (str.isEmpty()) {
        return str;
    }/*from  ww  w . ja  v  a 2  s .  co m*/

    char[] chars = str.toCharArray();
    StringBuilder out = new StringBuilder(str.length() + 10);

    switch (chars[0]) {
    case '#':
    case '@':
    case '?':
        out.append('\\');
    }

    boolean isInStyleTag = false;
    int startPos = 0;
    boolean enclose = false;
    boolean wasSpace = true;
    for (char c : chars) {
        if (isInStyleTag) {
            if (c == '>') {
                isInStyleTag = false;
                startPos = out.length() + 1;
                enclose = false;
            }
        } else if (c == ' ') {
            if (wasSpace) {
                enclose = true;
            }
            wasSpace = true;
        } else {
            wasSpace = false;
            switch (c) {
            case '\\':
                out.append('\\');
                break;
            case '\'':
            case '\n':
                enclose = true;
                break;
            case '"':
                out.append('\\');
                break;
            case '<':
                isInStyleTag = true;
                if (enclose) {
                    out.insert(startPos, '"').append('"');
                }
                break;
            default:
                if (!isPrintableChar(c)) {

                    // lets not write trailing \u0000 if we are at end of string
                    if ((out.length() + 1) == str.length() && c == '\u0000') {
                        continue;
                    }
                    out.append(String.format("\\u%04x", (int) c));
                    continue;
                }
            }
        }
        out.append(c);
    }

    if (enclose || wasSpace) {
        out.insert(startPos, '"').append('"');
    }
    return out.toString();
}

From source file:com.smartitengineering.util.opensearch.io.impl.dom.DomIOImplTest.java

public void testWrite() {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    OpenSearchDescriptorWriter writer = new OpenSearchDescriptorWriter(outputStream, MAX_DESC, true);
    try {/* w  w w .ja  v  a  2s .c  o  m*/
        final long start = System.currentTimeMillis();
        writer.write();
        final long end = System.currentTimeMillis();
        System.out.println("Time taken to write: " + (end - start));
    } catch (IOException ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
    final String toString = outputStream.toString();
    System.out.println(toString);
    assertEquals(MAX, toString);

    outputStream = new ByteArrayOutputStream();
    MAX_BUILDER.queries(OpenSearchAPIBuilders.getQueryBuilder().searchTerms("some terms")
            .customAttribute("xmlns:cns", "http://google.com/1.1").customAttribute("cns:add", "value").build());
    writer = new OpenSearchDescriptorWriter(outputStream, MAX_BUILDER.build(), true);
    try {
        final long start = System.currentTimeMillis();
        writer.write();
        final long end = System.currentTimeMillis();
        System.out.println("Time taken to write: " + (end - start));
    } catch (IOException ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
    final String extendedString = outputStream.toString();
    System.out.println(extendedString);
    StringBuilder newStringBuilder = new StringBuilder(MAX);
    int insertionPoint = newStringBuilder.indexOf("<Developer>");
    String additionalString = "<Query xmlns:cns=\"http://google.com/1.1\" cns:add=\"value\" role=\"example\" "
            + "searchTerms=\"some terms\" />";
    newStringBuilder.insert(insertionPoint, additionalString);
    assertEquals(newStringBuilder.toString(), extendedString);
}

From source file:org.jclouds.logging.internal.Wire.java

private void wire(String header, InputStream instream) {
    StringBuilder buffer = new StringBuilder();
    int ch;//  w  w  w .ja v  a2 s. c o  m
    try {
        while ((ch = instream.read()) != -1) {
            if (ch == 13) {
                buffer.append("[\\r]");
            } else if (ch == 10) {
                buffer.append("[\\n]\"");
                buffer.insert(0, "\"");
                buffer.insert(0, header);
                getWireLog().debug(buffer.toString());
                buffer.setLength(0);
            } else if ((ch < 32) || (ch > 127)) {
                buffer.append("[0x");
                buffer.append(Integer.toHexString(ch));
                buffer.append("]");
            } else {
                buffer.append((char) ch);
            }
        }
        if (buffer.length() > 0) {
            buffer.append('\"');
            buffer.insert(0, '\"');
            buffer.insert(0, header);
            getWireLog().debug(buffer.toString());
        }
    } catch (IOException e) {
        logger.error(e, "Error tapping line");
    }
}

From source file:com.github.nmorel.gwtjackson.rebind.ObjectMapperCreator.java

/**
 * Creates the implementation of the interface denoted by interfaceClass and extending {@link ObjectMapper}
 *
 * @param interfaceClass the interface to generate an implementation
 *
 * @return the fully qualified name of the created class
 * @throws UnableToCompleteException//from www.j  a  v a 2  s. c  o m
 */
public String create(JClassType interfaceClass) throws UnableToCompleteException {
    // We concatenate the name of all the enclosing class.
    StringBuilder builder = new StringBuilder(interfaceClass.getSimpleSourceName() + "Impl");
    JClassType enclosingType = interfaceClass.getEnclosingType();
    while (null != enclosingType) {
        builder.insert(0, enclosingType.getSimpleSourceName() + "_");
        enclosingType = enclosingType.getEnclosingType();
    }

    String mapperClassSimpleName = builder.toString();
    String packageName = interfaceClass.getPackage().getName();
    String qualifiedMapperClassName = packageName + "." + mapperClassSimpleName;

    PrintWriter printWriter = getPrintWriter(packageName, mapperClassSimpleName);
    // The class already exists, no need to continue.
    if (printWriter == null) {
        return qualifiedMapperClassName;
    }

    try {
        // Extract the type of the object to map.
        JClassType mappedTypeClass = extractMappedType(interfaceClass);

        boolean reader = typeOracle.isObjectReader(interfaceClass);
        boolean writer = typeOracle.isObjectWriter(interfaceClass);
        Class<?> abstractClass;
        if (reader) {
            if (writer) {
                abstractClass = AbstractObjectMapper.class;
            } else {
                abstractClass = AbstractObjectReader.class;
            }
        } else {
            abstractClass = AbstractObjectWriter.class;
        }

        TypeSpec.Builder mapperBuilder = TypeSpec.classBuilder(mapperClassSimpleName)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL).addSuperinterface(typeName(interfaceClass))
                .superclass(parameterizedName(abstractClass, mappedTypeClass))
                .addMethod(buildConstructor(mappedTypeClass));

        if (reader) {
            mapperBuilder.addMethod(buildNewDeserializerMethod(mappedTypeClass));
        }

        if (writer) {
            mapperBuilder.addMethod(buildNewSerializerMethod(mappedTypeClass));
        }

        write(packageName, mapperBuilder.build(), printWriter);
    } finally {
        printWriter.close();
    }

    return qualifiedMapperClassName;
}

From source file:com.taobao.adfs.util.Utilities.java

public static String deepToString(Object object) {
    if (object == null) {
        return "null";
    } else if (object instanceof Throwable) {
        return getThrowableStackTrace((Throwable) object);
    } else if (object.getClass().isEnum()) {
        return object.toString();
    } else if (object.getClass().isArray()) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(object.getClass().getSimpleName());
        int length = Array.getLength(object);
        stringBuilder.insert(stringBuilder.length() - 1, Array.getLength(object)).append("{");
        for (int i = 0; i < length; i++) {
            stringBuilder.append(deepToString(Array.get(object, i)));
            if (i < length - 1)
                stringBuilder.append(',');
        }/*from   w ww .ja v a  2  s.  c  o m*/
        return stringBuilder.append("}").toString();
    } else if (List.class.isAssignableFrom(object.getClass())) {
        List<?> listObject = ((List<?>) object);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(object.getClass().getSimpleName()).append('[').append(listObject.size())
                .append(']');
        stringBuilder.append("{");
        for (Object subObject : listObject) {
            stringBuilder.append(deepToString(subObject)).append(',');
        }
        if (!listObject.isEmpty())
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        return stringBuilder.append('}').toString();
    } else {
        try {
            Method toStringMethod = Invocation.getPublicMethod(object.getClass(), "toString");
            if (toStringMethod.getDeclaringClass() == Object.class)
                return toStringByFields(object, false);
        } catch (Throwable t) {
        }
        try {
            return object.toString();
        } catch (Throwable t) {
            return "FailToString";
        }
    }
}

From source file:com.smartitengineering.util.opensearch.io.impl.dom.DomIOImplTest.java

public void testRead() {
    OpenSearchDescriptorParser parser = new OpenSearchDescriptorParser(IOUtils.toInputStream(MIN));
    try {/*from www. ja va  2  s .c  o  m*/
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final OpenSearchDescriptor parsedDesc = parser.parse();
        OpenSearchDescriptorWriter writer = new OpenSearchDescriptorWriter(outputStream, parsedDesc, true);
        writer.write();
        final String toString = outputStream.toString();
        System.out.println(toString);
        assertEquals(MIN, toString);
    } catch (IOException ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
    parser = new OpenSearchDescriptorParser(IOUtils.toInputStream(MAX));
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final OpenSearchDescriptor parsedDesc = parser.parse();
        OpenSearchDescriptorWriter writer = new OpenSearchDescriptorWriter(outputStream, parsedDesc, true);
        writer.write();
        final String toString = outputStream.toString();
        System.out.println(toString);
        assertEquals(MAX, toString);
    } catch (IOException ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
    StringBuilder newStringBuilder = new StringBuilder(MAX);
    int insertionPoint = newStringBuilder.indexOf("<Developer>");
    String additionalString = "<Query xmlns:cns=\"http://google.com/1.1\" cns:add=\"value\" role=\"example\" "
            + "searchTerms=\"some terms\" />";
    newStringBuilder.insert(insertionPoint, additionalString);
    parser = new OpenSearchDescriptorParser(IOUtils.toInputStream(newStringBuilder.toString()));
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final OpenSearchDescriptor parsedDesc = parser.parse();
        OpenSearchDescriptorWriter writer = new OpenSearchDescriptorWriter(outputStream, parsedDesc, true);
        writer.write();
        final String toString = outputStream.toString();
        System.out.println(toString);
        assertEquals(newStringBuilder.toString(), toString);
    } catch (IOException ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
}

From source file:com.raja.knowme.FragmentProfile.java

private void setUIData(int count) {
    mHeaderSwitcher.setText(mProfileDetails.get(count).getHeader());
    StringBuilder sb = new StringBuilder();
    for (int counter = 0; counter < mProfileDetails.get(count).getDetailsData().size(); counter++)
        sb.insert(sb.lastIndexOf(sb.toString()),
                mProfileDetails.get(count).getDetailsData().get(counter) + "\n\n");
    mBodySwitcher.setText(sb.toString());
}

From source file:ch.mlutz.plugins.t4e.tapestry.element.TapestryHtmlElement.java

public String getPath() {
    StringBuilder sb = new StringBuilder();
    IContainer webAppFolder = parent.getWebappFolder();
    IContainer currentContainer = htmlFile.getParent();
    while (!currentContainer.equals(webAppFolder)) {
        if (sb.length() > 0) {
            sb.insert(0, "/");
        }//www .j  av a 2s .co  m
        sb.insert(0, currentContainer.getName());
        currentContainer = currentContainer.getParent();
    }
    if (sb.length() > 0) {
        sb.append("/");
    }
    sb.append(FilenameUtils.getBaseName(htmlFile.getName()));
    return sb.toString();
}

From source file:de.hybris.platform.refund.RefundServiceTest.java

public void importCSVFromResources(final String fileName) throws ImpExException {
    final StringBuilder resource = new StringBuilder(fileName);
    if (!hasExtension(resource.toString())) {
        resource.append(CSV_EXTENSION);/*from  w  ww  . ja v  a 2s .c  o  m*/
    }
    if (!hasResourceFolder(resource.toString())) {
        resource.insert(0, CSV_RESOURCE_DIR);
    }

    final InputStream inStr = RefundServiceTest.class.getResourceAsStream(resource.toString());
    ImpExManager.getInstance().importDataLight(inStr, "UTF-8", true);
}

From source file:com.raja.knowme.FragmentTestimonials.java

private void setUIData(int count) {
    mHeaderSwitcher.setText(mTestimonialsDetails.get(count).getHeader());
    StringBuilder sb = new StringBuilder();
    for (int counter = 0; counter < mTestimonialsDetails.get(count).getDetailsData().size(); counter++)
        sb.insert(sb.lastIndexOf(sb.toString()),
                mTestimonialsDetails.get(count).getDetailsData().get(counter) + "\n\n");
    mBodySwitcher.setText(sb.toString());
}