Example usage for java.lang StringBuilder charAt

List of usage examples for java.lang StringBuilder charAt

Introduction

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

Prototype

char charAt(int index);

Source Link

Document

Returns the char value at the specified index.

Usage

From source file:org.apache.brooklyn.util.net.Urls.java

/** returns the items with exactly one "/" between items (whether or not the individual items start or end with /),
 * except where character before the / is a : (url syntax) in which case it will permit multiple (will not remove any).
 * Throws a NullPointerException if any elements of 'items' is null.
 *  *///ww  w.j  a  va2s. c o  m
public static String mergePaths(String... items) {
    List<String> parts = Arrays.asList(items);

    if (parts.contains(null)) {
        throw new NullPointerException(String
                .format("Unable to reliably merge path from parts: %s; input contains null values", parts));
    }

    StringBuilder result = new StringBuilder();
    for (String part : parts) {
        boolean trimThisMerge = result.length() > 0 && !result.toString().endsWith("://")
                && !result.toString().endsWith(":///") && !result.toString().endsWith(":");
        if (trimThisMerge) {
            while (result.length() > 0 && result.charAt(result.length() - 1) == '/')
                result.deleteCharAt(result.length() - 1);
            result.append('/');
        }
        int i = result.length();
        result.append(part);
        if (trimThisMerge) {
            while (result.length() > i && result.charAt(i) == '/')
                result.deleteCharAt(i);
        }
    }
    return result.toString();
}

From source file:com.comcast.viper.flume2storm.zookeeper.ZkUtilies.java

/**
 * Builds a valid (guaranteed) ZNode path made of the components passed in
 * parameter. This method handles the path separator between component, so it
 * can be called with or without them./*  ww w  . j  av  a  2s .c  om*/
 * 
 * @param components
 *          A bunch of ZNode path elements. Some may be null.
 * @return The concatenated path of all the elements
 * @throws IllegalArgumentException
 *           if the path is invalid (empty for example)
 */
public static String buildZkPath(final String... components) {
    Preconditions.checkArgument(components != null, "No path element specified");
    boolean isFirst = true;
    final StringBuilder result = new StringBuilder();
    for (int i = 0; i < components.length; i++) {
        if (StringUtils.isEmpty(components[i])) {
            continue;
        }
        assert components[i] != null;
        // Checking path separator
        if (isFirst) {
            // First element must start with /
            if (!components[i].startsWith(SEPARATOR)) {
                result.append(SEPARATOR);
            }
            result.append(components[i]);
        } else {
            if (!SEPARATOR_CHAR.equals(result.charAt(result.length() - 1))
                    && !components[i].startsWith(SEPARATOR)) {
                result.append(SEPARATOR);
                result.append(components[i]);
            } else if (SEPARATOR_CHAR.equals(result.charAt(result.length() - 1))
                    && components[i].startsWith(SEPARATOR)) {
                result.append(components[i].substring(1));
            } else {
                result.append(components[i]);
            }
        }
        isFirst = false;
    }
    final String path = result.toString();
    PathUtils.validatePath(path);
    return path;
}

From source file:org.geoserver.ows.util.ResponseUtils.java

/**
 * Given a set of path components a full path is built
 * @param pathComponents The set of path components
 *
 * @return The full url with the path appended.
 * TODO: remove this and replace with Requetss.appendContextPath
 *//*w w  w  .  java 2 s . c o m*/
public static String appendPath(String... pathComponents) {
    StringBuilder result = new StringBuilder(pathComponents[0]);
    for (int i = 1; i < pathComponents.length; i++) {
        String component = pathComponents[i];
        boolean endsWithSlash = result.charAt(result.length() - 1) == '/';
        boolean startsWithSlash = component.startsWith("/");
        if (endsWithSlash && startsWithSlash) {
            result.setLength(result.length() - 1);
        } else if (!endsWithSlash && !startsWithSlash) {
            result.append("/");
        }
        result.append(component);
    }

    return result.toString();
}

From source file:com.google.publicalerts.cap.CapUtil.java

