ES报文辅助生成工具-JavaFX

此程序为基于 Java8 开发的 JavaFX Maven 工程,是 Java 组装ElasticSearch请求报文工具的辅助 Java 代码生成工具,方便开发者快速编写代码。现学现用,写得不好。

工具界面

在这里插入图片描述

代码

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.fx</groupId>
  <artifactId>esjson</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <name>EsjsonFx</name>
  <description>EsjsonFx</description>
  
  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  
  <dependencies>
	<dependency>
	    <groupId>com.google.code.gson</groupId>
	    <artifactId>gson</artifactId>
	    <version>2.10</version>
	</dependency>
  </dependencies>
  
  <build>
	<resources>
		<resource>
            <directory>config</directory>
            <targetPath>${project.build.directory}/jfx/app/config</targetPath>
        </resource>
        <resource>
			<!--把src/main/resources目录下的properties、xm文件打包打进程序中-->
			<directory>src/main/resources</directory>
			<includes>
				<include>**/*.properties</include>
				<include>**/*.xml</include>
				<include>**/*.fxml</include>
				<include>**/*.setting</include>
				<include>**/*.png</include>
			</includes>
			<filtering>false</filtering>
		</resource>
	</resources>
	<plugins>
		<plugin>
			<groupId>com.zenjava</groupId>
			<artifactId>javafx-maven-plugin</artifactId>
			<version>8.8.3</version>
			<configuration>
				<!-- 作者 -->
				<vendor></vendor>
				<!-- main方法的类 -->
				<mainClass>com.fx.esjson.MainApplication</mainClass>
				<!-- 运行文件名 -->
				<appName>${project.build.finalName}</appName>
				<!-- 发行版本 -->
				<nativeReleaseVersion>${project.version}</nativeReleaseVersion>
				<!-- 图标的位置,默认位置 src/main/deploy -->
				<!--<deployDir>${basedir}/src/main/resources/icon/icon.png</deployDir>-->
				<!-- 菜单 -->
				<needMenu>true</needMenu>
				<!-- 桌面图标 -->
				<needShortcut>true</needShortcut>
				<source>${maven.compiler.source}</source>
                <target>${maven.compiler.target}</target>
                <encoding>${project.build.sourceEncoding}</encoding>
                <bundleArguments>
                    <icon>${project.basedir}/src/main/resources/icon/icon.png</icon>
                    <!--下面这2个参数搭配,可实现一个特别重要的功能,就是,提示用户手动选择程序安装目录,默认目录是在:C:\Program Files (x86)\appName-->
                    <!--设置为true将在Program Files中安装应用程序。设置为false将应用程序安装到用户的主目录中。默认值为false。-->
                    <systemWide>true</systemWide>
                    <!-- 让用户选择安装目标文件夹 -->
                    <installdirChooser>true</installdirChooser>
                </bundleArguments>
			</configuration>
		</plugin>
	</plugins>
  </build>
</project>

应用图标路径

/src/main/resources/icon/icon.png

CharEnum.java

package com.fx.esjson;

public enum CharEnum {
	DOT("."),
	SPACE(" "),
	DOUBLE_QUOTE("\""),
	NULL("null"),
	COMMA(","),
	CURVE_LEFT("("),
	CURVE_RIGHT(")"),
	;

	private String ch;
	
	private CharEnum (String ch) {
		this.ch = ch;
	}

	public String getCh() {
		return ch;
	}
	
}

LineToken.java

package com.fx.esjson;

import java.util.ArrayList;
import java.util.List;

public class LineToken {

	/**
	 * 缩进次数
	 */
	private Integer indentCnt;
	
	/**
	 * 缩进字符
	 */
	private String indentChar;
	
	/**
	 * 一行中的字符串
	 */
	private List<String> lineStrs;
	
	/**
	 * 是否允许追加到前一个对象
	 */
	private Boolean allowAppendTo;
	
	/**
	 * 是否允许后面的对象追加进来
	 */
	private Boolean canAppendInto;
	
	/**
	 * 是否以左括号结尾
	 */
	private Boolean endsWithCurveLeft;
	
	/**
	 * 是否右括号
	 */
	private Boolean curveRight;

	public Integer getIndentCnt() {
		return indentCnt;
	}

	public void setIndentCnt(Integer indentCnt) {
		this.indentCnt = indentCnt;
	}

	public String getIndentChar() {
		return indentChar;
	}

	public void setIndentChar(String indentChar) {
		this.indentChar = indentChar;
	}

	public List<String> getLineStrs() {
		return lineStrs;
	}

	public void setLineStrs(List<String> lineStrs) {
		this.lineStrs = lineStrs;
	}

	public Boolean getAllowAppendTo() {
		return allowAppendTo;
	}

	public void setAllowAppendTo(Boolean allowAppendTo) {
		this.allowAppendTo = allowAppendTo;
	}
	
	public Boolean getCanAppendInto() {
		return canAppendInto;
	}

	public void setCanAppendInto(Boolean canAppendInto) {
		this.canAppendInto = canAppendInto;
	}

	public Boolean getEndsWithCurveLeft() {
		return endsWithCurveLeft;
	}

	public void setEndsWithCurveLeft(Boolean endsWithCurveLeft) {
		this.endsWithCurveLeft = endsWithCurveLeft;
	}

	public Boolean getCurveRight() {
		return curveRight;
	}

	public void setCurveRight(Boolean curveRight) {
		this.curveRight = curveRight;
	}

	public void appendLineStrs(String... strs) {
		if (strs != null) {
			if (lineStrs == null) {
				lineStrs = new ArrayList<>();
			}
			for (String str : strs) {
				lineStrs.add(str);
			}
		}
	}
	
	public void appendLineStrs(List<String> lineStrs) {
		if (lineStrs != null) {
			if (this.lineStrs == null) {
				this.lineStrs = new ArrayList<>();
			}
			this.lineStrs.addAll(lineStrs);
		}
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		if (this.indentCnt != null && this.indentChar != null) {
			int cnt = this.indentCnt;
			String ch = this.indentChar;
			for (int i = 0; i < cnt; i++) {
				sb.append(ch);
			}
		}
		if (this.lineStrs != null) {
			List<String> lineStrs = this.lineStrs;
			for (String str : lineStrs) {
				sb.append(str);
			}
		}
		return sb.toString();
	}
	
}

