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

com.fastchar.openapi.core.FastOpenAPIHelper Maven / Gradle / Ivy

The newest version!
package com.fastchar.openapi.core;

import com.fastchar.core.FastChar;
import com.fastchar.core.FastMapWrap;
import com.fastchar.core.FastResource;
import com.fastchar.openapi.FastCharOpenAPIConfig;
import com.fastchar.utils.FastFileUtils;
import com.fastchar.utils.FastStringUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FastOpenAPIHelper {

    /**
     * 替换占位符 ${.*}
     *
     * @param placeholders 属性值
     * @param content      需要替换的内容
     * @return 替换后的内容
     */
    public static String replacePlaceholder(Map placeholders, String content) {
        if (FastStringUtils.isEmpty(content)) {
            return content;
        }
        Pattern compile = Pattern.compile("(\\$[{\\[][^{}\\[\\]]+[}\\]])");
        Matcher matcher = compile.matcher(content);
        FastMapWrap fastMapWrap = FastMapWrap.newInstance(placeholders);

        Map keyValue = new HashMap<>();
        while (matcher.find()) {
            String realKey = matcher.group(1);
            String runKey = realKey.replace("[", "{").replace("]", "}");
            String value = fastMapWrap.getString(runKey, "");
            keyValue.put(realKey, value);
        }
        for (String key : keyValue.keySet()) {
            content = content.replace(key, keyValue.get(key));
        }
        return content;
    }


    public static String buildLoginHtml(String projectHost,String docTitle,String primaryColor,String logo) {
        FastCharOpenAPIConfig config = FastChar.getConfig(FastCharOpenAPIConfig.class);

        FastResource resource = FastChar.getResources().getResource("web/html/open-api-login.html");
        if (resource != null) {
            try {
                List strings = FastFileUtils.readLines(resource.getInputStream(), StandardCharsets.UTF_8);
                String htmlContent = FastStringUtils.join(strings, "\n");

                Map holder = new HashMap<>();
                holder.put("http", projectHost);
                holder.put("title", docTitle);
                holder.put("color", primaryColor);
                String openApiRoute = FastStringUtils.stripStart(config.getOpenApiRoute(), "/");
                holder.put("indexUrl", projectHost + openApiRoute);
                holder.put("loginUrl", projectHost + openApiRoute + "/login");
                holder.put("logo", logo);

                return replacePlaceholder(holder, htmlContent);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return "";
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy