Example usage for java.lang StringBuffer setCharAt

List of usage examples for java.lang StringBuffer setCharAt

Introduction

In this page you can find the example usage for java.lang StringBuffer setCharAt.

Prototype

@Override
public synchronized void setCharAt(int index, char ch) 

Source Link

Usage

From source file:net.fenyo.gnetwatch.activities.Capture.java

/**
 * Reads tethereal standard output and extracts frames one by one.
 * @param none.//from   ww w . java  2 s.  c  o m
 * @return void.
 */
// Capture thread
public void run() {
    final StringBuffer packet = new StringBuffer();

    try {
        cmd.fork();
        forked = true;

        while (!config.isEnd() && !must_end) {
            // on doit pouvoir optimiser en utilisant un StringBuffer pour str
            final String str = cmd.readLineStdout();
            if (str == null)
                break;
            packet.append(str);
            // log.debug("[" + str + "]");
            // replaces invalid XML characters with ' '
            for (int idx = 0; idx < packet.length(); idx++)
                // http://www.w3.org/TR/REC-xml/#charsets
                if (packet.charAt(idx) != 9 && packet.charAt(idx) != 10 && packet.charAt(idx) != 13
                        && packet.charAt(idx) < 32)
                    packet.setCharAt(idx, ' ');

            if (str.contains("</packet>")) {
                try {
                    handlePacket(packet);
                } catch (final DocumentException ex) {
                    log.warn("Exception", ex);
                }
                packet.setLength(0);
            }
        }
    } catch (final IOException ex) {
        log.warn("Exception", ex);
    } catch (final InterruptedException ex) {
        // terminate the thread
    } finally {
        forked = true;
    }
}

From source file:com.fiorano.openesb.application.application.Route.java

/**
 * Converts to new DMI/* w  w  w  . jav a  2 s  .  c o  m*/
 * @param that old Route DMI
 */
public void convert(com.fiorano.openesb.application.aps.Route that) {

    name = that.getRouteGUID();
    if (!Pattern.matches("([a-zA-Z0-9_]+)", name)) {
        StringBuffer nameBuff = new StringBuffer(name);
        for (int i = 0; i < nameBuff.length(); i++) {
            if (!Pattern.matches("([a-zA-Z0-9_]+)", String.valueOf(nameBuff.charAt(i)))) {
                nameBuff.setCharAt(i, '_');
            }
        }
        name = nameBuff.toString();
    }

    sourceServiceInstance = that.getSrcServInst();
    sourcePortInstance = that.getSrcPortName();

    targetServiceInstance = that.getTrgtServInst();
    targetPortInstance = that.getTrgtPortName();

    shortDescription = that.getShortDescription();
    longDescription = that.getLongDescription();
    durable = that.isDurable();

    if (!StringUtils.isEmpty(that.getTransformationXSL())
            || !StringUtils.isEmpty(that.getMessageTransformationXSL())) {
        messageTransformation = new MessageTransformation();
        messageTransformation.convert(that);
    }
    Iterator iter = that.getSelectors().entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        String type = (String) entry.getKey();
        if (com.fiorano.openesb.application.aps.Route.JMS_SELECTOR.equalsIgnoreCase(type))
            selectors.put(SELECTOR_JMS, entry.getValue());
        else if (com.fiorano.openesb.application.aps.Route.SENDER_SELECTOR.equalsIgnoreCase(type))
            selectors.put(SELECTOR_SENDER, entry.getValue());
        else {
            XPathSelector selector = new XPathSelector();
            if (entry.getValue() instanceof XPathDmi)
                selector.convert((XPathDmi) entry.getValue());
            else
                selector.setXPath((String) entry.getValue());
            selectors.put(com.fiorano.openesb.application.aps.Route.APP_CONTEXT_XPATH.equalsIgnoreCase(type)
                    ? SELECTOR_APPLICATION_CONTEXT
                    : SELECTOR_BODY, selector);
        }
    }
}

From source file:com.netspective.commons.text.TextUtils.java