FormatConfig.java

package com.fx.esjson;

public class FormatConfig {
	
	/**
	 * 全限定包名
	 */
	private String fullPackageName;
	
	/**
	 * 缩进次数
	 */
	private Integer indentCnt;
	
	/**
	 * 缩进字符
	 */
	private String indentChar;
	
	/**
	 * 静态kv方法名称
	 */
	private String staticKv;
	
	/**
	 * 动态kv方法名称
	 */
	private String dynamicKv;
	
	/**
	 * 静态数组方法名称
	 */
	private String staticArr;
	
	/**
	 * 动态数组方法名称
	 */
	private String dynamicArr;

	public String getFullPackageName() {
		return fullPackageName;
	}

	public void setFullPackageName(String fullPackageName) {
		this.fullPackageName = fullPackageName;
	}

	public Integer getIndentCnt() {
		return indentCnt;
	}

	public void setIndentCnt(Integer indentCnt) {
		this.indentCnt = indentCnt;
	}

	public String getIndentChar() {
		return indentChar;
	}

	public void setIndentChar(String indentChar) {
		this.indentChar = indentChar;
	}

	public String getStaticKv() {
		return staticKv;
	}

	public void setStaticKv(String staticKv) {
		this.staticKv = staticKv;
	}

	public String getDynamicKv() {
		return dynamicKv;
	}

	public void setDynamicKv(String dynamicKv) {
		this.dynamicKv = dynamicKv;
	}

	public String getStaticArr() {
		return staticArr;
	}

	public void setStaticArr(String staticArr) {
		this.staticArr = staticArr;
	}

	public String getDynamicArr() {
		return dynamicArr;
	}

	public void setDynamicArr(String dynamicArr) {
		this.dynamicArr = dynamicArr;
	}
	
}

CodeFormatUtils.java

核心类

package com.fx.esjson;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;

public class CodeFormatUtils {
	
	public static String getStaticPackage(FormatConfig formatConfig) {
		StringBuilder sb = new StringBuilder();
		sb.append("import static ").append(formatConfig.getFullPackageName()).append(CharEnum.DOT.getCh())
				.append("JsonSupport").append(CharEnum.DOT.getCh()).append(formatConfig.getStaticKv()).append(";");
		sb.append("\n");
		sb.append("import static ").append(formatConfig.getFullPackageName()).append(CharEnum.DOT.getCh())
				.append("JsonSupport").append(CharEnum.DOT.getCh()).append(formatConfig.getStaticArr()).append(";");
		return sb.toString();
	}

	public static String getCode (String json, FormatConfig formatConfig) {
		JsonElement element = JsonParser.parseString(json);
		if (!element.isJsonArray() && !element.isJsonObject()) {
			throw new RuntimeException("请在左侧面板输入 json 格式的文本...");
		}
		List<LineToken> list = new ArrayList<>();
		intoList(list, element, formatConfig);
		Iterator<LineToken> iterator = list.iterator();
		
		LineToken prevToken = null;
		while (iterator.hasNext()) {
			LineToken lineToken = iterator.next();
			if (prevToken == null) {
				prevToken = lineToken;
			} else {
				if (prevToken.getCanAppendInto() && lineToken.getAllowAppendTo()) {
					if (!lineToken.getCurveRight() && !prevToken.getEndsWithCurveLeft()) {
						prevToken.appendLineStrs(CharEnum.SPACE.getCh());
					}
					prevToken.appendLineStrs(lineToken.getLineStrs());
					prevToken.setCanAppendInto(lineToken.getCanAppendInto());
					iterator.remove();
				} else {
					prevToken = lineToken;
				}
			}
			
		}
		
		StringBuilder sb = new StringBuilder();
		for (LineToken lineToken : list) {
			if (sb.length() > 0) {
				sb.append("\n");
			}
			sb.append(lineToken.toString());
		}
		sb.append(";");
		return sb.toString();
	}
	
