提交 b75a6a7b 编写于 作者: NoSubject's avatar NoSubject

Merge remote-tracking branch 'origin/develop' into develop

...@@ -475,6 +475,10 @@ public class Query extends ConfigObject { ...@@ -475,6 +475,10 @@ public class Query extends ConfigObject {
} }
} }
public String getHdfsDirectoryPath() {
return this.adjustHdfsDirectoryPath();
}
private String adjustHdfsDirectoryPath() { private String adjustHdfsDirectoryPath() {
return StringUtils.startsWith(this.hdfsDirectoryPath, "/") ? this.hdfsDirectoryPath return StringUtils.startsWith(this.hdfsDirectoryPath, "/") ? this.hdfsDirectoryPath
: "/" + hdfsDirectoryPath; : "/" + hdfsDirectoryPath;
......
...@@ -25,6 +25,7 @@ import java.util.Map.Entry; ...@@ -25,6 +25,7 @@ import java.util.Map.Entry;
import java.util.Objects; import java.util.Objects;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.google.gson.Gson; import com.google.gson.Gson;
...@@ -36,31 +37,31 @@ import com.x.base.core.project.logger.Logger; ...@@ -36,31 +37,31 @@ import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory; import com.x.base.core.project.logger.LoggerFactory;
public class BaseTools { public class BaseTools {
private static Logger logger = LoggerFactory.getLogger(BaseTools.class); private static Logger logger = LoggerFactory.getLogger(BaseTools.class);
public static String getBasePath() throws IOException, URISyntaxException { public static String getBasePath() throws IOException, URISyntaxException {
return getBaseDirectory().toAbsolutePath().toString(); return getBaseDirectory().toAbsolutePath().toString();
} }
/** /**
* 从Main.class所在的目录开始递归向上,找到version.o2所在目录,就是程序根目录. * 从Main.class所在的目录开始递归向上,找到version.o2所在目录,就是程序根目录.
* *
* @return * @return
* @throws IOException * @throws IOException
* @throws URISyntaxException * @throws URISyntaxException
*/ */
private static Path getBaseDirectory() throws IOException, URISyntaxException { private static Path getBaseDirectory() throws IOException, URISyntaxException {
Path path = Paths.get( Path path = Paths.get(
new URI("file://" + BaseTools.class.getProtectionDomain().getCodeSource().getLocation().getPath())); new URI("file://" + BaseTools.class.getProtectionDomain().getCodeSource().getLocation().getPath()));
while (Files.exists(path)) { while (Files.exists(path)) {
Path versionFile = path.resolve("version.o2"); Path versionFile = path.resolve("version.o2");
if (Files.exists(versionFile) && Files.isRegularFile(versionFile)) { if (Files.exists(versionFile) && Files.isRegularFile(versionFile)) {
return path.toAbsolutePath(); return path.toAbsolutePath();
} }
path = path.getParent(); path = path.getParent();
} }
throw new IOException("can not define o2server base directory."); throw new IOException("can not define o2server base directory.");
} }
// public static File getBaseDirectory() throws Exception { // public static File getBaseDirectory() throws Exception {
// String path = BaseTools.class.getProtectionDomain().getCodeSource().getLocation().getPath(); // String path = BaseTools.class.getProtectionDomain().getCodeSource().getLocation().getPath();
...@@ -78,192 +79,192 @@ public class BaseTools { ...@@ -78,192 +79,192 @@ public class BaseTools {
// throw new Exception("can not define o2server base directory."); // throw new Exception("can not define o2server base directory.");
// } // }
public static <T> T readConfigObject(String path, Class<T> cls) throws Exception { public static <T> T readConfigObject(String path, Class<T> cls) throws Exception {
String base = BaseTools.getBasePath(); String base = BaseTools.getBasePath();
File file = new File(base, path); File file = new File(base, path);
if ((!file.exists()) || file.isDirectory()) { if ((!file.exists()) || file.isDirectory()) {
return null; return null;
} }
String json = FileUtils.readFileToString(file, DefaultCharset.charset); String json = FileUtils.readFileToString(file, DefaultCharset.charset);
Gson gson = new Gson(); Gson gson = new Gson();
JsonElement jsonElement = gson.fromJson(json, JsonElement.class); JsonElement jsonElement = gson.fromJson(json, JsonElement.class);
if ((null != jsonElement) && jsonElement.isJsonObject()) { if ((null != jsonElement) && jsonElement.isJsonObject()) {
LinkedHashMap<Object, Object> map = new LinkedHashMap<>(); LinkedHashMap<Object, Object> map = new LinkedHashMap<>();
map = new Gson().fromJson(jsonElement, map.getClass()); map = new Gson().fromJson(jsonElement, map.getClass());
removeComment(map); removeComment(map);
jsonElement = gson.toJsonTree(map); jsonElement = gson.toJsonTree(map);
} }
return gson.fromJson(jsonElement, cls); return gson.fromJson(jsonElement, cls);
} }
private static void removeComment(Map<Object, Object> map) { private static void removeComment(Map<Object, Object> map) {
List<Entry<Object, Object>> entries = new ArrayList<>(); List<Entry<Object, Object>> entries = new ArrayList<>();
for (Entry<Object, Object> entry : map.entrySet()) { for (Entry<Object, Object> entry : map.entrySet()) {
if (StringUtils.startsWith(Objects.toString(entry.getKey()), "###")) { if (StringUtils.startsWith(Objects.toString(entry.getKey()), "###")) {
entries.add(entry); entries.add(entry);
continue; continue;
} else { } else {
if (entry.getValue() instanceof Map) { if (entry.getValue() instanceof Map) {
removeComment((Map<Object, Object>) entry.getValue()); removeComment((Map<Object, Object>) entry.getValue());
} }
} }
} }
for (Entry<Object, Object> entry : entries) { for (Entry<Object, Object> entry : entries) {
map.remove(entry.getKey()); map.remove(entry.getKey());
} }
} }
public static <T> T readConfigObject(String path, String otherPath, Class<T> cls) throws Exception { public static <T> T readConfigObject(String path, String otherPath, Class<T> cls) throws Exception {
String base = BaseTools.getBasePath(); String base = BaseTools.getBasePath();
File file = new File(base, path); File file = new File(base, path);
if (file.exists() && file.isFile()) { if (file.exists() && file.isFile()) {
return readConfigObject(path, cls); return readConfigObject(path, cls);
} }
file = new File(base, otherPath); file = new File(base, otherPath);
if (file.exists() && file.isFile()) { if (file.exists() && file.isFile()) {
return readConfigObject(otherPath, cls); return readConfigObject(otherPath, cls);
} }
throw new Exception("can not get file with path:" + path + ", otherPath:" + otherPath + "."); throw new Exception("can not get file with path:" + path + ", otherPath:" + otherPath + ".");
} }
public static void writeObject(String path, Object obj) throws Exception { public static void writeObject(String path, Object obj) throws Exception {
String base = BaseTools.getBasePath(); String base = BaseTools.getBasePath();
File file = new File(base, path); File file = new File(base, path);
String json = (new Gson()).toJson(obj); String json = (new Gson()).toJson(obj);
FileUtils.writeStringToFile(file, json, DefaultCharset.charset); FileUtils.writeStringToFile(file, json, DefaultCharset.charset);
} }
public static String readCfg(String path) throws Exception { public static String readCfg(String path) throws Exception {
String base = BaseTools.getBasePath(); String base = BaseTools.getBasePath();
File file = new File(base, path); File file = new File(base, path);
if ((!file.exists()) || file.isDirectory()) { if ((!file.exists()) || file.isDirectory()) {
return null; return null;
} }
String str = FileUtils.readFileToString(file, DefaultCharset.charset); String str = FileUtils.readFileToString(file, DefaultCharset.charset);
return (StringUtils.trim(str)); return (StringUtils.trim(str));
} }
public static String readCfg(String path, String defaultValue) throws Exception { public static String readCfg(String path, String defaultValue) throws Exception {
String str = readCfg(path); String str = readCfg(path);
if (StringUtils.isEmpty(str)) { if (StringUtils.isEmpty(str)) {
str = defaultValue; str = defaultValue;
} }
return (StringUtils.trim(str)); return (StringUtils.trim(str));
} }
public static void writeCfg(String path, String value) throws Exception { public static void writeCfg(String path, String value) throws Exception {
String base = BaseTools.getBasePath(); String base = BaseTools.getBasePath();
File file = new File(base, path); File file = new File(base, path);
FileUtils.writeStringToFile(file, StringUtils.trim(value), DefaultCharset.charset); FileUtils.writeStringToFile(file, StringUtils.trim(value), DefaultCharset.charset);
} }
public static byte[] readBytes(String path) throws IOException, URISyntaxException { public static byte[] readBytes(String path) throws IOException, URISyntaxException {
String base = BaseTools.getBasePath(); String base = BaseTools.getBasePath();
File file = new File(base, path); File file = new File(base, path);
if ((!file.exists()) || file.isDirectory()) { if ((!file.exists()) || file.isDirectory()) {
throw new IOException("can not get file with path:" + file.getAbsolutePath()); throw new IOException("can not get file with path:" + file.getAbsolutePath());
} }
return FileUtils.readFileToByteArray(file); return FileUtils.readFileToByteArray(file);
} }
public static String readString(String path) throws IOException, URISyntaxException { public static String readString(String path) throws IOException, URISyntaxException {
String base = BaseTools.getBasePath(); String base = BaseTools.getBasePath();
File file = new File(base, path); File file = new File(base, path);
if ((!file.exists()) || file.isDirectory()) { if ((!file.exists()) || file.isDirectory()) {
return null; return null;
} }
return FileUtils.readFileToString(file, DefaultCharset.charset); return FileUtils.readFileToString(file, DefaultCharset.charset);
} }
public static boolean executeSyncFile(String syncFilePath) throws Exception { public static boolean executeSyncFile(String syncFilePath) throws Exception {
boolean Syncflag = false; boolean Syncflag = false;
Nodes nodes = Config.nodes(); Nodes nodes = Config.nodes();
// 同步config文件 // 同步config文件
if (Config.general().getConfigApiEnable()) { if (BooleanUtils.isTrue(Config.general().getConfigApiEnable())) {
for (String node : nodes.keySet()) { for (String node : nodes.keySet()) {
if (nodes.get(node).getApplication().getEnable() || nodes.get(node).getCenter().getEnable()) { if (nodes.get(node).getApplication().getEnable() || nodes.get(node).getCenter().getEnable()) {
Syncflag = executeSyncFile(syncFilePath, node, nodes.get(node).nodeAgentPort()); Syncflag = executeSyncFile(syncFilePath, node, nodes.get(node).nodeAgentPort());
} }
} }
} }
return Syncflag; return Syncflag;
} }
private static boolean executeSyncFile(String syncFilePath, String nodeName, int nodePort) { private static boolean executeSyncFile(String syncFilePath, String nodeName, int nodePort) {
boolean syncFileFlag = false; boolean syncFileFlag = false;
File syncFile; File syncFile;
InputStream fileInputStream = null; InputStream fileInputStream = null;
try (Socket socket = new Socket(nodeName, nodePort)) { try (Socket socket = new Socket(nodeName, nodePort)) {
syncFile = new File(Config.base(), syncFilePath); syncFile = new File(Config.base(), syncFilePath);
fileInputStream = new FileInputStream(syncFile); fileInputStream = new FileInputStream(syncFile);
socket.setKeepAlive(true); socket.setKeepAlive(true);
socket.setSoTimeout(2000); socket.setSoTimeout(2000);
DataOutputStream dos = null; DataOutputStream dos = null;
DataInputStream dis = null; DataInputStream dis = null;
try { try {
dos = new DataOutputStream(socket.getOutputStream()); dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream()); dis = new DataInputStream(socket.getInputStream());
Map<String, Object> commandObject = new HashMap<>(); Map<String, Object> commandObject = new HashMap<>();
commandObject.put("command", "syncFile:" + syncFilePath); commandObject.put("command", "syncFile:" + syncFilePath);
commandObject.put("credential", Crypto.rsaEncrypt("o2@", Config.publicKey())); commandObject.put("credential", Crypto.rsaEncrypt("o2@", Config.publicKey()));
dos.writeUTF(XGsonBuilder.toJson(commandObject)); dos.writeUTF(XGsonBuilder.toJson(commandObject));
dos.flush(); dos.flush();
dos.writeUTF(syncFilePath); dos.writeUTF(syncFilePath);
dos.flush(); dos.flush();
logger.info("同步文件:" + syncFilePath + " starting..."); logger.info("同步文件:" + syncFilePath + " starting...");
byte[] bytes = new byte[1024]; byte[] bytes = new byte[1024];
int length = 0; int length = 0;
while ((length = fileInputStream.read(bytes, 0, bytes.length)) != -1) { while ((length = fileInputStream.read(bytes, 0, bytes.length)) != -1) {
dos.write(bytes, 0, length); dos.write(bytes, 0, length);
dos.flush(); dos.flush();
} }
logger.info("同步文件:" + syncFilePath + "end."); logger.info("同步文件:" + syncFilePath + " end.");
} finally { } finally {
dos.close(); dos.close();
dis.close(); dis.close();
socket.close(); socket.close();
fileInputStream.close(); fileInputStream.close();
} }
syncFileFlag = true; syncFileFlag = true;
} catch (Exception ex) { } catch (Exception ex) {
logger.error(ex); logger.error(ex);
syncFileFlag = false; syncFileFlag = false;
} }
return syncFileFlag; return syncFileFlag;
} }
public static String getIpAddress() { public static String getIpAddress() {
try { try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces(); Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null; InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) { while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) { if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue; continue;
} else { } else {
Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) { while (addresses.hasMoreElements()) {
ip = addresses.nextElement(); ip = addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) { if (ip != null && ip instanceof Inet4Address) {
return ip.getHostAddress(); return ip.getHostAddress();
} }
} }
} }
} }
} catch (Exception e) { } catch (Exception e) {
System.err.println("IP地址获取失败" + e.toString()); System.err.println("IP地址获取失败" + e.toString());
} }
return ""; return "";
} }
} }
...@@ -32,7 +32,6 @@ import java.util.regex.Matcher; ...@@ -32,7 +32,6 @@ import java.util.regex.Matcher;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.quartz.Scheduler;
import com.x.base.core.project.config.ApplicationServer; import com.x.base.core.project.config.ApplicationServer;
import com.x.base.core.project.config.CenterServer; import com.x.base.core.project.config.CenterServer;
...@@ -44,7 +43,6 @@ import com.x.base.core.project.gson.XGsonBuilder; ...@@ -44,7 +43,6 @@ import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.tools.Crypto; import com.x.base.core.project.tools.Crypto;
import com.x.base.core.project.tools.DefaultCharset; import com.x.base.core.project.tools.DefaultCharset;
import com.x.base.core.project.tools.StringTools; import com.x.base.core.project.tools.StringTools;
import com.x.server.console.action.ActionConfig;
import com.x.server.console.action.ActionControl; import com.x.server.console.action.ActionControl;
import com.x.server.console.action.ActionSetPassword; import com.x.server.console.action.ActionSetPassword;
import com.x.server.console.action.ActionVersion; import com.x.server.console.action.ActionVersion;
...@@ -123,7 +121,7 @@ public class Main { ...@@ -123,7 +121,7 @@ public class Main {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
init(); init();
if (null == Config.currentNode()) { if (null == Config.currentNode()) {
throw new Exception("无法找到当前节点,请检查config/node_{name}.json与local/node.cfg文件内容中的名称是否一致."); throw new IllegalStateException("无法找到当前节点,请检查config/node_{name}.json与local/node.cfg文件内容中的名称是否一致.");
} }
swapCommandThread.start(); swapCommandThread.start();
consoleCommandThread.start(); consoleCommandThread.start();
...@@ -134,8 +132,8 @@ public class Main { ...@@ -134,8 +132,8 @@ public class Main {
nodeAgent.start(); nodeAgent.start();
} }
SchedulerBuilder schedulerBuilder = new SchedulerBuilder(); // SchedulerBuilder schedulerBuilder = new SchedulerBuilder();
Scheduler scheduler = schedulerBuilder.start(); // Scheduler scheduler = schedulerBuilder.start();
if (BooleanUtils.isTrue(Config.currentNode().autoStart())) { if (BooleanUtils.isTrue(Config.currentNode().autoStart())) {
startAll(); startAll();
...@@ -217,11 +215,7 @@ public class Main { ...@@ -217,11 +215,7 @@ public class Main {
matcher = CommandFactory.setPassword_pattern.matcher(cmd); matcher = CommandFactory.setPassword_pattern.matcher(cmd);
if (matcher.find()) { if (matcher.find()) {
setPassword(matcher.group(1), matcher.group(2)); setPassword(matcher.group(1), matcher.group(2));
if (config()) { continue;
break;
} else {
continue;
}
} }
matcher = CommandFactory.control_pattern.matcher(cmd); matcher = CommandFactory.control_pattern.matcher(cmd);
...@@ -242,9 +236,6 @@ public class Main { ...@@ -242,9 +236,6 @@ public class Main {
} }
System.out.println("unknown command:" + cmd); System.out.println("unknown command:" + cmd);
} }
// 关闭定时器
scheduler.shutdown();
// SystemOutErrorSideCopyBuilder.stop();
} }
private static void version() { private static void version() {
...@@ -255,15 +246,6 @@ public class Main { ...@@ -255,15 +246,6 @@ public class Main {
} }
} }
private static boolean config() {
try {
return new ActionConfig().execute();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
private static void startDataServer() { private static void startDataServer() {
try { try {
if (BooleanUtils.isTrue(Servers.dataServerIsRunning())) { if (BooleanUtils.isTrue(Servers.dataServerIsRunning())) {
......
package com.x.server.console.action;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.http.HttpMediaType;
import com.x.base.core.project.tools.JarTools;
public class ActionConfig extends ActionBase {
public boolean execute() throws Exception {
if (StringUtils.equalsIgnoreCase(Config.node(), Config.resource_node_centersPirmaryNode())) {
byte[] bytes = this.getZip();
this.unzip(bytes);
System.out.println("synchronize config success, should to restart server.");
return true;
} else {
System.out.println("config command only synchronize config from primary center.");
return false;
}
}
@SuppressWarnings("deprecation")
private byte[] getZip() throws Exception {
String address = Config.url_x_program_center_jaxrs("config");
URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", HttpMediaType.APPLICATION_JSON_UTF_8);
EffectivePerson effectivePerson = EffectivePerson.cipher(Config.token().getCipher(),
Config.person().getEncryptType());
connection.setRequestProperty(Config.person().getTokenName(), effectivePerson.getToken());
connection.setRequestMethod("GET");
connection.setDoOutput(false);
connection.setDoInput(true);
connection.connect();
String json = null;
try (InputStream input = connection.getInputStream()) {
json = IOUtils.toString(input);
}
JsonElement jsonElement = XGsonBuilder.instance().fromJson(json, JsonElement.class);
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (jsonObject.has("type")) {
if (StringUtils.equals("success", jsonObject.get("type").getAsString())) {
String value = jsonObject.get("data").getAsString();
byte[] bytes = Base64.decodeBase64(value);
return bytes;
} else {
throw new Exception("return type not success.");
}
} else {
throw new Exception("can not read return type.");
}
} else {
throw new Exception("return object is not jsonObject.");
}
}
private void unzip(byte[] bytes) throws Exception {
File dir = new File(Config.base(), "config");
FileUtils.forceMkdir(dir);
JarTools.unjar(bytes, "", dir, true);
}
}
\ No newline at end of file
...@@ -14,40 +14,41 @@ import com.x.base.core.project.config.DataServer; ...@@ -14,40 +14,41 @@ import com.x.base.core.project.config.DataServer;
import com.x.base.core.project.config.Token; import com.x.base.core.project.config.Token;
import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory; import com.x.base.core.project.logger.LoggerFactory;
import com.x.server.console.server.Servers;
public class ActionSetPassword extends ActionBase { public class ActionSetPassword extends ActionBase {
private static Logger logger = LoggerFactory.getLogger(ActionSetPassword.class); private static final Logger LOGGER = LoggerFactory.getLogger(ActionSetPassword.class);
public boolean execute(String oldPassword, String newPassword) throws Exception { public boolean execute(String oldPassword, String newPassword) throws Exception {
/** 如果初始密码没有修改就设置为初始密码 */ /** 如果初始密码没有修改就设置为初始密码 */
if (StringUtils.equals(Config.token().getPassword(), Token.initPassword)) { if (StringUtils.equals(Config.token().getPassword(), Token.initPassword)) {
oldPassword = Token.initPassword; oldPassword = Token.initPassword;
} }
if (!StringUtils.equals(Config.token().getPassword(), oldPassword)) { if (!StringUtils.equals(Config.token().getPassword(), oldPassword)) {
logger.print("old password not match."); LOGGER.print("old password not match.");
return false; return false;
} }
this.changeInternalDataServerPassword(oldPassword, newPassword); this.changeInternalDataServerPassword(oldPassword, newPassword);
Config.token().setPassword(newPassword); Config.token().setPassword(newPassword);
Config.token().save(); Config.token().save();
logger.print("The initial manager password has been modified."); LOGGER.print("The initial manager password has been modified.");
return true; return true;
} }
private void changeInternalDataServerPassword(String oldPassword, String newPassword) throws Exception { private void changeInternalDataServerPassword(String oldPassword, String newPassword) throws Exception {
org.h2.Driver.load(); org.h2.Driver.load();
for (Entry<String, DataServer> en : Config.nodes().dataServers().entrySet()) { for (Entry<String, DataServer> en : Config.nodes().dataServers().entrySet()) {
DataServer o = en.getValue(); DataServer o = en.getValue();
if (BooleanUtils.isTrue(o.getEnable())) { if (BooleanUtils.isTrue(o.getEnable()) && (!Config.externalDataSources().enable())) {
try (Connection conn = DriverManager.getConnection( try (Connection conn = DriverManager.getConnection(
"jdbc:h2:tcp://" + en.getKey() + ":" + o.getTcpPort() + "/X", "sa", oldPassword)) { "jdbc:h2:tcp://" + en.getKey() + ":" + o.getTcpPort() + "/X", "sa", oldPassword)) {
RunScript.execute(conn, new StringReader("ALTER USER SA SET PASSWORD '" + newPassword + "'")); RunScript.execute(conn, new StringReader("ALTER USER SA SET PASSWORD '" + newPassword + "'"));
} catch (Exception e) { } catch (Exception e) {
throw new IllegalStateException("Verify that the dataServer:" + en.getKey() throw new IllegalStateException("Verify that the dataServer:" + en.getKey()
+ " is started and that the dataServer password is updated synchronously.", e); + " is started and that the dataServer password is updated synchronously.", e);
} }
} }
} }
} }
} }
...@@ -25,167 +25,167 @@ import io.swagger.v3.oas.annotations.media.Schema; ...@@ -25,167 +25,167 @@ import io.swagger.v3.oas.annotations.media.Schema;
class ActionChangePassword extends BaseAction { class ActionChangePassword extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionChangePassword.class); private static final Logger LOGGER = LoggerFactory.getLogger(ActionChangePassword.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception { ActionResult<Wo> execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName); LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ActionResult<Wo> result = new ActionResult<>(); ActionResult<Wo> result = new ActionResult<>();
Wi wi = this.convertToWrapIn(jsonElement, Wi.class); Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
if (BooleanUtils.isNotTrue(Config.general().getConfigApiEnable())) { if (BooleanUtils.isNotTrue(Config.general().getConfigApiEnable())) {
throw new ExceptionModifyConfig(); throw new ExceptionModifyConfig();
} }
check(wi); check(wi);
String oldPassword = password(wi.getOldPassword()); String oldPassword = password(wi.getOldPassword());
String newPassword = password(wi.getNewPassword()); String newPassword = password(wi.getNewPassword());
checkPasswordComplexity(wi.getCredential(), newPassword); checkPasswordComplexity(wi.getCredential(), newPassword);
if (Config.ternaryManagement().isAuditManager(wi.getCredential())) { if (Config.ternaryManagement().isAuditManager(wi.getCredential())) {
changeAuditManagerPassword(effectivePerson, wi.getCredential(), oldPassword, newPassword); changeAuditManagerPassword(effectivePerson, wi.getCredential(), oldPassword, newPassword);
} else if (Config.ternaryManagement().isSecurityManager(wi.getCredential())) { } else if (Config.ternaryManagement().isSecurityManager(wi.getCredential())) {
changeSecurityManager(effectivePerson, wi.getCredential(), oldPassword, newPassword); changeSecurityManager(effectivePerson, wi.getCredential(), oldPassword, newPassword);
} else if (Config.ternaryManagement().isSystemManager(wi.getCredential())) { } else if (Config.ternaryManagement().isSystemManager(wi.getCredential())) {
changeSystemManager(effectivePerson, wi.getCredential(), oldPassword, newPassword); changeSystemManager(effectivePerson, wi.getCredential(), oldPassword, newPassword);
} else if (StringUtils.equals(wi.getCredential(), Config.token().getInitialManager())) { } else if (StringUtils.equals(wi.getCredential(), Config.token().getInitialManager())) {
changeInitialManager(effectivePerson, oldPassword, newPassword); changeInitialManager(effectivePerson, oldPassword, newPassword);
} else { } else {
throw new ExceptionInvalidCredential(); throw new ExceptionInvalidCredential();
} }
Wo wo = new Wo(); Wo wo = new Wo();
wo.setValue(true); wo.setValue(true);
result.setData(wo); result.setData(wo);
return result; return result;
} }
private void changeAuditManagerPassword(EffectivePerson effectivePerson, String credential, String oldPassword, private void changeAuditManagerPassword(EffectivePerson effectivePerson, String credential, String oldPassword,
String newPassword) throws Exception { String newPassword) throws Exception {
if (BooleanUtils.isNotTrue(Config.ternaryManagement().verifyPassword(credential, oldPassword))) { if (BooleanUtils.isNotTrue(Config.ternaryManagement().verifyPassword(credential, oldPassword))) {
throw new ExceptionInvalidOldPassword(); throw new ExceptionInvalidOldPassword();
} }
Config.ternaryManagement().setAuditManagerPassword(newPassword); Config.ternaryManagement().setAuditManagerPassword(newPassword);
Config.ternaryManagement().save(); Config.ternaryManagement().save();
this.configFlush(effectivePerson); this.configFlush(effectivePerson);
} }
private void changeSecurityManager(EffectivePerson effectivePerson, String credential, String oldPassword, private void changeSecurityManager(EffectivePerson effectivePerson, String credential, String oldPassword,
String newPassword) throws Exception { String newPassword) throws Exception {
if (BooleanUtils.isNotTrue(Config.ternaryManagement().verifyPassword(credential, oldPassword))) { if (BooleanUtils.isNotTrue(Config.ternaryManagement().verifyPassword(credential, oldPassword))) {
throw new ExceptionInvalidOldPassword(); throw new ExceptionInvalidOldPassword();
} }
Config.ternaryManagement().setSecurityManagerPassword(newPassword); Config.ternaryManagement().setSecurityManagerPassword(newPassword);
Config.ternaryManagement().save(); Config.ternaryManagement().save();
this.configFlush(effectivePerson); this.configFlush(effectivePerson);
} }
private void changeSystemManager(EffectivePerson effectivePerson, String credential, String oldPassword, private void changeSystemManager(EffectivePerson effectivePerson, String credential, String oldPassword,
String newPassword) throws Exception { String newPassword) throws Exception {
if (BooleanUtils.isNotTrue(Config.ternaryManagement().verifyPassword(credential, oldPassword))) { if (BooleanUtils.isNotTrue(Config.ternaryManagement().verifyPassword(credential, oldPassword))) {
throw new ExceptionInvalidOldPassword(); throw new ExceptionInvalidOldPassword();
} }
Config.ternaryManagement().setSystemManagerPassword(newPassword); Config.ternaryManagement().setSystemManagerPassword(newPassword);
Config.ternaryManagement().save(); Config.ternaryManagement().save();
this.configFlush(effectivePerson); this.configFlush(effectivePerson);
} }
private void changeInitialManager(EffectivePerson effectivePerson, String oldPassword, String newPassword) private void changeInitialManager(EffectivePerson effectivePerson, String oldPassword, String newPassword)
throws Exception { throws Exception {
if (BooleanUtils.isNotTrue(StringUtils.equals(Config.token().getPassword(), oldPassword))) { if (BooleanUtils.isNotTrue(StringUtils.equals(Config.token().getPassword(), oldPassword))) {
throw new ExceptionInvalidOldPassword(); throw new ExceptionInvalidOldPassword();
} }
this.changeInternalDataServerPassword(oldPassword, newPassword); this.changeInternalDataServerPassword(oldPassword, newPassword);
Config.token().setPassword(newPassword); Config.token().setPassword(newPassword);
Config.token().save(); Config.token().save();
this.configFlush(effectivePerson); this.configFlush(effectivePerson);
} }
private void changeInternalDataServerPassword(String oldPassword, String newPassword) throws Exception { private void changeInternalDataServerPassword(String oldPassword, String newPassword) throws Exception {
org.h2.Driver.load(); org.h2.Driver.load();
for (Entry<String, DataServer> en : Config.nodes().dataServers().entrySet()) { for (Entry<String, DataServer> en : Config.nodes().dataServers().entrySet()) {
DataServer o = en.getValue(); DataServer o = en.getValue();
if (BooleanUtils.isTrue(o.getEnable())) { if (BooleanUtils.isTrue(o.getEnable()) && (!Config.externalDataSources().enable())) {
try (Connection conn = DriverManager.getConnection( try (Connection conn = DriverManager.getConnection(
"jdbc:h2:tcp://" + en.getKey() + ":" + o.getTcpPort() + "/X", "sa", oldPassword)) { "jdbc:h2:tcp://" + en.getKey() + ":" + o.getTcpPort() + "/X", "sa", oldPassword)) {
RunScript.execute(conn, new StringReader("ALTER USER SA SET PASSWORD '" + newPassword + "'")); RunScript.execute(conn, new StringReader("ALTER USER SA SET PASSWORD '" + newPassword + "'"));
} catch (Exception e) { } catch (Exception e) {
throw new IllegalStateException("Verify that the dataServer:" + en.getKey() throw new IllegalStateException("Verify that the dataServer:" + en.getKey()
+ " is started and that the dataServer password is updated synchronously.", e); + " is started and that the dataServer password is updated synchronously.", e);
} }
} }
} }
} }
private void check(Wi wi) throws ExceptionEmptyCredential, ExceptionEmptyOldPassword, ExceptionEmptyNewPassword { private void check(Wi wi) throws ExceptionEmptyCredential, ExceptionEmptyOldPassword, ExceptionEmptyNewPassword {
if (StringUtils.isEmpty(wi.getCredential())) { if (StringUtils.isEmpty(wi.getCredential())) {
throw new ExceptionEmptyCredential(); throw new ExceptionEmptyCredential();
} }
if (StringUtils.isEmpty(wi.getOldPassword())) { if (StringUtils.isEmpty(wi.getOldPassword())) {
throw new ExceptionEmptyOldPassword(); throw new ExceptionEmptyOldPassword();
} }
if (StringUtils.isEmpty(wi.getCredential())) { if (StringUtils.isEmpty(wi.getCredential())) {
throw new ExceptionEmptyNewPassword(); throw new ExceptionEmptyNewPassword();
} }
} }
private void checkPasswordComplexity(String credential, String newPassword) throws Exception { private void checkPasswordComplexity(String credential, String newPassword) throws Exception {
if (!newPassword.matches(Config.person().getPasswordRegex())) { if (!newPassword.matches(Config.person().getPasswordRegex())) {
throw new ExceptionInvalidPassword(credential, Config.person().getPasswordRegexHint()); throw new ExceptionInvalidPassword(credential, Config.person().getPasswordRegexHint());
} }
} }
protected String password(String text) throws Exception { protected String password(String text) throws Exception {
return BooleanUtils.isTrue(Config.token().getRsaEnable()) ? Crypto.rsaDecrypt(text, Config.privateKey()) : text; return BooleanUtils.isTrue(Config.token().getRsaEnable()) ? Crypto.rsaDecrypt(text, Config.privateKey()) : text;
} }
@Schema(name = "com.x.program.center.jaxrs.config.ActionChangePassword$Wo") @Schema(name = "com.x.program.center.jaxrs.config.ActionChangePassword$Wo")
public static class Wo extends WrapBoolean { public static class Wo extends WrapBoolean {
private static final long serialVersionUID = -6564786947838509994L; private static final long serialVersionUID = -6564786947838509994L;
} }
@Schema(name = "com.x.program.center.jaxrs.config.ActionChangePassword$Wi") @Schema(name = "com.x.program.center.jaxrs.config.ActionChangePassword$Wi")
public static class Wi extends GsonPropertyObject { public static class Wi extends GsonPropertyObject {
private static final long serialVersionUID = -8627814779546541124L; private static final long serialVersionUID = -8627814779546541124L;
@FieldDescribe("用户标识.") @FieldDescribe("用户标识.")
@Schema(description = "用户标识.") @Schema(description = "用户标识.")
private String credential; private String credential;
@FieldDescribe("原密码.") @FieldDescribe("原密码.")
@Schema(description = "原密码.") @Schema(description = "原密码.")
private String oldPassword; private String oldPassword;
@FieldDescribe("新密码.") @FieldDescribe("新密码.")
@Schema(description = "新密码.") @Schema(description = "新密码.")
private String newPassword; private String newPassword;
public String getCredential() { public String getCredential() {
return credential; return credential;
} }
public void setCredential(String credential) { public void setCredential(String credential) {
this.credential = credential; this.credential = credential;
} }
public String getOldPassword() { public String getOldPassword() {
return oldPassword; return oldPassword;
} }
public void setOldPassword(String oldPassword) { public void setOldPassword(String oldPassword) {
this.oldPassword = oldPassword; this.oldPassword = oldPassword;
} }
public String getNewPassword() { public String getNewPassword() {
return newPassword; return newPassword;
} }
public void setNewPassword(String newPassword) { public void setNewPassword(String newPassword) {
this.newPassword = newPassword; this.newPassword = newPassword;
} }
} }
} }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册