public String fixupTableNameCase(String tableNameOrig) {
    if (null == tableNameOrig)
        return null;

    StringBuffer tableNameBuf = new StringBuffer(tableNameOrig.toLowerCase());
    boolean capNext = false;
    for (int i = 0; i < tableNameBuf.length(); i++) {
        if (tableNameBuf.charAt(i) == '_')
            capNext = true;/*ww  w  . ja v  a  2s  .co  m*/
        else {
            if (i == 0 || capNext) {
                tableNameBuf.setCharAt(i, Character.toUpperCase(tableNameBuf.charAt(i)));
                capNext = false;
            }
        }
    }
    return tableNameBuf.toString();
}

From source file:com.fiorano.openesb.application.application.Route.java

protected void populate(FioranoStaxParser cursor) throws XMLStreamException, FioranoException {
    if (cursor.markCursor(ELEM_ROUTE)) {
        name = cursor.getAttributeValue(null, ATTR_NAME);
        ignoreAbsenceOfTransformation = getBooleanAttribute(cursor, ATTR_IGNORE_ABSENCE_TRANSFORMATION, false);

        if (DmiObject.INVALID_INPUT_CHARS_REGEX.matcher(name).find()) {
            StringBuffer nameBuff = new StringBuffer(name);
            for (int i = 0; i < nameBuff.length(); i++) {
                if (DmiObject.INVALID_INPUT_CHARS_REGEX.matcher(String.valueOf(nameBuff.charAt(i))).find()) {
                    nameBuff.setCharAt(i, '_');
                }//w  ww . j a  v  a2 s.co m
            }
            name = nameBuff.toString();
        }

        while (cursor.nextElement()) {
            String elemName = cursor.getLocalName();
            if (ELEM_SOURCE.equals(elemName)) {
                sourceServiceInstance = cursor.getAttributeValue(null, ATTR_SOURCE_SERVICE_INSTANCE);
                sourcePortInstance = cursor.getAttributeValue(null, ATTR_SOURCE_PORT_INSTANCE);
            } else if (ELEM_TARGET.equals(elemName)) {
                targetServiceInstance = cursor.getAttributeValue(null, ATTR_SOURCE_SERVICE_INSTANCE);
                targetPortInstance = cursor.getAttributeValue(null, ATTR_TARGET_PORT_INSTANCE);
            } else if (ELEM_SHORT_DESCRIPTION.equals(elemName))
                shortDescription = cursor.getText();
            else if (ELEM_LONG_DESCRIPTION.equals(elemName))
                longDescription = cursor.getText();
            else if (ELEM_MESSAGES.equals(elemName)) {
                populateMessagingConfiguration(cursor);
            } else if (ELEM_MESSAGING_CONFIG_NAME.equals(elemName)) {
                messagingConfigName = cursor.getAttributeValue(null, ATTR_NAME);
            } else if (MessageTransformation.ELEM_MESSAGE_TRANSFORMATION.equals(elemName)) {
                messageTransformation = new MessageTransformation();
                messageTransformation.setFieldValues(cursor);
            } else if (ELEM_SELECTORS.equals(elemName)) {
                populateSelectorsConfiguration(cursor);
            } else if (ELEM_SELECTOR_CONFIG_NAME.equals(elemName)) {
                selectorConfigName = cursor.getAttributeValue(null, ATTR_NAME);
            } else if (LogManager.ELEM_LOG_MANAGER.equals(elemName)) {
                logManager = new LogManager();
                logManager.setFieldValues(cursor);
            } else if (ELEM_LOGMODULES.equals(elemName)) {
                cursor.markCursor(cursor.getLocalName());
                while (cursor.nextElement()) {
                    if (LogModule.ELEM_LOGMODULE.equals(cursor.getLocalName())) {
                        LogModule logModule = new LogModule();
                        logModule.setFieldValues(cursor);
                        logModules.add(logModule);
                    }
                }
                cursor.resetCursor();
            }
        }
    }
}

From source file:org.etudes.ambrosia.impl.UiPropertyReference.java

/**
 * Write the value.//from  w w w .j a va 2s. c  o m
 * 
 * @param entity
 *        The entity to write to.
 * @param property
 *        The property to set.
 * @param value
 *        The value to write.
 */