	private static void intoList (List<LineToken> list, JsonElement element, FormatConfig formatConfig) {
		if (element.isJsonObject()) {
			int preCnt = 0 - formatConfig.getIndentCnt();
			if (!list.isEmpty()) {
				int index = list.size() - 1;
				preCnt = list.get(index).getIndentCnt();
			}
			JsonObject jsonObject = element.getAsJsonObject();
			LineToken primaryToken = new LineToken();
			primaryToken.setIndentCnt(formatConfig.getIndentCnt() + preCnt);
			primaryToken.setIndentChar(formatConfig.getIndentChar());
			primaryToken.setAllowAppendTo(false);
			primaryToken.setCanAppendInto(false);
			primaryToken.setEndsWithCurveLeft(false);
			primaryToken.setCurveRight(false);
			primaryToken.appendLineStrs(formatConfig.getStaticKv(), CharEnum.CURVE_LEFT.getCh(), CharEnum.CURVE_RIGHT.getCh());
			list.add(primaryToken);
			Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
			for (Entry<String, JsonElement> entry : entrySet) {
				LineToken startToken = new LineToken();
				startToken.setIndentCnt(formatConfig.getIndentCnt() + preCnt);
				startToken.setIndentChar(formatConfig.getIndentChar());
				startToken.setAllowAppendTo(false);
				startToken.setCanAppendInto(true);
				startToken.setEndsWithCurveLeft(false);
				startToken.setCurveRight(false);
				startToken.appendLineStrs(CharEnum.DOT.getCh(), formatConfig.getDynamicKv(), CharEnum.CURVE_LEFT.getCh(), CharEnum.DOUBLE_QUOTE.getCh(), entry.getKey(), CharEnum.DOUBLE_QUOTE.getCh(), CharEnum.COMMA.getCh());
				list.add(startToken);
				JsonElement value = entry.getValue();
				if (value.isJsonObject() || value.isJsonArray()) {
					intoList(list, value, formatConfig);
				} else {
					primitiveIntoList(list, value, formatConfig);
				}
				LineToken endToken = new LineToken();
				endToken.setIndentCnt(formatConfig.getIndentCnt() + preCnt);
				endToken.setIndentChar(formatConfig.getIndentChar());
				endToken.setAllowAppendTo(true);
				endToken.setCanAppendInto(false);
				endToken.setEndsWithCurveLeft(false);
				endToken.setCurveRight(true);
				endToken.appendLineStrs(CharEnum.CURVE_RIGHT.getCh());
				list.add(endToken);
			}
		} else if (element.isJsonArray()) {
			int preCnt = 0 - formatConfig.getIndentCnt();
			if (!list.isEmpty()) {
				int index = list.size() - 1;
				preCnt = list.get(index).getIndentCnt();
			}
			JsonArray jsonArray = element.getAsJsonArray();
			if (jsonArray.isEmpty()) {
				throw new RuntimeException("ElasticSearch 请求报文不能存在空数组");
			}
			if (isAllString(jsonArray)) {
				list.add(generatePlainArr(jsonArray, true));
			} else if (isAllNonString(jsonArray)) {
				list.add(generatePlainArr(jsonArray, false));
			} else {
				LineToken primaryToken = new LineToken();
				primaryToken.setIndentCnt(formatConfig.getIndentCnt() + preCnt);
				primaryToken.setIndentChar(formatConfig.getIndentChar());
				primaryToken.setAllowAppendTo(false);
				primaryToken.setCanAppendInto(false);
				primaryToken.setEndsWithCurveLeft(false);
				primaryToken.setCurveRight(false);
				primaryToken.appendLineStrs(formatConfig.getStaticArr(), CharEnum.CURVE_LEFT.getCh(), CharEnum.CURVE_RIGHT.getCh());
				list.add(primaryToken);
				for (JsonElement jsonElement : jsonArray) {
					LineToken startToken = new LineToken();
					startToken.setIndentCnt(formatConfig.getIndentCnt() + preCnt);
					startToken.setIndentChar(formatConfig.getIndentChar());
					startToken.setAllowAppendTo(false);
					startToken.setCanAppendInto(true);
					startToken.setEndsWithCurveLeft(true);
					startToken.setCurveRight(false);
					startToken.appendLineStrs(CharEnum.DOT.getCh(), formatConfig.getDynamicArr(), CharEnum.CURVE_LEFT.getCh());
					list.add(startToken);
					intoList(list, jsonElement, formatConfig);
					LineToken endToken = new LineToken();
					endToken.setIndentCnt(formatConfig.getIndentCnt() + preCnt);
					endToken.setIndentChar(formatConfig.getIndentChar());
					endToken.setAllowAppendTo(true);
					endToken.setCanAppendInto(false);
					endToken.setEndsWithCurveLeft(false);
					endToken.setCurveRight(true);
					endToken.appendLineStrs(CharEnum.CURVE_RIGHT.getCh());
					list.add(endToken);
				}
			}
		} else {
			primitiveIntoList(list, element, formatConfig);
		}
	}
	
