Java String Substritute substituteVars(String text, char[] names, Object[] values)

Here you can find the source of substituteVars(String text, char[] names, Object[] values)

Description

Equivalent to #substituteVars(String,char[],Object[],String[],String,boolean) substituteVars(text, names, values, null, null, false) .

License

Open Source License

Declaration

public static String substituteVars(String text, char[] names, Object[] values) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from   ww w  . j  ava 2  s .  c  o  m*/
     * Equivalent to {@link
     * #substituteVars(String, char[], Object[], String[], String, boolean)
     * substituteVars(text, names, values, null, null, false)}.
     */
    public static String substituteVars(String text, char[] names, Object[] values) {
        return substituteVars(text, names, values, null, null, false);
    }

    /**
     * Equivalent to {@link
     * #substituteVars(String, char[], Object[], String[], String, boolean)
     * substituteVars(text, names, values, args, allArgs, false)}.
     */
    public static String substituteVars(String text, char[] names, Object[] values, String[] args, String allArgs) {
        return substituteVars(text, names, values, args, allArgs, false);
    }

    /**
     * Returns specified text where %0, %1, ..., %9, %* and %<i>X</i>, 
     * %<i>Y</i>, etc, variables have been subsituted by specified values.
     * <p>"%%" may be used to escape character "%".
     * <p>A variable, whether named or not, %<i>X</i> may also be specified as
     * %{<i>X</i>} etc.
     * 
     * @param text text containing variables
     * @param names the one-character long name of named variables %<i>X</i>,
     * %<i>Y</i>, etc.
     * <p>May be <code>null</code>.
     * @param values the values of named variables %<i>X</i>, %<i>Y</i>, etc.
     * <p>These objects are converted to strings using the
     * <code>toString()</code> method.
     * <p>When there are no enough values, the corresponding variables are not
     * replaced.
     * <p>May be <code>null</code> if <tt>names</tt> is also <code>null</code>.
     * @param args the values of <tt>%0</tt>, <tt>%1</tt>, ..., 
     * <tt>%9</tt> variables.
     * <p>When there are no enough values, the corresponding variables are
     * replaced by the empty string.
     * <p>May be <code>null</code>.
     * @param allArgs the values of <tt>%*</tt> variable. 
     * <p>May be <code>null</code>, in which case, <tt>args</tt> are joined 
     * using {@link #joinArguments} to form <tt>allArgs</tt>.
     * @param allowForeignVars if <code>true</code>, unknown variables
     * specified as %{<i>var_name</i>} are assumed to be system properties or
     * environment variables and are subsituted as such.
     * @return specified text where variables have been subsituted with their
     * values
     */
    public static String substituteVars(String text, char[] names, Object[] values, String[] args, String allArgs,
            boolean allowForeignVars) {
        StringBuilder buffer = new StringBuilder();
        int state = 0;

        int length = text.length();
        for (int i = 0; i < length; ++i) {
            char c = text.charAt(i);

            switch (state) {
            case 1: // Seen "%"
                switch (c) {
                case '%':
                    buffer.append('%');
                    state = 0;
                    break;

                case '{':
                    state = 2;
                    break;

                case '*':
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    if (args == null) {
                        // Not a variable.
                        buffer.append('%');
                        buffer.append(c);
                    } else {
                        if (c == '*') {
                            buffer.append((allArgs == null) ? joinArguments(args) : allArgs);
                        } else {
                            // c is a digit ---

                            int j = i + 1;
                            while (j < length) {
                                char cc = text.charAt(j);
                                if (cc >= '0' && cc <= '9') {
                                    ++j;
                                } else {
                                    break;
                                }
                            }
                            String indexSpec = text.substring(i, j);

                            int index = -1;
                            try {
                                index = Integer.parseInt(indexSpec);
                            } catch (NumberFormatException cannotHappen) {
                            }

                            if (index >= 0 && index < args.length) {
                                buffer.append(args[index]);
                            } else {
                                // Not a variable.
                                buffer.append('%');
                                buffer.append(indexSpec);
                            }

                            i = j - 1;
                        }
                    }
                    state = 0;
                    break;

                default:
                    if (names == null) {
                        // Not a variable.
                        buffer.append('%');
                        buffer.append(c);
                    } else {
                        Object value = null;
                        for (int j = 0; j < names.length; ++j) {
                            if (c == names[j]) {
                                value = values[j];
                                break;
                            }
                        }
                        if (value == null) {
                            // Not a variable.
                            buffer.append('%');
                            buffer.append(c);
                        } else {
                            buffer.append(value.toString());
                        }
                    }
                    state = 0;
                }
                break;

            case 2: // Seen "%{"
                switch (c) {
                case '*':
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    if (args == null) {
                        // Not a variable.
                        buffer.append("%{");
                        buffer.append(c);
                        state = 0;
                    } else {
                        if (c == '*') {
                            buffer.append((allArgs == null) ? joinArguments(args) : allArgs);
                            state = 3;
                        } else {
                            // c is a digit ---

                            int j = i + 1;
                            while (j < length) {
                                char cc = text.charAt(j);
                                if (cc >= '0' && cc <= '9') {
                                    ++j;
                                } else {
                                    break;
                                }
                            }
                            String indexSpec = text.substring(i, j);

                            int index = -1;
                            try {
                                index = Integer.parseInt(indexSpec);
                            } catch (NumberFormatException cannotHappen) {
                            }

                            if (index >= 0 && index < args.length) {
                                buffer.append(args[index]);
                                state = 3;
                            } else {
                                // Not a variable.
                                buffer.append("%{");
                                buffer.append(indexSpec);
                                state = 0;
                            }

                            i = j - 1;
                        }
                    }
                    break;

                default:
                    if (names == null) {
                        if (allowForeignVars) {
                            int end = text.indexOf('}', i + 1);
                            if (end > i + 1) {
                                String value = getForeignVar(text, i, end);
                                if (value != null) {
                                    buffer.append(value);
                                    state = 3;
                                    i = end - 1;
                                }
                            }
                        }

                        if (state != 3) {
                            // Not a variable.
                            buffer.append("%{");
                            buffer.append(c);
                            state = 0;
                        }
                    } else {
                        // Note that "%{%}" and "%{{}" are supported.

                        Object found = null;

                        for (int j = 0; j < names.length; ++j) {
                            if (c == names[j]) {
                                found = values[j];
                                break;
                            }
                        }

                        if (found != null && i + 1 < length && text.charAt(i + 1) == '}') {
                            buffer.append(found.toString());
                            state = 3;
                        } else {
                            if (allowForeignVars) {
                                int end = text.indexOf('}', i + 1);
                                if (end > i + 1) {
                                    String value = getForeignVar(text, i, end);
                                    if (value != null) {
                                        buffer.append(value);
                                        state = 3;
                                        i = end - 1;
                                    }
                                }
                            }

                            if (state != 3) {
                                // Not a variable.
                                buffer.append("%{");
                                buffer.append(c);
                                state = 0;
                            }
                        }
                    }
                }
                break;

            case 3: // Seen "%{x"
                if (c != '}') {
                    buffer.append(c);
                }
                state = 0;
                break;

            default:
                if (c == '%') {
                    state = 1;
                } else {
                    buffer.append(c);
                }
            }
        }

        switch (state) {
        case 1:
            buffer.append('%');
            break;
        case 2:
            buffer.append("%{");
            break;
        }

        return buffer.toString();
    }

    /**
     * Inverse operation of {@link #splitArguments}. Returns ``command line''.
     * 
     * @see #quoteArgument
     */
    public static String joinArguments(String... args) {
        StringBuilder joined = new StringBuilder();

        for (int i = 0; i < args.length; ++i) {
            if (i > 0)
                joined.append(' ');
            joined.append(quoteArgument(args[i]));
        }

        return joined.toString();
    }

    private static String getForeignVar(String text, int start, int end) {
        String value = null;

        String name = text.substring(start, end).trim();
        if (name.length() > 0) {
            value = System.getProperty(name);
            if (value == null) {
                value = System.getenv(name);
            }
        }

        return value;
    }

    /**
     * Quotes specified string using <tt>'\"'</tt> if needed to. Returns
     * quoted string.
     * <p>Note that whitespace characters such as '\n' and '\t' are not
     * escaped as "\n" and "\t". Instead, the whole string is quoted. This is
     * sufficient to allow it to contain any whitespace character.
     * 
     * @see #joinArguments
     */
    public static String quoteArgument(String arg) {
        int length = arg.length();

        boolean needQuotes;
        if (length == 0) {
            needQuotes = true;
        } else {
            switch (arg.charAt(0)) {
            case '\"':
            case '\'':
                needQuotes = true;
                break;
            default: {
                needQuotes = false;
                for (int i = 0; i < length; ++i) {
                    if (Character.isWhitespace(arg.charAt(i))) {
                        needQuotes = true;
                        break;
                    }
                }
            }
            }
        }
        if (!needQuotes)
            return arg;

        StringBuilder quoted = new StringBuilder();
        quoted.append('\"');
        for (int i = 0; i < length; ++i) {
            char c = arg.charAt(i);

            if (c == '\"')
                quoted.append("\\\"");
            else
                quoted.append(c);
        }
        quoted.append('\"');

        return quoted.toString();
    }
}

Related

  1. substituteSymbol(String text, String symbol, String value)
  2. substituteTabsAndNewLinesWithSpaces(String str)
  3. substituteText(String text, String token, String substitute)
  4. substituteToken(StringBuffer buf, String token, String value)
  5. substituteUserId(final long aUserId, final String aTemplate)
  6. substituteWhenEmpty(Object value, String valueWhenEmpty)