Example usage for java.lang StringBuffer charAt

List of usage examples for java.lang StringBuffer charAt

Introduction

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

Prototype

@Override
public synchronized char charAt(int index) 

Source Link

Usage

From source file:Unsigned.java

/**
 * Parse a binary number, skipping leading whitespace. Does not throw an
 * exception; if no object can be parsed, index is unchanged!
 * //from   w w w. ja  v  a 2  s  .  c o  m
 * @param source
 *            the string to parse
 * @param status
 *            the string index to start at
 * @return The binary number as a Long object.
 * 
 * @since 1.0
 */
public Object parseObject(String source, ParsePosition status) {
    int start = status.getIndex();
    boolean success = false;
    boolean skipWhitespace = true;
    StringBuffer buffer = new StringBuffer();

    StringCharacterIterator iter = new StringCharacterIterator(source, start);

    for (char c = iter.current(); c != CharacterIterator.DONE; c = iter.next()) {
        if (skipWhitespace && Character.isWhitespace(c)) {
            // skip whitespace
            continue;
        }
        skipWhitespace = false;

        if ((c == '1') || (c == '0')) {
            success = true;
            buffer.append(c);
        } else {
            break;
        }
    }

    if (!success) {
        return (null);
    }

    // convert binary to long
    if (buffer.length() > 64) {
        // larger than a long, error
        return (null);
    }

    long result = 0;
    buffer.reverse();
    int length = buffer.length();
    for (int i = 0; i < length; i++) {
        result += (buffer.charAt(i) == '1') ? 1 << i : 0;
    }
    status.setIndex(iter.getIndex());
    return (new Long(result));
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String[] splitCommaSeparatedString(String toSeparate) {

    if (toSeparate == null || toSeparate == "")
        return null;

    List list = new ArrayList();
    String[] strArr = new String[1]; //just do determine the type of the array in list.toArray(Object[] o)

    StringBuffer sb = new StringBuffer(toSeparate);
    for (int i = 0; i < sb.length(); i++) {
        if (sb.charAt(i) == ' ')
            sb.deleteCharAt(i);//www.j  a v a 2 s  . co m
    }
    int start = 0;
    for (int i = 0; i < sb.length(); i++) {
        if (sb.charAt(i) == ',' || i == sb.length() - 1) {
            list.add(sb.substring(start, i == sb.length() - 1 ? i + 1 : i));
            start = i + 1;
        }
    }

    Object[] objArr = null;
    objArr = list.toArray(strArr);
    return (String[]) objArr;
}

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

private void writeInteger(StringBuffer result, StringBuffer output, List<Special> numSpecials,
        Set<StringMod> mods, boolean showCommas) {

    int pos = result.indexOf(".") - 1;
    if (pos < 0) {
        if (exponent != null && numSpecials == integerSpecials)
            pos = result.indexOf("E") - 1;
        else//from  w w w . j av a  2  s . co m
            pos = result.length() - 1;
    }

    int strip;
    for (strip = 0; strip < pos; strip++) {
        char resultCh = result.charAt(strip);
        if (resultCh != '0' && resultCh != ',')
            break;
    }

    ListIterator<Special> it = numSpecials.listIterator(numSpecials.size());
    boolean followWithComma = false;
    Special lastOutputIntegerDigit = null;
    int digit = 0;
    while (it.hasPrevious()) {
        char resultCh;
        if (pos >= 0)
            resultCh = result.charAt(pos);
        else {
            // If result is shorter than field, pretend there are leading zeros
            resultCh = '0';
        }
        Special s = it.previous();
        followWithComma = showCommas && digit > 0 && digit % 3 == 0;
        boolean zeroStrip = false;
        if (resultCh != '0' || s.ch == '0' || s.ch == '?' || pos >= strip) {
            zeroStrip = s.ch == '?' && pos < strip;
            output.setCharAt(s.pos, (zeroStrip ? ' ' : resultCh));
            lastOutputIntegerDigit = s;
        }
        if (followWithComma) {
            mods.add(insertMod(s, zeroStrip ? " " : ",", StringMod.AFTER));
            followWithComma = false;
        }
        digit++;
        --pos;
    }
    StringBuffer extraLeadingDigits = new StringBuffer();
    if (pos >= 0) {
        // We ran out of places to put digits before we ran out of digits; put this aside so we can add it later
        ++pos; // pos was decremented at the end of the loop above when the iterator was at its end
        extraLeadingDigits = new StringBuffer(result.substring(0, pos));
        if (showCommas) {
            while (pos > 0) {
                if (digit > 0 && digit % 3 == 0)
                    extraLeadingDigits.insert(pos, ',');
                digit++;
                --pos;
            }
        }
        mods.add(insertMod(lastOutputIntegerDigit, extraLeadingDigits, StringMod.BEFORE));
    }
}

From source file:usbong.android.utils.UsbongUtils.java

public static String performSimpleFileEncrypt(int key, String fileData) {
    StringBuffer myFileData = new StringBuffer(fileData.toString());
    StringBuffer encrypted = new StringBuffer();
    int myFileDataLength = fileData.length();
    int myAlphanumericLength = alphanumeric.length;
    boolean isUpperCase = false;

    for (int i = 0; i < myFileDataLength; i++) {
        if (Character.isUpperCase(myFileData.charAt(i))) {
            isUpperCase = true;/*from  w  ww .  ja v  a  2 s.c o m*/
        } else {
            isUpperCase = false;
        }

        if (Character.isLetter(myFileData.charAt(i)) || Character.isDigit(myFileData.charAt(i))) {
            for (int k = 0; k < myAlphanumericLength; k++) {
                if (Character.toLowerCase(myFileData.charAt(i)) == alphanumeric[k]) {
                    int counter = (k + key) % myAlphanumericLength; //do a plus
                    if (isUpperCase) {
                        encrypted.append(Character.toUpperCase(alphanumeric[counter]));
                    } else {
                        encrypted.append(alphanumeric[counter]);
                    }
                }
            }
        } else {
            encrypted.append(fileData.charAt(i));
        }
    }
    return encrypted.toString();
}

From source file:usbong.android.utils.UsbongUtils.java

public static String performSimpleFileDecrypt(int key, String fileData) {
    StringBuffer myFileData = new StringBuffer(fileData.toString());
    StringBuffer decoded = new StringBuffer();
    int myFileDataLength = fileData.length();
    int myAlphanumericLength = alphanumeric.length;
    boolean isUpperCase = false;

    for (int i = 0; i < myFileDataLength; i++) {
        if (Character.isUpperCase(myFileData.charAt(i))) {
            isUpperCase = true;//  w w  w  .  ja  v a  2s .  co  m
        } else {
            isUpperCase = false;
        }

        if (Character.isLetter(myFileData.charAt(i)) || Character.isDigit(myFileData.charAt(i))) {
            for (int k = 0; k < myAlphanumericLength; k++) {
                if (Character.toLowerCase(myFileData.charAt(i)) == alphanumeric[k]) {
                    //Reference: http://stackoverflow.com/questions/11464890/first-char-to-upper-case;
                    //last accessed: 21 Dec. 2013; answered by Jon
                    //                   int counter = ((k-key) % 26 + 26) % 26;
                    int counter = ((k - key) % myAlphanumericLength + myAlphanumericLength)
                            % myAlphanumericLength;
                    if (isUpperCase) {
                        decoded.append(Character.toUpperCase(alphanumeric[counter]));
                    } else {
                        decoded.append(alphanumeric[counter]);
                    }
                }
            }
        } else {
            decoded.append(fileData.charAt(i));
        }
    }
    return decoded.toString();
}

From source file:util.FoursquareAPI_backup.java

/**
 * Command-line interface for the sample Yelp API runner.
 *//*  w  ww.j av  a  2  s.co m*/
/*private static class YelpAPICLI {
 //@Parameter(names = {"-q", "--term"}, description = "Search Query Term")
 //public String term = DEFAULT_TERM;
 //http://api.yelp.com/v2/search?term=german+food&location=Hayes&cll=37.77493,-122.419415
 //cll=latitude,longitude
 //@Parameter(names = {"-l", "--location"}, description = "Location to be Queried")
 @Parameter(names = {"-l", "--location"}, description = "Location to be Queried")
 public String location = DEFAULT_LOCATION;
 }
 */
//http://maps.googleapis.com/maps/api/geocode/json?latlng=-9.56189,113.15437&sensor=true
//http://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=-26.929948,142.401002
public JSONObject searchGoogleMap(String term, double latitude, double longitude) {
    try {
        //OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.foursquare.com/v2/venues/search");
        int len = Google_htp.length();
        Google_htp.append(latitude);
        Google_htp.append(',');
        Google_htp.append(longitude);
        int len1 = Google_htp.length();
        //String contents = java.net.URL();
        URL url = new URL(Google_htp.toString());
        Google_htp.delete(len, len1);
        URLConnection con = url.openConnection();

        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

        String input = null;
        boolean Begin_City = false;
        int number = 0;
        JSONObject list1 = new JSONObject();
        StringBuffer SaveString = new StringBuffer();
        while ((input = br.readLine()) != null) {
            String[] tempS = input.split(":");
            if (Begin_City) {
                if (tempS[0].contains("short_name")) {
                    SaveString.append(tempS[1].trim());
                }
                if (tempS[0].contains("types")) {
                    String tempType = tempS[1].trim();
                    if (tempType.length() < 3) {
                        if (tempS.length < 3) {
                            SaveString.setLength(0);
                            continue;
                        }
                        tempType = tempS[2].trim();
                    }
                    int loc = 1;
                    do {
                        loc = -1;
                        for (int i = 0; i < SaveString.length(); i++)
                            switch (SaveString.charAt(i)) {
                            case '\"':
                            case ',':
                            case ':':
                                loc = i;
                                break;
                            }

                        if (loc >= 0)
                            SaveString.delete(loc, loc + 1);
                    } while (loc >= 0);
                    if (tempType.contains("postal_code")) {
                        list1.put("post_code", SaveString.toString());
                        number++;
                    } else if (tempType.contains("administrative_area_level_1")) {
                        list1.put("state_code", SaveString.toString());
                        number++;
                    } else if (tempType.contains("country")) {
                        list1.put("country_code", SaveString.toString());
                        number++;
                    } else if (tempType.contains("locality")) {
                        list1.put("city_name", SaveString.toString());
                        number++;
                    }
                    //              else
                    //              System.out.println(tempType+":"+SaveString.toString());
                    SaveString.setLength(0);
                }
            }
            if (tempS[0].contains("address_components")) {
                if (Begin_City)
                    break;
                Begin_City = true;
            }
        }
        br.close();

        return list1;
    } catch (IOException ex) {
        Logger.getLogger(FoursquareAPI_backup.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.apache.axis2.builder.XFormURLEncodedBuilder.java

/**
 * Here is what I will try to do here. I will first try to identify the location of the first
 * template element in the request URI. I am trying to deduce the location of that location
 * using the httpLocation element of the binding (it is passed in to this
 * method)./*from w  w w.  java  2  s  .c  o  m*/
 * If there is a contant part in the httpLocation, then I will identify it. For this, I get
 * the index of {, from httpLocation param, and whatever to the left of it is the contant part.
 * Then I search for this constant part inside the url. This will give us the access to the first
 * template parameter.
 * To find the end of this parameter, we need to get the index of the next constant, from
 * httpLocation attribute. Likewise we keep on discovering parameters.
 * <p/>
 * Assumptions :
 * 1. User will always append the value of httpLocation to the address given in the
 * endpoint.
 * 2. I was talking about the constants in the httpLocation. Those constants will not occur,
 * to a reasonable extend, before the constant we are looking for.
 *
 * @param templatedPath
 * @param parameterMap
 */
protected String extractParametersUsingHttpLocation(String templatedPath, MultipleEntryHashMap parameterMap,
        String requestURL, String queryParameterSeparator) throws AxisFault, UnsupportedEncodingException {

    if (templatedPath != null && !"".equals(templatedPath) && templatedPath.indexOf("{") > -1) {
        StringBuffer pathTemplate = new StringBuffer(templatedPath);

        // this will hold the index, from which we need to process the request URI
        int startIndex = 0;
        int templateStartIndex = 0;
        int templateEndIndex = 0;
        int indexOfNextConstant = 0;

        StringBuffer requestURIBuffer = new StringBuffer(requestURL);

        while (startIndex < requestURIBuffer.length()) {
            // this will always hold the starting index of a template parameter
            templateStartIndex = pathTemplate.indexOf("{", templateStartIndex);

            if (templateStartIndex > 0) {
                // get the preceding constant part from the template
                String constantPart = pathTemplate.substring(templateEndIndex + 1, templateStartIndex);
                constantPart = constantPart.replaceAll("\\{\\{", "{");
                constantPart = constantPart.replaceAll("}}", "}");

                // get the index of the end of this template param
                templateEndIndex = pathTemplate.indexOf("}", templateStartIndex);
                if ((pathTemplate.length() - 1) > templateEndIndex
                        && pathTemplate.charAt(templateEndIndex + 1) == '}') {
                    templateEndIndex = pathTemplate.indexOf("}", templateEndIndex + 2);
                }

                String parameterName = pathTemplate.substring(templateStartIndex + 1, templateEndIndex);
                // next try to find the next constant
                templateStartIndex = pathTemplate.indexOf("{", templateEndIndex);
                if (pathTemplate.charAt(templateStartIndex + 1) == '{') {
                    templateStartIndex = pathTemplate.indexOf("{", templateStartIndex + 2);
                }

                int endIndexOfConstant = requestURIBuffer.indexOf(constantPart, indexOfNextConstant)
                        + constantPart.length();

                if (templateStartIndex == -1) {
                    if (templateEndIndex == pathTemplate.length() - 1) {

                        // We may have occations where we have templates of the form foo/{name}.
                        // In this case the next connstant will be ? and not the
                        // queryParameterSeparator
                        indexOfNextConstant = requestURIBuffer.indexOf("?", endIndexOfConstant);
                        if (indexOfNextConstant == -1) {
                            indexOfNextConstant = requestURIBuffer.indexOf(queryParameterSeparator,
                                    endIndexOfConstant);
                        }
                        if (indexOfNextConstant > 0) {
                            addParameterToMap(parameterMap, parameterName,
                                    requestURIBuffer.substring(endIndexOfConstant, indexOfNextConstant));
                            return requestURL.substring(indexOfNextConstant);
                        } else {

                            addParameterToMap(parameterMap, parameterName,
                                    requestURIBuffer.substring(endIndexOfConstant));
                            return "";
                        }

                    } else {

                        constantPart = pathTemplate.substring(templateEndIndex + 1, pathTemplate.length());
                        constantPart = constantPart.replaceAll("\\{\\{", "{");
                        constantPart = constantPart.replaceAll("}}", "}");
                        indexOfNextConstant = requestURIBuffer.indexOf(constantPart, endIndexOfConstant);

                        addParameterToMap(parameterMap, parameterName,
                                requestURIBuffer.substring(endIndexOfConstant, indexOfNextConstant));

                        if (requestURIBuffer.length() > indexOfNextConstant + 1) {
                            return requestURIBuffer.substring(indexOfNextConstant + 1);
                        }
                        return "";
                    }
                } else {

                    // this is the next constant from the template
                    constantPart = pathTemplate.substring(templateEndIndex + 1, templateStartIndex);
                    constantPart = constantPart.replaceAll("\\{\\{", "{");
                    constantPart = constantPart.replaceAll("}}", "}");

                    indexOfNextConstant = requestURIBuffer.indexOf(constantPart, endIndexOfConstant);
                    addParameterToMap(parameterMap, parameterName,
                            requestURIBuffer.substring(endIndexOfConstant, indexOfNextConstant));
                    startIndex = indexOfNextConstant;

                }

            }

        }
    }

    return requestURL;
}

From source file:Main.java

/**
 * Convert the given Node to an XML String.
 * <p>// www.  j  a v a 2  s .com
 * This method is a simplified version of...
 * <p>
 * <code>
 *    ByteArrayOutputStream out = new ByteArrayOutputStream();<br/>
 *    javax.xml.Transformer transformer = TransformerFactory.newInstance().newTransformer();<br/>
 *    transformer.transform( new DOMSource( node ), new StreamResult( out ));<br/>
 *    return out.toString();
 * </code>
 * <p>
 * ...but not all platforms (eg. Android) support <code>javax.xml.transform.Transformer</code>.
 *
 * @param indent
 *            how much to indent the output. -1 for no indent.
 */

private static String nodeToString(Node node, int indent) {

    // Text nodes

    if (node == null) {
        return null;
    }

    if (!(node instanceof Element)) {

        String value = node.getNodeValue();

        if (value == null) {
            return null;
        }

        return escapeForXml(value.trim());
    }

    // (use StringBuffer for J2SE 1.4 compatibility)

    StringBuffer buffer = new StringBuffer();

    // Open tag

    indent(buffer, indent);
    String nodeName = escapeForXml(node.getNodeName());
    buffer.append("<");
    buffer.append(nodeName);

    // Changing namespace

    String namespace = node.getNamespaceURI();
    Node parentNode = node.getParentNode();

    if (namespace != null && (parentNode == null || !namespace.equals(parentNode.getNamespaceURI()))) {
        buffer.append(" xmlns=\"");
        buffer.append(namespace);
        buffer.append("\"");
    }

    // Attributes

    NamedNodeMap attributes = node.getAttributes();

    // Always put name first for easy unit tests

    Node name = attributes.getNamedItem("name");

    if (name != null) {
        buffer.append(" name=\"");
        buffer.append(escapeForXml(name.getNodeValue()));
        buffer.append("\"");
    }

    for (int loop = 0; loop < attributes.getLength(); loop++) {
        Node attribute = attributes.item(loop);
        String attributeName = attribute.getNodeName();

        // (I'm a bit surprised xmlns is an attribute - is that a bug?)

        if ("xmlns".equals(attributeName)) {
            continue;
        }

        // (always put name first for easy unit tests)

        if ("name".equals(attributeName)) {
            continue;
        }

        buffer.append(" ");
        buffer.append(escapeForXml(attributeName));
        buffer.append("=\"");
        buffer.append(escapeForXml(attribute.getNodeValue()));
        buffer.append("\"");
    }

    // Children (if any)

    NodeList children = node.getChildNodes();
    int length = children.getLength();

    if (length == 0) {
        buffer.append("/>");
    } else {
        buffer.append(">");

        int nextIndent = indent;

        if (indent != -1) {
            nextIndent++;
        }

        for (int loop = 0; loop < length; loop++) {
            Node childNode = children.item(loop);

            if (indent != -1 && childNode instanceof Element) {
                buffer.append("\n");
            }

            buffer.append(nodeToString(childNode, nextIndent));
        }

        if (indent != -1 && buffer.charAt(buffer.length() - 1) == '>') {
            buffer.append("\n");
            indent(buffer, indent);
        }

        // Close tag

        buffer.append("</");
        buffer.append(nodeName);
        buffer.append(">");
    }

    return buffer.toString();
}

From source file:util.FoursquareAPI.java

/**
 * Command-line interface for the sample Yelp API runner.
 *//* ww w  . ja  v a2s .co  m*/
/*private static class YelpAPICLI {
 //@Parameter(names = {"-q", "--term"}, description = "Search Query Term")
 //public String term = DEFAULT_TERM;
 //http://api.yelp.com/v2/search?term=german+food&location=Hayes&cll=37.77493,-122.419415
 //cll=latitude,longitude
 //@Parameter(names = {"-l", "--location"}, description = "Location to be Queried")
 @Parameter(names = {"-l", "--location"}, description = "Location to be Queried")
 public String location = DEFAULT_LOCATION;
 }
 */
//http://maps.googleapis.com/maps/api/geocode/json?latlng=-9.56189,113.15437&sensor=true
//http://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=-26.929948,142.401002
public JSONObject searchGoogleMap(String term, double latitude, double longitude) {
    try {
        //OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.foursquare.com/v2/venues/search");
        int len = Google_htp.length();
        Google_htp.append("latlng=");
        Google_htp.append(latitude);
        Google_htp.append(',');
        Google_htp.append(longitude);
        int len1 = Google_htp.length();
        //String contents = java.net.URL();
        URL url = new URL(Google_htp.toString());
        Google_htp.delete(len, len1);
        URLConnection con = url.openConnection();

        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

        String input = null;
        boolean Begin_City = false;
        int number = 0;
        JSONObject list1 = new JSONObject();
        StringBuffer SaveString = new StringBuffer();
        while ((input = br.readLine()) != null) {
            String[] tempS = input.split(":");
            if (Begin_City) {
                if (tempS[0].contains("short_name")) {
                    SaveString.append(tempS[1].trim());
                }
                if (tempS[0].contains("types")) {
                    String tempType = tempS[1].trim();
                    if (tempType.length() < 3) {
                        if (tempS.length < 3) {
                            SaveString.setLength(0);
                            continue;
                        }
                        tempType = tempS[2].trim();
                    }
                    int loc = 1;
                    do {
                        loc = -1;
                        for (int i = 0; i < SaveString.length(); i++)
                            switch (SaveString.charAt(i)) {
                            case '\"':
                            case ',':
                            case ':':
                                loc = i;
                                break;
                            }

                        if (loc >= 0)
                            SaveString.delete(loc, loc + 1);
                    } while (loc >= 0);
                    if (tempType.contains("postal_code")) {
                        list1.put("post_code", SaveString.toString());
                        number++;
                    } else if (tempType.contains("administrative_area_level_1")) {
                        list1.put("state_code", SaveString.toString());
                        number++;
                    } else if (tempType.contains("country")) {
                        list1.put("country_code", SaveString.toString());
                        number++;
                    } else if (tempType.contains("locality")) {
                        list1.put("city_name", SaveString.toString());
                        number++;
                    }
                    //              else
                    //              System.out.println(tempType+":"+SaveString.toString());
                    SaveString.setLength(0);
                }
            }
            if (tempS[0].contains("address_components")) {
                if (Begin_City)
                    break;
                Begin_City = true;
            }
        }
        br.close();

        return list1;
    } catch (IOException ex) {
        Logger.getLogger(FoursquareAPI.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatWritePanel.java

/**
 * When CTRL+Z is pressed invokes the <code>ChatWritePanel.undo()</code>
 * method, when CTRL+R is pressed invokes the
 * <code>ChatWritePanel.redo()</code> method.
 *
 * @param e the <tt>KeyEvent</tt> that notified us
 *///from   w  ww  .jav  a 2 s.c om
public void keyPressed(KeyEvent e) {
    if ((e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK && (e.getKeyCode() == KeyEvent.VK_Z)
    // And not ALT(right ALT gives CTRL + ALT).
            && (e.getModifiers() & KeyEvent.ALT_MASK) != KeyEvent.ALT_MASK) {
        if (undo.canUndo())
            undo();
    } else if ((e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK
            && (e.getKeyCode() == KeyEvent.VK_R)
            // And not ALT(right ALT gives CTRL + ALT).
            && (e.getModifiers() & KeyEvent.ALT_MASK) != KeyEvent.ALT_MASK) {
        if (undo.canRedo())
            redo();
    } else if (e.getKeyCode() == KeyEvent.VK_TAB) {
        if (!(chatPanel.getChatSession() instanceof ConferenceChatSession))
            return;

        e.consume();
        int index = ((JEditorPane) e.getSource()).getCaretPosition();

        StringBuffer message = new StringBuffer(chatPanel.getMessage());

        int position = index - 1;

        while (position > 0 && (message.charAt(position) != ' ')) {
            position--;
        }

        if (position != 0)
            position++;

        String sequence = message.substring(position, index);

        if (sequence.length() <= 0) {
            // Do not look for matching contacts if the matching pattern is
            // 0 chars long, since all contacts will match.
            return;
        }

        Iterator<ChatContact<?>> iter = chatPanel.getChatSession().getParticipants();
        ArrayList<String> contacts = new ArrayList<String>();
        while (iter.hasNext()) {
            ChatContact<?> c = iter.next();
            if (c.getName().length() >= (index - position)
                    && c.getName().substring(0, index - position).equals(sequence)) {
                message.replace(position, index, c.getName().substring(0, index - position));
                contacts.add(c.getName());
            }
        }

        if (contacts.size() > 1) {
            char key = contacts.get(0).charAt(index - position - 1);
            int pos = index - position - 1;
            boolean flag = true;

            while (flag) {
                try {
                    for (String name : contacts) {
                        if (key != name.charAt(pos)) {
                            flag = false;
                        }
                    }

                    if (flag) {
                        pos++;
                        key = contacts.get(0).charAt(pos);
                    }
                } catch (IndexOutOfBoundsException exp) {
                    flag = false;
                }
            }

            message.replace(position, index, contacts.get(0).substring(0, pos));

            Iterator<String> contactIter = contacts.iterator();
            String contactList = "<DIV align='left'><h5>";
            while (contactIter.hasNext()) {
                contactList += contactIter.next() + " ";
            }
            contactList += "</h5></DIV>";

            chatPanel.getChatConversationPanel().appendMessageToEnd(contactList,
                    ChatHtmlUtils.HTML_CONTENT_TYPE);
        } else if (contacts.size() == 1) {
            String limiter = (position == 0) ? ": " : "";
            message.replace(position, index, contacts.get(0) + limiter);
        }

        try {
            ((JEditorPane) e.getSource()).getDocument().remove(0,
                    ((JEditorPane) e.getSource()).getDocument().getLength());
            ((JEditorPane) e.getSource()).getDocument().insertString(0, message.toString(), null);
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    } else if (e.getKeyCode() == KeyEvent.VK_UP) {
        // Only enters editing mode if the write panel is empty in
        // order not to lose the current message contents, if any.
        if (this.chatPanel.getLastSentMessageUID() != null && this.chatPanel.isWriteAreaEmpty()) {
            this.chatPanel.startLastMessageCorrection();
            e.consume();
        }
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
        if (chatPanel.isMessageCorrectionActive()) {
            Document doc = editorPane.getDocument();
            if (editorPane.getCaretPosition() == doc.getLength()) {
                chatPanel.stopMessageCorrection();
            }
        }
    }
}