static String toCase(String s, boolean camel) {
    String[] parts = s.split("_");
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < parts.length; i++) {
        String part = parts[i];//from   w w w.ja  v a  2 s  . c o m
        if (part.length() > 0) {
            sb.append(part.substring(0, 1).toUpperCase()).append(part.substring(1).toLowerCase());
        }
    }
    if (!camel && sb.length() > 0) {
        sb.replace(0, 1, String.valueOf(Character.toLowerCase(sb.charAt(0))));
    }
    return sb.toString();
}

From source file:com.igormaznitsa.mindmap.model.ModelUtils.java

@Nullable
public static URI toURI(@Nullable final Path path) {
    if (path == null) {
        return null;
    }//from   ww  w  .  ja  v a 2 s .c o  m
    try {
        final StringBuilder buffer = new StringBuilder();

        final Path root = path.getRoot();
        if (root != null) {
            buffer.append(root.toString().replace('\\', '/'));
        }

        for (final Path p : path) {
            if (buffer.length() > 0 && buffer.charAt(buffer.length() - 1) != '/') {
                buffer.append('/');
            }
            buffer.append(encodeForURI(p.toFile().getName()));
        }

        if (path.isAbsolute()) {
            buffer.insert(0, "file://" + (root == null ? "/" : "")); //NOI18N
        }

        return new URI(buffer.toString());
    } catch (Exception ex) {
        throw new IllegalArgumentException("Can't convert path to URI: " + path, ex); //NOI18N
    }
}

From source file:fr.ribesg.bukkit.api.chat.Chat.java

private static void appendClick(final StringBuilder builder, final Click clickAction) {
    if (clickAction != null) {
        if (builder.charAt(builder.length() - 1) != '{') {
            builder.append(',');
        }/*from   w  w  w. j a v  a  2  s .c o  m*/
        builder.append("\"clickEvent\":{\"value\":\"").append(Chat.escapeString(clickAction.getText()))
                .append("\",\"action\":\"");
        switch (clickAction.getType()) {
        case OPEN_URL:
            builder.append("open_url");
            break;
        case SEND_TEXT:
            builder.append("run_command");
            break;
        case SET_TEXT:
            builder.append("suggest_command");
            break;
        }
        builder.append("\"}");
    }
}

From source file:fr.ribesg.bukkit.api.chat.Chat.java

/**
 * Converts a String representing standard Minecraft formatted text to
 * a Mojangson Chat 'extra' String and append it to the provided
 * StringBuilder.//from w  w  w  .j a  va2  s .  c o  m
 *
 * @param builder    a StringBuilder
 * @param text       a text
 * @param extraLevel the amount of extra levels added to the Mojangson
 *
 * @return the updated amount of extra levels
 */
private static int appendText(final StringBuilder builder, final String text, int extraLevel) {
    if (builder.charAt(builder.length() - 1) != '{') {
        builder.append(',');
    }
    if (text.contains("http") || text.indexOf(ChatColor.COLOR_CHAR) != -1) {
        builder.append("\"text\":\"\",\"extra\":[");
        ++extraLevel;
        int httpIndex, colorIndex, tmp;
        String remainingText = text, url;
        do {
            httpIndex = remainingText.indexOf("http");
            colorIndex = remainingText.indexOf(ChatColor.COLOR_CHAR);
            if (httpIndex != -1 && (colorIndex == -1 || httpIndex < colorIndex)) {
                // The link is the first thing in the String
                if (httpIndex != 0) {
                    builder.append("{\"text\":\"")
                            .append(Chat.escapeString(remainingText.substring(0, httpIndex)))
                            .append("\",\"extra\":[");
                    remainingText = remainingText.substring(httpIndex);
                }
                tmp = remainingText.indexOf(' ');
                tmp = tmp == -1 ? remainingText.length() : tmp;
                url = remainingText.substring(0, tmp);
                builder.append("{\"text\":\"").append(Chat.escapeString(url)).append('"');
                Chat.appendClick(builder, Click.ofOpenUrl(url));
                builder.append('}');
                if (httpIndex != 0) {
                    builder.append("]}");
                }
                remainingText = remainingText.substring(url.length());
            } else if (colorIndex != -1 && (httpIndex == -1 || colorIndex < httpIndex)) {
                // The color change is the first thing in the String
                if (colorIndex != 0) {
                    builder.append("{\"text\":\"")
                            .append(Chat.escapeString(remainingText.substring(0, colorIndex)))
                            .append("\",\"extra\":[");
                    ++extraLevel;
                    remainingText = remainingText.substring(colorIndex);
                }
                try {
                    builder.append("{\"text\":\"\",\"color\":\"")
                            .append(Chat.getColorString(remainingText.charAt(1))).append("\",\"extra\":[");
                } catch (final IndexOutOfBoundsException e) {
                    throw new IllegalArgumentException("Malformed input: incomplete color code", e);
                }
                ++extraLevel;
                remainingText = remainingText.substring(2);
            } else {
                // Can't be at the same place: they're both equal to -1. Just append everything left.
                builder.append('"').append(Chat.escapeString(remainingText)).append('"');
                remainingText = "";
            }
            if (!remainingText.isEmpty()) {
                builder.append(',');
            }
        } while (!remainingText.isEmpty());
    } else {
        builder.append("\"text\":\"").append(Chat.escapeString(text)).append('"');
    }
    return extraLevel;
}