	private static void primitiveIntoList (List<LineToken> list, JsonElement element, FormatConfig formatConfig) {
		int preCnt = 0 - formatConfig.getIndentCnt();
		if (!list.isEmpty()) {
			int index = list.size() - 1;
			preCnt = list.get(index).getIndentCnt();
		}
		if (element.isJsonNull()) {
			throw new RuntimeException("ElasticSearch 请求报文不能包含 null");
		} else if (element.isJsonPrimitive()) {
			JsonPrimitive primitive = element.getAsJsonPrimitive();
			if (primitive.isBoolean() || primitive.isNumber()) {
				LineToken lineToken = new LineToken();
				lineToken.setIndentCnt(formatConfig.getIndentCnt() + preCnt);
				lineToken.setIndentChar(formatConfig.getIndentChar());
				lineToken.setAllowAppendTo(true);
				lineToken.setCanAppendInto(true);
				lineToken.setEndsWithCurveLeft(false);
				lineToken.setCurveRight(false);
				String str = primitive.getAsString();
				if (isLong(str)) {
					lineToken.appendLineStrs(str, "L");
				} else {
					lineToken.appendLineStrs(str);
				}
				list.add(lineToken);
			} else if (primitive.isString()) {
				LineToken lineToken = new LineToken();
				lineToken.setIndentCnt(formatConfig.getIndentCnt() + preCnt);
				lineToken.setIndentChar(formatConfig.getIndentChar());
				lineToken.setAllowAppendTo(true);
				lineToken.setCanAppendInto(true);
				lineToken.setEndsWithCurveLeft(false);
				lineToken.setCurveRight(false);
				lineToken.appendLineStrs(CharEnum.DOUBLE_QUOTE.getCh(), primitive.getAsString(), CharEnum.DOUBLE_QUOTE.getCh());
				list.add(lineToken);
			}
		}
	}
	
	private static boolean isAllString (JsonArray jsonArray) {
		for (JsonElement jsonElement : jsonArray) {
			if (jsonElement.isJsonPrimitive()) {
				JsonPrimitive primitive = jsonElement.getAsJsonPrimitive();
				if (!primitive.isString()) {
					return false;
				}
			} else {
				return false;
			}
		}
		return true;
	}
	
	private static boolean isAllNonString (JsonArray jsonArray) {
		for (JsonElement jsonElement : jsonArray) {
			if (jsonElement.isJsonNull()) {
				throw new RuntimeException("ElasticSearch 请求报文不能包含 null");
			}
			if (jsonElement.isJsonPrimitive()) {
				JsonPrimitive primitive = jsonElement.getAsJsonPrimitive();
				if (primitive.isString()) {
					return false;
				}
			} else {
				return false;
			}
		}
		return true;
	}
	
	private static LineToken generatePlainArr (JsonArray jsonArray, boolean isString) {
		LineToken primaryToken = new LineToken();
		primaryToken.setIndentCnt(0);
		primaryToken.setIndentChar("");
		primaryToken.setAllowAppendTo(true);
		primaryToken.setCanAppendInto(true);
		primaryToken.setEndsWithCurveLeft(false);
		primaryToken.setCurveRight(false);
		StringBuilder sb = new StringBuilder();
		sb.append(CharEnum.CURVE_LEFT.getCh())
			.append(CharEnum.CURVE_RIGHT.getCh())
			.append(CharEnum.SPACE.getCh())
			.append("->")
			.append(CharEnum.SPACE.getCh())
			.append("Stream")
			.append(CharEnum.DOT.getCh())
			.append("of")
			.append(CharEnum.CURVE_LEFT.getCh());
		int i = 0;
		if (isString) {
			for (JsonElement jsonElement : jsonArray) {
				if (i > 0) {
					sb.append(CharEnum.COMMA.getCh()).append(CharEnum.SPACE.getCh());
				} else {
					i++;
				}
				sb.append(CharEnum.DOUBLE_QUOTE.getCh()).append(jsonElement.getAsString()).append(CharEnum.DOUBLE_QUOTE.getCh());
			}
		} else {
			for (JsonElement jsonElement : jsonArray) {
				if (i > 0) {
					sb.append(CharEnum.COMMA.getCh()).append(CharEnum.SPACE.getCh());
				} else {
					i++;
				}
				String str = jsonElement.getAsString();
				if (isLong(str)) {
					sb.append(str).append("L");
				} else {
					sb.append(str);
				}
			}
		}
		sb.append(CharEnum.CURVE_RIGHT.getCh())
			.append(CharEnum.DOT.getCh())
			.append("collect")
			.append(CharEnum.CURVE_LEFT.getCh())
			.append("Collectors")
			.append(CharEnum.DOT.getCh())
			.append("toList")
			.append(CharEnum.CURVE_LEFT.getCh())
			.append(CharEnum.CURVE_RIGHT.getCh())
			.append(CharEnum.CURVE_RIGHT.getCh());
			
		primaryToken.appendLineStrs(sb.toString());
		return primaryToken;
	}
	
	private static boolean isLong (String str) {
		if (str == null) {
			return false;
		}
		if (!str.matches("^-?\\d+$")) {
			return false;
		}
		long longValue = Long.valueOf(str).longValue();
		if (longValue < Integer.MIN_VALUE || longValue > Integer.MAX_VALUE) {
			return true;
		}
		return false;
	}
	
}

FileUtils.java

用于持久化

