All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.dennisit.vplus.data.utils.MixUtils Maven / Gradle / Ivy

/*--------------------------------------------------------------------------
 *  Copyright (c) 2010-2020, Elon.su All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the elon developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: Elon.su, you can also mail [email protected]
 *--------------------------------------------------------------------------
*/
package com.github.dennisit.vplus.data.utils;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Elon.su on 17/11/30.
 */
public class MixUtils {

    /**
     * 空串值或者目标值的渲染
     */
    public static final Pattern NAMES_PATTERN = Pattern.compile("\\{([\\w\\.]*)\\}");

    private MixUtils() {
        // 私有构造
    }

    /**
     * 替换目标串中的占位符为给定数值
     * @param source 目标串
     * @param variables 替换值
     * @return 渲染结果
     */
    public static final String mixup(String source, Map variables) {
        if(null == variables || variables.isEmpty()){
            return source;
        }
        return mixup(source, new MapVariables(variables));
    }


    /**
     * 替换目标串中的占位符为给定数值
     * @param source 目标串
     * @param variableValues 替换值
     * @return 渲染结果
     */
    public static final String mixup(String source, Object... variableValues) {
        if(null == variableValues || 0 == variableValues.length){
            return source;
        }
        return mixup(source, new VarArgsVariables(variableValues));
    }


    /**
     * 替换处理逻辑
     * @param source 目标串
     * @param templateVariables 替换值规范
     * @return 处理结果
     */
    private static String mixup(String source, TemplateVariables templateVariables) {
        if (null == source) {
            return null;
        }
        if (source.indexOf('{') == -1) {
            return source;
        }
        if (source.indexOf(':') != -1) {
            source = sanitizeSource(source);
        }
        Matcher matcher = NAMES_PATTERN.matcher(source);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String match = matcher.group();
            String variableName = getVariableName(match);
            Object variableValue = templateVariables.getValue(variableName);
            String variableString = getValueAsString(variableValue);
            String replacement = Matcher.quoteReplacement(variableString);
            matcher.appendReplacement(sb, replacement);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }


    private static String getVariableName(String match) {
        int colonIdx = match.indexOf(':');
        return (colonIdx != -1 ? match.substring(0, colonIdx) : match);
    }


    private static String getValueAsString(Object variableValue) {
        return (variableValue != null ? variableValue.toString() : "");
    }


    /**
     * 移除待渲染串中的嵌套的"{}"符号
     * @param source 待处理字符串
     * @return 处理结果
     */
    private static String sanitizeSource(String source) {
        int level = 0;
        StringBuilder sb = new StringBuilder();
        for (char c : source.toCharArray()) {
            if (c == '{') {
                level++;
            }
            if (c == '}') {
                level--;
            }
            if (level > 1 || (level == 1 && c == '}')) {
                continue;
            }
            sb.append(c);
        }
        return sb.toString();
    }

    /*
     * 定义参数渲染行为
     */
    private interface TemplateVariables {

        Object getValue(String name);
    }


    /*
     * Map结构参数
     */
    private static class MapVariables implements TemplateVariables {

        private final Map uriVariables;

        public MapVariables(Map uriVariables) {
            this.uriVariables = uriVariables;
        }

        @Override
        public Object getValue(String name) {
            if (!this.uriVariables.containsKey(name)) {
                return null;
                // throw new IllegalArgumentException("Map has no value for '" + name + "'");
            }
            return this.uriVariables.get(name);
        }
    }

    /*
     * 数组结构参数
     */
    private static class VarArgsVariables implements TemplateVariables {

        private final Iterator valueIterator;

        public VarArgsVariables(Object... uriVariableValues) {
            this.valueIterator = Arrays.asList(uriVariableValues).iterator();
        }

        @Override
        public Object getValue(String name) {
            if (!this.valueIterator.hasNext()) {
                return null;
                //throw new IllegalArgumentException("Not enough variable values available to expand '" + name + "'");
            }
            return this.valueIterator.next();
        }
    }

}