From source file:fr.ribesg.bukkit.api.chat.Chat.java

private static void appendHover(final StringBuilder builder, final Hover hover, final boolean noText) {
    if (hover != null) {
        if (builder.charAt(builder.length() - 1) != '{') {
            builder.append(',');
        }/*w ww .  j a va  2 s .co m*/
        builder.append("\"hoverEvent\":{\"value\":\"");
        switch (hover.getType()) {
        case SHOW_ACHIEVEMENT:
            builder.append(Chat.getAchievementId(hover.getAchievement()))
                    .append("\",\"action\":\"show_achievement\"}");
            if (noText) {
                // FIXME Append achievement name as "translate" (How?)
                builder.append("\"text\":\"").append(hover.getAchievement().name()).append('"');
            }
            break;
        case SHOW_ITEM:
            Chat.appendItem(builder, hover.getItem());
            builder.append("\",\"action\":\"show_item\"}");
            if (noText) {
                // FIXME Append item name as "translate" (How?)
                builder.append("\"text\":\"").append(hover.getItem().getType()).append('"');
            }
            break;
        case SHOW_TEXT:
            builder.append(Chat.escapeString(StringUtils.join(hover.getText(), '\n')));
            builder.append("\",\"action\":\"show_text\"}");
            break;
        }
    }
}

From source file:org.etudes.util.HtmlHelper.java

/**
 * Remove any characters from the data that will cause mysql to reject the record because of encoding errors<br />
 * (java.sql.SQLException: Incorrect string value) if they are present.
 * //  ww w  .  j  ava  2s  .co  m
 * @param data
 *        The html data.
 * @return The data with the bad characters replaced with spaces.
 */
public static String stripBadEncodingCharacters(String data) {
    // Note: these characters become two characters in the String - the first is 56256 0xDBC0 or 55304 0xD808 and the second varies, but is 56xxx

    if (data == null)
        return data;

    // quick check for any strange characters
    if ((data.indexOf(56256) == -1) && (data.indexOf(55304) == -1))
        return data;

    StringBuilder buf = new StringBuilder(data);
    int len = buf.length() - 1;
    for (int i = 0; i < len; i++) {
        char c = buf.charAt(i);
        if ((c == 56256) || (c == 55304)) {
            buf.setCharAt(i, ' ');
            i++;
            buf.setCharAt(i, ' ');
        }
    }

    return buf.toString();
}

From source file:Main.java

/**
 * Returns a valid Java name from an XML Name.
 *
 * @param name//  w  w w.  java 2s  .  c  om
 * @param isUpperCase
 * @return a valid Java name from an XML Name
 */
public static String getJavaNameFromXMLName(String name, boolean isUpperCase) {
    List<String> parsedName = parseName(name, '_');
    StringBuilder result = new StringBuilder(64 * parsedName.size());
    for (String nameComponent : parsedName) {
        if (nameComponent.length() > 0) {
            if (result.length() > 0 || isUpperCase) {
                result.append(Character.toUpperCase(nameComponent.charAt(0)));
                result.append(nameComponent.substring(1));
            } else {
                result.append(nameComponent);
            }
        }
    }

    if (result.length() == 0) {
        return "_";
    }
    if (Character.isJavaIdentifierStart(result.charAt(0))) {
        return isUpperCase ? result.toString() : decapitalizeName(result.toString());
    }
    return "_" + result;
}