package com.fx.esjson;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public final class FileUtils {

	private FileUtils () {}
	
	public static String readFileToString (File file) throws IOException {
		String content = "";
		StringBuilder sb = new StringBuilder();
		try (
				BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
				) {
			int i = 0;
			while ((content = reader.readLine()) != null) {
				if (i > 0) {
					sb.append("\n");
				} else {
					i++;
				}
				sb.append(content);
			}
		}
		return sb.toString();
	}
	
	public static void writeFile (File file, String str) throws IOException {
		try (
				BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
				) {
			writer.write(str);
			writer.flush();
		}
	}
	
	public static FormatConfig defaultConfig () {
		FormatConfig formatConfig = new FormatConfig();
		formatConfig.setFullPackageName("com.fx.learn");
		formatConfig.setIndentCnt(4);
		formatConfig.setIndentChar(" ");
		formatConfig.setStaticKv("KV");
		formatConfig.setDynamicKv("kv");
		formatConfig.setStaticArr("L");
		formatConfig.setDynamicArr("l");
		return formatConfig;
	}
	
	public static FormatConfig readConfig () {
		FormatConfig defaultConfig = defaultConfig();
		return readConfig(defaultConfig);
	}
	
	private static FormatConfig readConfig (FormatConfig defaultConfig) {
		try {
			File dir = new File("config");
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File file = new File(dir, "config.json");
			if (!file.exists()) {
				file.createNewFile();
			}
			String str = readFileToString(file);
			if (str == null || str.isEmpty()) {
				return defaultConfig;
			}
			Gson gson = new Gson();
			FormatConfig formatConfig = gson.fromJson(str, FormatConfig.class);
			if (formatConfig == null) {
				return defaultConfig;
			}
			if (formatConfig.getFullPackageName() == null || !formatConfig.getFullPackageName().matches("^[a-zA-Z0-9_\\.]{0,256}$")) {
				formatConfig.setFullPackageName(defaultConfig.getFullPackageName());
			}
			if (!" ".equals(formatConfig.getIndentChar()) && !"\t".equals(formatConfig.getIndentChar())) {
				formatConfig.setIndentChar(defaultConfig.getIndentChar());
			}
			Integer indentCnt = formatConfig.getIndentCnt();
			if (indentCnt == null || indentCnt < 0 || indentCnt > 8) {
				if (" ".equals(formatConfig.getIndentChar())) {
					formatConfig.setIndentCnt(4);
				} else {
					formatConfig.setIndentCnt(1);
				}
			}
			if (formatConfig.getStaticKv() == null || !formatConfig.getStaticKv().matches("^[a-zA-Z_]{1}[0-9a-zA-Z_]{0,63}$")) {
				formatConfig.setStaticKv(defaultConfig.getStaticKv());
			}
			if (formatConfig.getDynamicKv() == null || !formatConfig.getDynamicKv().matches("^[a-zA-Z_]{1}[0-9a-zA-Z_]{0,63}$")) {
				formatConfig.setDynamicKv(defaultConfig.getDynamicKv());
			}
			if (formatConfig.getStaticArr() == null || !formatConfig.getStaticArr().matches("^[a-zA-Z_]{1}[0-9a-zA-Z_]{0,63}$")) {
				formatConfig.setStaticArr(defaultConfig.getStaticArr());
			}
			if (formatConfig.getDynamicArr() == null || !formatConfig.getDynamicArr().matches("^[a-zA-Z_]{1}[0-9a-zA-Z_]{0,63}$")) {
				formatConfig.setDynamicArr(defaultConfig.getDynamicArr());
			}
			return formatConfig;
		} catch (Exception e) {
			return defaultConfig;
		}
	}
	
	public static FormatConfig writeConfig (FormatConfig formatConfig) {
		File dir = new File("config");
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir, "config.json");
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
			}
		}
		if (formatConfig == null) {
			FormatConfig defaultConfig = defaultConfig();
			try {
				String str = readFileToString(file);
				if (str == null || str.isEmpty()) {
					Gson gson = new GsonBuilder().setPrettyPrinting().create();
					writeFile(file, gson.toJson(defaultConfig));
				}
				Gson gson1 = new Gson();
				FormatConfig fromJson = gson1.fromJson(str, FormatConfig.class);
				if (fromJson == null) {
					Gson gson = new GsonBuilder().setPrettyPrinting().create();
					writeFile(file, gson.toJson(defaultConfig));
				}
			} catch (IOException e) {
			}
			return defaultConfig;
		} else {
			try {
				Gson gson = new GsonBuilder().setPrettyPrinting().create();
				writeFile(file, gson.toJson(formatConfig));
			} catch (IOException e) {
			}
			return formatConfig;
		}
		
	}
	
	public static void copyProperties (FormatConfig source, FormatConfig target) {
		target.setFullPackageName(source.getFullPackageName());
		target.setStaticKv(source.getStaticKv());
		target.setDynamicKv(source.getDynamicKv());
		target.setStaticArr(source.getStaticArr());
		target.setDynamicArr(source.getDynamicArr());
		target.setIndentChar(source.getIndentChar());
		target.setIndentCnt(source.getIndentCnt());
	}
	
	public static boolean equals (FormatConfig source, FormatConfig target) {
		if (!source.getFullPackageName().equals(target.getFullPackageName())) {
			return false;
		}
		if (!source.getStaticKv().equals(target.getStaticKv())) {
			return false;
		}
		if (!source.getDynamicKv().equals(target.getDynamicKv())) {
			return false;
		}
		if (!source.getStaticArr().equals(target.getStaticArr())) {
			return false;
		}
		if (!source.getDynamicArr().equals(target.getDynamicArr())) {
			return false;
		}
		if (!source.getIndentChar().equals(target.getIndentChar())) {
			return false;
		}
		if (source.getIndentCnt().compareTo(target.getIndentCnt()) != 0) {
			return false;
		}
		return true;
	}
	
	public static void writeLastInput (String str) {
		File dir = new File("history");
		if (!dir.exists()) {
			if (str == null || str.length() == 0) {
				return;
			}
			dir.mkdirs();
		}
		File file = new File(dir, "last-input.txt");
		if (!file.exists() && (str == null || str.length() == 0)) {
			return;
		}
		try {
			writeFile(file, str);
		} catch (IOException e) {
		}
	}
	
	public static String readLastInput () {
		File dir = new File("history");
		if (!dir.exists()) {
			return "";
		}
		File file = new File(dir, "last-input.txt");
		if (!file.exists() || !file.isFile()) {
			return "";
		}
		try {
			return readFileToString(file);
		} catch (IOException e) {
			return "";
		}
	}
}