protected void setValue(Object entity, String property, String[] valueSource) {
    // form a "setFoo()" based setter method name
    StringBuffer setter = new StringBuffer("set" + property);
    setter.setCharAt(3, setter.substring(3, 4).toUpperCase().charAt(0));

    // unformat the values - in any are invalid, give up
    String[] value = null;
    try {
        if (valueSource != null) {
            value = new String[valueSource.length];
            for (int i = 0; i < valueSource.length; i++) {
                value[i] = StringUtil.trimToNull(unFormat(valueSource[i]));
            }
        }
    } catch (IllegalArgumentException e) {
        return;
    }

    try {
        // use this form, providing the setter name and no getter, so we can support properties that are write-only
        PropertyDescriptor pd = new PropertyDescriptor(property, entity.getClass(), null, setter.toString());
        Method write = pd.getWriteMethod();
        Object[] params = new Object[1];
        params[0] = null;

        Class[] paramTypes = write.getParameterTypes();
        if ((paramTypes != null) && (paramTypes.length == 1)) {
            // single value boolean
            if (paramTypes[0] == Boolean.class) {
                params[0] = ((value != null) && (value[0] != null))
                        ? Boolean.valueOf(StringUtil.trimToZero(value[0]))
                        : null;
            }

            // multiple value boolean
            else if (paramTypes[0] == Boolean[].class) {
                if (value != null) {
                    Boolean[] values = new Boolean[value.length];
                    for (int i = 0; i < value.length; i++) {
                        values[i] = Boolean.valueOf(StringUtil.trimToZero(value[i]));
                    }
                    params[0] = values;
                }
            }

            // single value long
            else if (paramTypes[0] == Long.class) {
                params[0] = ((value != null) && (value[0] != null))
                        ? Long.valueOf(StringUtil.trimToZero(value[0]))
                        : null;
            }

            // multiple value long
            else if (paramTypes[0] == Long[].class) {
                if (value != null) {
                    Long[] values = new Long[value.length];
                    for (int i = 0; i < value.length; i++) {
                        values[i] = Long.valueOf(StringUtil.trimToZero(value[i]));
                    }
                    params[0] = values;
                }
            }

            // single value int
            else if (paramTypes[0] == Integer.class) {
                params[0] = ((value != null) && (value[0] != null))
                        ? Integer.valueOf(StringUtil.trimToZero(value[0]))
                        : null;
            }

            // multiple value int
            else if (paramTypes[0] == Integer[].class) {
                if (value != null) {
                    Integer[] values = new Integer[value.length];
                    for (int i = 0; i < value.length; i++) {
                        values[i] = Integer.valueOf(StringUtil.trimToZero(value[i]));
                    }
                    params[0] = values;
                }
            }

            // single value Date
            else if (paramTypes[0] == Date.class) {
                // assume a long ms format
                params[0] = ((value != null) && (value[0] != null)) ? new Date(Long.parseLong(value[0])) : null;
            }

            // multiple value Date
            else if (paramTypes[0] == Date[].class) {
                if (value != null) {
                    Date[] values = new Date[value.length];
                    for (int i = 0; i < value.length; i++) {
                        // assume a long ms format
                        values[i] = new Date(Long.parseLong(value[i]));
                    }
                    params[0] = values;
                }
            }

            // single value string
            else if (paramTypes[0] == String.class) {
                params[0] = ((value != null) && (value[0] != null)) ? StringUtil.trimToNull(value[0]) : null;
            }

            // multiple value string
            else if (paramTypes[0] == String[].class) {
                // trim it
                if (value != null) {
                    for (int i = 0; i < value.length; i++) {
                        value[i] = StringUtil.trimToNull(value[i]);
                    }
                }

                params[0] = value;
            }

            // single value enum
            else if (paramTypes[0].isEnum()) {
                if ((value == null) || (value[0] == null)) {
                    params[0] = null;
                } else {
                    Object[] constants = paramTypes[0].getEnumConstants();
                    if (constants != null) {
                        // see if value matches any of these
                        for (Object o : constants) {
                            if (o.toString().equals(value[0])) {
                                params[0] = o;
                                break;
                            }
                        }
                    }
                }
            }

            // single value float
            else if (paramTypes[0] == Float.class) {
                params[0] = ((value != null) && (value[0] != null))
                        ? Float.valueOf(StringUtil.trimToZero(value[0]))
                        : null;
            }

            // multiple value float
            else if (paramTypes[0] == Float[].class) {
                if (value != null) {
                    Float[] values = new Float[value.length];
                    for (int i = 0; i < value.length; i++) {
                        values[i] = Float.valueOf(StringUtil.trimToZero(value[i]));
                    }
                    params[0] = values;
                }
            }

            // multiple value string in list
            else if (paramTypes[0] == List.class) {
                if (value != null) {
                    // trim it into a List
                    List valueList = new ArrayList(value.length);
                    if (value != null) {
                        for (int i = 0; i < value.length; i++) {
                            String v = StringUtil.trimToNull(value[i]);
                            if (v != null) {
                                valueList.add(v);
                            }
                        }
                    }

                    params[0] = valueList;
                }
            }

            // multiple value string in set
            else if (paramTypes[0] == Set.class) {
                if (value != null) {
                    // trim it into a List
                    Set valueSet = new HashSet(value.length);
                    for (int i = 0; i < value.length; i++) {
                        String v = StringUtil.trimToNull(value[i]);
                        if (v != null) {
                            valueSet.add(v);
                        }
                    }

                    params[0] = valueSet;
                }
            }

            // TODO: other types
            else {
                M_log.warn("setValue: unhandled setter parameter type - not set: " + paramTypes[0]);
                return;
            }

            write.invoke(entity, params);
        } else {
            M_log.warn("setValue: method: " + property + " object: " + entity.getClass()
                    + " : no one parameter setter method defined");
        }
    } catch (NumberFormatException ie) {
    } catch (IntrospectionException ie) {
        M_log.warn("setValue: method: " + property + " object: " + entity.getClass(), ie);
    } catch (IllegalAccessException ie) {
        M_log.warn("setValue: method: " + property + " object: " + entity.getClass(), ie);
    } catch (IllegalArgumentException ie) {
        M_log.warn("setValue: method: " + property + " object: " + entity.getClass(), ie);
    } catch (InvocationTargetException ie) {
        M_log.warn("setValue: method: " + property + " object: " + entity.getClass(), ie);
    }
}

From source file:org.versly.rest.wsdoc.AnnotationProcessor.java

String jsonSchemaFromTypeMirror(TypeMirror type) {
    String serializedSchema = null;

    if (type.getKind().isPrimitive() || type.getKind() == TypeKind.VOID) {
        return null;
    }/*from  w  w  w . j ava2 s .  c  om*/

    // we need the dto class to generate schema using jackson json-schema module
    // note: Types.erasure() provides canonical names whereas Class.forName() wants a "regular" name,
    // so forName will fail for nested and inner classes as "regular" names use $ between parent and child.
    Class dtoClass = null;
    StringBuffer erasure = new StringBuffer(_typeUtils.erasure(type).toString());
    for (boolean done = false; !done;) {
        try {
            dtoClass = Class.forName(erasure.toString());
            done = true;
        } catch (ClassNotFoundException e) {
            if (erasure.lastIndexOf(".") != -1) {
                erasure.setCharAt(erasure.lastIndexOf("."), '$');
            } else {
                done = true;
            }
        }
    }

    // if we were able to figure out the dto class, use jackson json-schema module to serialize it
    Exception e = null;
    if (dtoClass != null) {
        try {
            ObjectMapper m = new ObjectMapper();
            m.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
            m.registerModule(new JodaModule());
            SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
            m.acceptJsonFormatVisitor(m.constructType(dtoClass), visitor);
            serializedSchema = m.writeValueAsString(visitor.finalSchema());
        } catch (Exception ex) {
            e = ex;
        }
    }

    // report warning if we were not able to generate schema for non-primitive type
    if (serializedSchema == null) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
                "cannot generate json-schema for class " + type.toString() + " (erasure " + erasure + "), "
                        + ((e != null) ? ("exception: " + e.getMessage()) : "class not found"));
    }

    return serializedSchema;
}

From source file:cx.fbn.nevernote.sql.REnSearch.java