ConfigScheduledService.java

保存配置的任务

package com.fx.esjson;

import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;

public class ConfigScheduledService extends ScheduledService<Void> {
	
	private volatile FormatConfig oldConfig;
	
	private volatile FormatConfig newConfig;

	public ConfigScheduledService(FormatConfig oldConfig, FormatConfig newConfig) {
		super();
		this.oldConfig = oldConfig;
		this.newConfig = newConfig;
	}

	@Override
	protected Task<Void> createTask() {
		
		return new Task<Void>() {

			@Override
			protected Void call() throws Exception {
				if (FileUtils.equals(ConfigScheduledService.this.oldConfig, ConfigScheduledService.this.newConfig)) {
					return null;
				}
				FileUtils.copyProperties(ConfigScheduledService.this.newConfig, ConfigScheduledService.this.oldConfig);
				FileUtils.writeConfig(oldConfig);
				return null;
			}
		};
	}

}

FormatScheduledService.java

生成java代码的任务

package com.fx.esjson;

import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.scene.control.TextArea;

public class FormatScheduledService extends ScheduledService<Void> {
	
	private volatile FormatConfig oldConfig;
	
	private TextArea rightTopTextArea;
	
	private TextArea rightCenterTextArea;
	
	private volatile String[] leftTextAreaValue;
	
	private volatile FormatConfig tempFormatConfig = new FormatConfig();
	
	private volatile String oldJsonSource = "";
	
	private volatile String rightTopTextOld = "";
	
	private volatile String rightTopTextNew = "";
	
	private volatile String rightCenterText = "";
	
	private volatile boolean exception = false;

	public FormatScheduledService(FormatConfig oldConfig, TextArea rightTopTextArea,
			TextArea rightCenterTextArea, String[] leftTextAreaValue) {
		super();
		this.oldConfig = oldConfig;
		this.rightTopTextArea = rightTopTextArea;
		this.rightCenterTextArea = rightCenterTextArea;
		this.leftTextAreaValue = leftTextAreaValue;
		FileUtils.copyProperties(oldConfig, this.tempFormatConfig);
	}

	@Override
	protected Task<Void> createTask() {
		return new Task<Void>() {

			@Override
			protected Void call() throws Exception {
				FormatScheduledService.this.rightTopTextNew = CodeFormatUtils.getStaticPackage(FormatScheduledService.this.oldConfig);
				if (FileUtils.equals(FormatScheduledService.this.tempFormatConfig, FormatScheduledService.this.oldConfig)) {
					if (FormatScheduledService.this.oldJsonSource.equals(FormatScheduledService.this.leftTextAreaValue[0])) {
						return null;
					}
				} else {
					FileUtils.copyProperties(FormatScheduledService.this.oldConfig, FormatScheduledService.this.tempFormatConfig);
				}
				FormatScheduledService.this.oldJsonSource = FormatScheduledService.this.leftTextAreaValue[0];
				if (FormatScheduledService.this.oldJsonSource.length() != 0) {
					try {
						FormatScheduledService.this.rightCenterText = CodeFormatUtils.getCode(FormatScheduledService.this.oldJsonSource, FormatScheduledService.this.oldConfig);
						FormatScheduledService.this.exception = false;
					} catch (Exception e) {
						FormatScheduledService.this.exception = true;
						FormatScheduledService.this.rightCenterText = e.getMessage();
					}
				} else {
					FormatScheduledService.this.exception = false;
					FormatScheduledService.this.rightCenterText = "";
				}
				return null;
			}

			@Override
			protected void updateValue(Void value) {
				super.updateValue(value);
				if (!FormatScheduledService.this.rightTopTextNew.equals(FormatScheduledService.this.rightTopTextOld)) {
					FormatScheduledService.this.rightTopTextOld = FormatScheduledService.this.rightTopTextNew;
					FormatScheduledService.this.rightTopTextArea.setText(FormatScheduledService.this.rightTopTextOld);
				}
				String text = FormatScheduledService.this.rightCenterTextArea.getText();
				if (!FormatScheduledService.this.rightCenterText.equals(text)) {
					if (FormatScheduledService.this.exception) {
						FormatScheduledService.this.rightCenterTextArea.setWrapText(true);
						FormatScheduledService.this.rightCenterTextArea.setStyle("-fx-font-size: 1.2em;-fx-text-fill: #CC0000;");
						FormatScheduledService.this.rightCenterTextArea.setText(FormatScheduledService.this.rightCenterText);
						FormatScheduledService.this.rightCenterTextArea.deselect();
					} else {
						FormatScheduledService.this.rightCenterTextArea.setWrapText(false);
						FormatScheduledService.this.rightCenterTextArea.setStyle("-fx-font-size: 1.2em;-fx-text-fill: #202020;");
						FormatScheduledService.this.rightCenterTextArea.setText(FormatScheduledService.this.rightCenterText);
						FormatScheduledService.this.rightCenterTextArea.requestFocus();
						FormatScheduledService.this.rightCenterTextArea.selectAll();
					}
				}
			}
			
		};
	}

}

MainApplication.java

主启动类和 UI 类

package com.fx.esjson;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.HPos;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Spinner;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class MainApplication extends Application {
	
	private TextArea leftTextArea;

	public static void main(String[] args) {
		launch(MainApplication.class, args);
	}

	@Override
	public void init() throws Exception {
		FileUtils.writeConfig(null);
	}

	@Override
	public void start(Stage stage) throws Exception {
		stage.setTitle("ES报文辅助生成工具");
		stage.getIcons().add(new Image(getClass().getClassLoader().getResourceAsStream("icon/icon.png")));
		stage.setWidth(900);
		stage.setHeight(600);
		stage.setMinWidth(680);
		stage.setMinHeight(400);
		
		final FormatConfig initConfig = FileUtils.readConfig();
		final FormatConfig newConfig = new FormatConfig();
		FileUtils.copyProperties(initConfig, newConfig);
		
		final String[] leftTextAreaValue = new String[] {""};
		
		BorderPane root = new BorderPane();
		GridPane topGridPane = new GridPane();
		topGridPane.setPrefHeight(100);
		topGridPane.setStyle("-fx-background-color: #F0F0B0;");
		topGridPane.setAlignment(Pos.CENTER);
		topGridPane.setHgap(6);
		topGridPane.setVgap(6);
		
		Label packageLabel = new Label("全限定包名:");
		GridPane.setHalignment(packageLabel, HPos.RIGHT);
		topGridPane.add(packageLabel, 0, 0);
		TextField packageField = new TextField();
		packageField.setText(initConfig.getFullPackageName());
		packageField.setMinWidth(400);
		packageField.textProperty().addListener((observable, oldValue, newValue) -> {
			if (newValue != null && !newValue.matches("^[a-zA-Z0-9_\\.]{0,255}$") && !newValue.equals(oldValue)) {
				packageField.setText(oldValue);
				return;
			}
			newConfig.setFullPackageName(newValue);
		});
		topGridPane.add(packageField, 1, 0, 7, 1);
		
		Label staticKvLabel = new Label("静态键值方法名:");
		GridPane.setHalignment(staticKvLabel, HPos.RIGHT);
		topGridPane.add(staticKvLabel, 0, 1);
		TextField staticKvField = new TextField();
		staticKvField.setText(initConfig.getStaticKv());
		staticKvField.setPrefWidth(50);
		staticKvField.textProperty().addListener((observable, oldValue, newValue) -> {
			if (newValue != null && newValue.length() > 0) {
				if (!newValue.matches("[a-zA-Z_]{1}[0-9a-zA-Z_]{0,63}$") && !newValue.equals(oldValue)) {
					staticKvField.setText(oldValue);
					return;
				}
				newConfig.setStaticKv(newValue);
			}
		});
		topGridPane.add(staticKvField, 1, 1);
		
		Label dynamicKvLabel = new Label("动态键值方法名:");
		GridPane.setHalignment(dynamicKvLabel, HPos.RIGHT);
		topGridPane.add(dynamicKvLabel, 2, 1);
		TextField dynamicKvField = new TextField();
		dynamicKvField.setText(initConfig.getDynamicKv());
		dynamicKvField.setPrefWidth(50);
		dynamicKvField.textProperty().addListener((observable, oldValue, newValue) -> {
			if (newValue != null && newValue.length() > 0) {
				if (!newValue.matches("[a-zA-Z_]{1}[0-9a-zA-Z_]{0,63}$") && !newValue.equals(oldValue)) {
					dynamicKvField.setText(oldValue);
					return;
				}
				newConfig.setDynamicKv(newValue);
			}
		});
		topGridPane.add(dynamicKvField, 3, 1);
		
		Label staticArrLabel = new Label("静态数组方法名:");
		GridPane.setHalignment(staticArrLabel, HPos.RIGHT);
		topGridPane.add(staticArrLabel, 4, 1);
		TextField staticArrField = new TextField();
		staticArrField.setText(initConfig.getStaticArr());
		staticArrField.setPrefWidth(50);
		staticArrField.textProperty().addListener((observable, oldValue, newValue) -> {
			if (newValue != null && newValue.length() > 0) {
				if (!newValue.matches("[a-zA-Z_]{1}[0-9a-zA-Z_]{0,63}$") && !newValue.equals(oldValue)) {
					staticArrField.setText(oldValue);
					return;
				}
				newConfig.setStaticArr(newValue);
			}
		});
		topGridPane.add(staticArrField, 5, 1);
		
		Label dynamicArrLabel = new Label("动态数组方法名:");
		GridPane.setHalignment(dynamicArrLabel, HPos.RIGHT);
		topGridPane.add(dynamicArrLabel, 6, 1);
		TextField dynamicArrField = new TextField();
		dynamicArrField.setText(initConfig.getDynamicArr());
		dynamicArrField.setPrefWidth(50);
		dynamicArrField.textProperty().addListener((observable, oldValue, newValue) -> {
			if (newValue != null && newValue.length() > 0) {
				if (!newValue.matches("[a-zA-Z_]{1}[0-9a-zA-Z_]{0,63}$") && !newValue.equals(oldValue)) {
					dynamicArrField.setText(oldValue);
					return;
				}
				newConfig.setDynamicArr(newValue);
			}
		});
		topGridPane.add(dynamicArrField, 7, 1);
		
		Label indentCntLabel = new Label("缩进次数:");
		GridPane.setHalignment(indentCntLabel, HPos.RIGHT);
		topGridPane.add(indentCntLabel, 0, 2);
		
		Spinner<Integer> indentCntSpinner = new Spinner<>(0, 8, initConfig.getIndentCnt());
		indentCntSpinner.setPrefWidth(50);
		indentCntSpinner.setEditable(false);
		indentCntSpinner.valueProperty().addListener((observable, oldValue, newValue) -> {
			newConfig.setIndentCnt(newValue);
		});
		topGridPane.add(indentCntSpinner, 1, 2);
		
		Label indentCharLabel = new Label("缩进字符:");
		GridPane.setHalignment(indentCharLabel, HPos.RIGHT);
		topGridPane.add(indentCharLabel, 2, 2);
		
		ToggleGroup tg = new ToggleGroup();
		RadioButton spaceRadioButton = new RadioButton("SPACE");
		spaceRadioButton.setToggleGroup(tg);
		RadioButton tabRadioButton = new RadioButton("TAB");
		tabRadioButton.setToggleGroup(tg);
		if ("\t".equals(initConfig.getIndentChar())) {
			tg.selectToggle(tabRadioButton);
		} else {
			tg.selectToggle(spaceRadioButton);
		}
		tg.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
			if (newValue == tabRadioButton) {
				newConfig.setIndentChar("\t");
			} else {
				newConfig.setIndentChar(" ");
			}
		});
		topGridPane.add(spaceRadioButton, 3, 2);
		topGridPane.add(tabRadioButton, 4, 2);
		
		root.setTop(topGridPane);
		
		SplitPane centerSplitPane = new SplitPane();
		
		TextArea leftTextArea = new TextArea();
		leftTextArea.setMinWidth(160);
		leftTextArea.setPromptText("请在此输入 json 本文...");
		leftTextArea.setFocusTraversable(false);
		leftTextArea.setStyle("-fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);-fx-font-size: 1.2em;-fx-text-fill: #202020;");
		Platform.runLater(() -> leftTextArea.requestFocus());
		leftTextArea.textProperty().addListener((observable, oldValue, newValue) -> {
			leftTextAreaValue[0] = newValue == null ? "" : newValue.trim();
		});
		this.leftTextArea = leftTextArea;
		
		SplitPane rightSplitPane = new SplitPane();
		rightSplitPane.setOrientation(Orientation.VERTICAL);
		rightSplitPane.setMinWidth(160);
		
		TextArea rightTopTextArea = new TextArea();
		rightTopTextArea.setMinHeight(0);
		rightTopTextArea.setMaxHeight(80);
		rightTopTextArea.setEditable(false);
		rightTopTextArea.setStyle("-fx-font-size: 1.2em;-fx-text-fill: #202020;");
		TextArea rightCenterTextArea = new TextArea();
		rightCenterTextArea.setEditable(false);
		rightCenterTextArea.setStyle("-fx-font-size: 1.2em;-fx-text-fill: #202020;");
		rightSplitPane.getItems().addAll(rightTopTextArea, rightCenterTextArea);
		
		
		centerSplitPane.getItems().addAll(leftTextArea, rightSplitPane);
		
		root.setCenter(centerSplitPane);
		
		Scene scene = new Scene(root);
		stage.setScene(scene);
		stage.show();
		
		leftTextArea.setText(FileUtils.readLastInput());
		leftTextArea.appendText("");
		
		ConfigScheduledService configScheduledService = new ConfigScheduledService(initConfig, newConfig);
		configScheduledService.setDelay(Duration.seconds(2));
		configScheduledService.setPeriod(Duration.seconds(1.5));
		configScheduledService.setRestartOnFailure(true);
		configScheduledService.setMaximumFailureCount(3);
		configScheduledService.start();
		
		FormatScheduledService formatScheduledService = new FormatScheduledService(initConfig, rightTopTextArea, rightCenterTextArea, leftTextAreaValue);
		formatScheduledService.setDelay(Duration.seconds(1));
		formatScheduledService.setPeriod(Duration.seconds(1.5));
		formatScheduledService.setRestartOnFailure(true);
		formatScheduledService.setMaximumFailureCount(3);
		formatScheduledService.start();
	}

	@Override
	public void stop() throws Exception {
		super.stop();
		if (leftTextArea != null) {
			String text = leftTextArea.getText();
			FileUtils.writeLastInput(text);
		}
	}

}

打包

在工具根目录,执行以下 cmd mvn 命令,即可在根目录下生成 target/jfx/ 打包后的程序

mvn jfx:native
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值