private void resolveSearch(String search) {
    List<String> words = new ArrayList<String>();
    StringBuffer b = new StringBuffer(search);

    int len = search.length();
    char nextChar = ' ';
    boolean quote = false;
    for (int i = 0, j = 0; i < len; i++, j++) {
        if (search.charAt(i) == nextChar && !quote) {
            b.setCharAt(j, '\0');
            nextChar = ' ';
        } else {/*w w w .j  a  v a  2  s  . co m*/
            if (search.charAt(i) == '\"') {
                if (!quote) {
                    quote = true;
                } else {
                    quote = false;
                    j++;
                    b.insert(j, "\0");
                }
            }
        }
        if (((i + 2) < len) && search.charAt(i) == '\\') {
            i = i + 2;
        }
    }

    search = b.toString();
    int pos = 0;
    for (int i = 0; i < search.length(); i++) {
        if (search.charAt(i) == '\0') {
            search = search.substring(1);
            i = 0;
        } else {
            pos = search.indexOf('\0');
            if (pos > 0) {
                words.add(search.substring(0, pos).toLowerCase());
                search = search.substring(pos);
                i = 0;
            }
        }
    }
    if (search.charAt(0) == '\0')
        words.add(search.substring(1).toLowerCase());
    else
        words.add(search.toLowerCase());
    parseTerms(words);
}

From source file:com.qut.middleware.spep.filter.SPEPFilter.java

/**
 * Transcodes %XX symbols per RFC 2369 to normalized character format - adapted from apache commons
 * //from   ww  w . j  av a 2s .c  o  m
 * @param buffer
 *            The stringBuffer object containing the request data
 * @param offset
 *            How far into the string buffer we should start processing from
 * @param length
 *            Number of chars in the buffer
 * @throws ServletException
 */
private void decode(final StringBuffer buffer, final int offset, final int length) throws ServletException {
    int index = offset;
    int count = length;
    int dig1, dig2;
    while (count > 0) {
        final char ch = buffer.charAt(index);
        if (ch != '%') {
            count--;
            index++;
            continue;
        }
        if (count < 3) {
            throw new ServletException(
                    Messages.getString("SPEPFilter.10") + buffer.substring(index, index + count)); //$NON-NLS-1$
        }

        dig1 = Character.digit(buffer.charAt(index + 1), 16);
        dig2 = Character.digit(buffer.charAt(index + 2), 16);
        if (dig1 == -1 || dig2 == -1) {
            throw new ServletException(
                    Messages.getString("SPEPFilter.11") + buffer.substring(index, index + count)); //$NON-NLS-1$
        }
        char value = (char) (dig1 << 4 | dig2);

        buffer.setCharAt(index, value);
        buffer.delete(index + 1, index + 3);
        count -= 3;
        index++;
    }
}

From source file:org.zkoss.poi.ss.format.CellNumberFormatter.java

private void writeFractional(StringBuffer result, StringBuffer output) {
    int digit;/*  ww  w .  j  av  a 2s . c o m*/
    int strip;
    ListIterator<Special> it;
    if (fractionalSpecials.size() > 0) {
        //20100914, henrichen@zkoss.org: respect given Locale
        final char dot = Formatters.getDecimalSeparator(locale);
        output.setCharAt(decimalPoint.pos, dot);

        digit = result.indexOf("" + dot) + 1;
        if (exponent != null)
            strip = result.indexOf("e") - 1;
        else
            strip = result.length() - 1;
        while (strip > digit && result.charAt(strip) == '0')
            strip--;
        it = fractionalSpecials.listIterator();
        while (it.hasNext()) {
            Special s = it.next();
            char resultCh = result.charAt(digit);
            if (resultCh != '0' || s.ch == '0' || digit < strip)
                output.setCharAt(s.pos, resultCh);
            else if (s.ch == '?') {
                // This is when we're in trailing zeros, and the format is '?'.  We still strip out remaining '#'s later
                output.setCharAt(s.pos, ' ');
            }
            digit++;
        }
    }
}

From source file:net.ddns.mlsoftlaberge.contactslist.ui.ContactAdminFragment.java

private String onlyNumbers(String from) {
    StringBuffer tonum = new StringBuffer();
    tonum.setLength(14);//ww  w  .ja  v a2s .  c om
    int i;
    int j = 0;
    for (i = 0; i < from.length(); ++i) {
        char c = from.charAt(i);
        if (c >= '0' && c <= '9') {
            tonum.setCharAt(j, c);
            j++;
        }
    }
    tonum.setLength(j);
    return tonum.toString();
}