diff --git a/o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/Query.java b/o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/Query.java index ea2ffe5960e233818155772f84a9d59f5776ffef..87d2fba9d8cc10bc376149980db16c26188f3d5b 100644 --- a/o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/Query.java +++ b/o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/Query.java @@ -475,6 +475,10 @@ public class Query extends ConfigObject { } } + public String getHdfsDirectoryPath() { + return this.adjustHdfsDirectoryPath(); + } + private String adjustHdfsDirectoryPath() { return StringUtils.startsWith(this.hdfsDirectoryPath, "/") ? this.hdfsDirectoryPath : "/" + hdfsDirectoryPath; diff --git a/o2server/x_base_core_project/src/main/java/com/x/base/core/project/tools/BaseTools.java b/o2server/x_base_core_project/src/main/java/com/x/base/core/project/tools/BaseTools.java index 882744e578bf343ad70dcdcc3a0898cfcafabad5..99f3c2727f2aa54b3a2a81fe9a6a8fdcbc265a85 100644 --- a/o2server/x_base_core_project/src/main/java/com/x/base/core/project/tools/BaseTools.java +++ b/o2server/x_base_core_project/src/main/java/com/x/base/core/project/tools/BaseTools.java @@ -25,6 +25,7 @@ import java.util.Map.Entry; import java.util.Objects; import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import com.google.gson.Gson; @@ -36,31 +37,31 @@ import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; 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 { - return getBaseDirectory().toAbsolutePath().toString(); - } + public static String getBasePath() throws IOException, URISyntaxException { + return getBaseDirectory().toAbsolutePath().toString(); + } - /** - * 从Main.class所在的目录开始递归向上,找到version.o2所在目录,就是程序根目录. - * - * @return - * @throws IOException - * @throws URISyntaxException - */ - private static Path getBaseDirectory() throws IOException, URISyntaxException { - Path path = Paths.get( - new URI("file://" + BaseTools.class.getProtectionDomain().getCodeSource().getLocation().getPath())); - while (Files.exists(path)) { - Path versionFile = path.resolve("version.o2"); - if (Files.exists(versionFile) && Files.isRegularFile(versionFile)) { - return path.toAbsolutePath(); - } - path = path.getParent(); - } - throw new IOException("can not define o2server base directory."); - } + /** + * 从Main.class所在的目录开始递归向上,找到version.o2所在目录,就是程序根目录. + * + * @return + * @throws IOException + * @throws URISyntaxException + */ + private static Path getBaseDirectory() throws IOException, URISyntaxException { + Path path = Paths.get( + new URI("file://" + BaseTools.class.getProtectionDomain().getCodeSource().getLocation().getPath())); + while (Files.exists(path)) { + Path versionFile = path.resolve("version.o2"); + if (Files.exists(versionFile) && Files.isRegularFile(versionFile)) { + return path.toAbsolutePath(); + } + path = path.getParent(); + } + throw new IOException("can not define o2server base directory."); + } // public static File getBaseDirectory() throws Exception { // String path = BaseTools.class.getProtectionDomain().getCodeSource().getLocation().getPath(); @@ -78,192 +79,192 @@ public class BaseTools { // throw new Exception("can not define o2server base directory."); // } - public static T readConfigObject(String path, Class cls) throws Exception { - String base = BaseTools.getBasePath(); - File file = new File(base, path); - if ((!file.exists()) || file.isDirectory()) { - return null; - } - String json = FileUtils.readFileToString(file, DefaultCharset.charset); + public static T readConfigObject(String path, Class cls) throws Exception { + String base = BaseTools.getBasePath(); + File file = new File(base, path); + if ((!file.exists()) || file.isDirectory()) { + return null; + } + String json = FileUtils.readFileToString(file, DefaultCharset.charset); - Gson gson = new Gson(); + Gson gson = new Gson(); - JsonElement jsonElement = gson.fromJson(json, JsonElement.class); - if ((null != jsonElement) && jsonElement.isJsonObject()) { - LinkedHashMap map = new LinkedHashMap<>(); - map = new Gson().fromJson(jsonElement, map.getClass()); - removeComment(map); - jsonElement = gson.toJsonTree(map); - } - return gson.fromJson(jsonElement, cls); - } + JsonElement jsonElement = gson.fromJson(json, JsonElement.class); + if ((null != jsonElement) && jsonElement.isJsonObject()) { + LinkedHashMap map = new LinkedHashMap<>(); + map = new Gson().fromJson(jsonElement, map.getClass()); + removeComment(map); + jsonElement = gson.toJsonTree(map); + } + return gson.fromJson(jsonElement, cls); + } - private static void removeComment(Map map) { - List> entries = new ArrayList<>(); - for (Entry entry : map.entrySet()) { - if (StringUtils.startsWith(Objects.toString(entry.getKey()), "###")) { - entries.add(entry); - continue; - } else { - if (entry.getValue() instanceof Map) { - removeComment((Map) entry.getValue()); - } - } - } - for (Entry entry : entries) { - map.remove(entry.getKey()); - } - } + private static void removeComment(Map map) { + List> entries = new ArrayList<>(); + for (Entry entry : map.entrySet()) { + if (StringUtils.startsWith(Objects.toString(entry.getKey()), "###")) { + entries.add(entry); + continue; + } else { + if (entry.getValue() instanceof Map) { + removeComment((Map) entry.getValue()); + } + } + } + for (Entry entry : entries) { + map.remove(entry.getKey()); + } + } - public static T readConfigObject(String path, String otherPath, Class cls) throws Exception { - String base = BaseTools.getBasePath(); - File file = new File(base, path); - if (file.exists() && file.isFile()) { - return readConfigObject(path, cls); - } - file = new File(base, otherPath); - if (file.exists() && file.isFile()) { - return readConfigObject(otherPath, cls); - } - throw new Exception("can not get file with path:" + path + ", otherPath:" + otherPath + "."); - } + public static T readConfigObject(String path, String otherPath, Class cls) throws Exception { + String base = BaseTools.getBasePath(); + File file = new File(base, path); + if (file.exists() && file.isFile()) { + return readConfigObject(path, cls); + } + file = new File(base, otherPath); + if (file.exists() && file.isFile()) { + return readConfigObject(otherPath, cls); + } + throw new Exception("can not get file with path:" + path + ", otherPath:" + otherPath + "."); + } - public static void writeObject(String path, Object obj) throws Exception { - String base = BaseTools.getBasePath(); - File file = new File(base, path); - String json = (new Gson()).toJson(obj); - FileUtils.writeStringToFile(file, json, DefaultCharset.charset); - } + public static void writeObject(String path, Object obj) throws Exception { + String base = BaseTools.getBasePath(); + File file = new File(base, path); + String json = (new Gson()).toJson(obj); + FileUtils.writeStringToFile(file, json, DefaultCharset.charset); + } - public static String readCfg(String path) throws Exception { - String base = BaseTools.getBasePath(); - File file = new File(base, path); - if ((!file.exists()) || file.isDirectory()) { - return null; - } - String str = FileUtils.readFileToString(file, DefaultCharset.charset); - return (StringUtils.trim(str)); - } + public static String readCfg(String path) throws Exception { + String base = BaseTools.getBasePath(); + File file = new File(base, path); + if ((!file.exists()) || file.isDirectory()) { + return null; + } + String str = FileUtils.readFileToString(file, DefaultCharset.charset); + return (StringUtils.trim(str)); + } - public static String readCfg(String path, String defaultValue) throws Exception { - String str = readCfg(path); - if (StringUtils.isEmpty(str)) { - str = defaultValue; - } - return (StringUtils.trim(str)); - } + public static String readCfg(String path, String defaultValue) throws Exception { + String str = readCfg(path); + if (StringUtils.isEmpty(str)) { + str = defaultValue; + } + return (StringUtils.trim(str)); + } - public static void writeCfg(String path, String value) throws Exception { - String base = BaseTools.getBasePath(); - File file = new File(base, path); - FileUtils.writeStringToFile(file, StringUtils.trim(value), DefaultCharset.charset); - } + public static void writeCfg(String path, String value) throws Exception { + String base = BaseTools.getBasePath(); + File file = new File(base, path); + FileUtils.writeStringToFile(file, StringUtils.trim(value), DefaultCharset.charset); + } - public static byte[] readBytes(String path) throws IOException, URISyntaxException { - String base = BaseTools.getBasePath(); - File file = new File(base, path); - if ((!file.exists()) || file.isDirectory()) { - throw new IOException("can not get file with path:" + file.getAbsolutePath()); - } - return FileUtils.readFileToByteArray(file); - } + public static byte[] readBytes(String path) throws IOException, URISyntaxException { + String base = BaseTools.getBasePath(); + File file = new File(base, path); + if ((!file.exists()) || file.isDirectory()) { + throw new IOException("can not get file with path:" + file.getAbsolutePath()); + } + return FileUtils.readFileToByteArray(file); + } - public static String readString(String path) throws IOException, URISyntaxException { - String base = BaseTools.getBasePath(); - File file = new File(base, path); - if ((!file.exists()) || file.isDirectory()) { - return null; - } - return FileUtils.readFileToString(file, DefaultCharset.charset); - } + public static String readString(String path) throws IOException, URISyntaxException { + String base = BaseTools.getBasePath(); + File file = new File(base, path); + if ((!file.exists()) || file.isDirectory()) { + return null; + } + 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; - Nodes nodes = Config.nodes(); - // 同步config文件 - if (Config.general().getConfigApiEnable()) { - for (String node : nodes.keySet()) { - if (nodes.get(node).getApplication().getEnable() || nodes.get(node).getCenter().getEnable()) { - Syncflag = executeSyncFile(syncFilePath, node, nodes.get(node).nodeAgentPort()); - } - } - } - return Syncflag; - } + boolean Syncflag = false; + Nodes nodes = Config.nodes(); + // 同步config文件 + if (BooleanUtils.isTrue(Config.general().getConfigApiEnable())) { + for (String node : nodes.keySet()) { + if (nodes.get(node).getApplication().getEnable() || nodes.get(node).getCenter().getEnable()) { + Syncflag = executeSyncFile(syncFilePath, node, nodes.get(node).nodeAgentPort()); + } + } + } + return Syncflag; + } - private static boolean executeSyncFile(String syncFilePath, String nodeName, int nodePort) { - boolean syncFileFlag = false; - File syncFile; - InputStream fileInputStream = null; + private static boolean executeSyncFile(String syncFilePath, String nodeName, int nodePort) { + boolean syncFileFlag = false; + File syncFile; + InputStream fileInputStream = null; - try (Socket socket = new Socket(nodeName, nodePort)) { + try (Socket socket = new Socket(nodeName, nodePort)) { - syncFile = new File(Config.base(), syncFilePath); - fileInputStream = new FileInputStream(syncFile); + syncFile = new File(Config.base(), syncFilePath); + fileInputStream = new FileInputStream(syncFile); - socket.setKeepAlive(true); - socket.setSoTimeout(2000); - DataOutputStream dos = null; - DataInputStream dis = null; - try { - dos = new DataOutputStream(socket.getOutputStream()); - dis = new DataInputStream(socket.getInputStream()); + socket.setKeepAlive(true); + socket.setSoTimeout(2000); + DataOutputStream dos = null; + DataInputStream dis = null; + try { + dos = new DataOutputStream(socket.getOutputStream()); + dis = new DataInputStream(socket.getInputStream()); - Map commandObject = new HashMap<>(); - commandObject.put("command", "syncFile:" + syncFilePath); - commandObject.put("credential", Crypto.rsaEncrypt("o2@", Config.publicKey())); - dos.writeUTF(XGsonBuilder.toJson(commandObject)); - dos.flush(); + Map commandObject = new HashMap<>(); + commandObject.put("command", "syncFile:" + syncFilePath); + commandObject.put("credential", Crypto.rsaEncrypt("o2@", Config.publicKey())); + dos.writeUTF(XGsonBuilder.toJson(commandObject)); + dos.flush(); - dos.writeUTF(syncFilePath); - dos.flush(); + dos.writeUTF(syncFilePath); + dos.flush(); - logger.info("同步文件:" + syncFilePath + " starting..."); - byte[] bytes = new byte[1024]; - int length = 0; - while ((length = fileInputStream.read(bytes, 0, bytes.length)) != -1) { - dos.write(bytes, 0, length); - dos.flush(); - } - logger.info("同步文件:" + syncFilePath + "end."); + logger.info("同步文件:" + syncFilePath + " starting..."); + byte[] bytes = new byte[1024]; + int length = 0; + while ((length = fileInputStream.read(bytes, 0, bytes.length)) != -1) { + dos.write(bytes, 0, length); + dos.flush(); + } + logger.info("同步文件:" + syncFilePath + " end."); - } finally { - dos.close(); - dis.close(); - socket.close(); - fileInputStream.close(); - } + } finally { + dos.close(); + dis.close(); + socket.close(); + fileInputStream.close(); + } - syncFileFlag = true; - } catch (Exception ex) { - logger.error(ex); - syncFileFlag = false; - } - return syncFileFlag; - } + syncFileFlag = true; + } catch (Exception ex) { + logger.error(ex); + syncFileFlag = false; + } + return syncFileFlag; + } - public static String getIpAddress() { - try { - Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); - InetAddress ip = null; - while (allNetInterfaces.hasMoreElements()) { - NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); - if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) { - continue; - } else { - Enumeration addresses = netInterface.getInetAddresses(); - while (addresses.hasMoreElements()) { - ip = addresses.nextElement(); - if (ip != null && ip instanceof Inet4Address) { - return ip.getHostAddress(); - } - } - } - } - } catch (Exception e) { - System.err.println("IP地址获取失败" + e.toString()); - } - return ""; - } + public static String getIpAddress() { + try { + Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); + InetAddress ip = null; + while (allNetInterfaces.hasMoreElements()) { + NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); + if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) { + continue; + } else { + Enumeration addresses = netInterface.getInetAddresses(); + while (addresses.hasMoreElements()) { + ip = addresses.nextElement(); + if (ip != null && ip instanceof Inet4Address) { + return ip.getHostAddress(); + } + } + } + } + } catch (Exception e) { + System.err.println("IP地址获取失败" + e.toString()); + } + return ""; + } } diff --git a/o2server/x_console/src/main/java/com/x/server/console/Main.java b/o2server/x_console/src/main/java/com/x/server/console/Main.java index e5fa0295ed9e3d6bd1a8f4e62e2929f6d51a4525..63d0286967c971cf598bb749e60c093865e4039c 100644 --- a/o2server/x_console/src/main/java/com/x/server/console/Main.java +++ b/o2server/x_console/src/main/java/com/x/server/console/Main.java @@ -32,7 +32,6 @@ import java.util.regex.Matcher; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.BooleanUtils; 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.CenterServer; @@ -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.DefaultCharset; 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.ActionSetPassword; import com.x.server.console.action.ActionVersion; @@ -123,7 +121,7 @@ public class Main { public static void main(String[] args) throws Exception { init(); 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(); consoleCommandThread.start(); @@ -134,8 +132,8 @@ public class Main { nodeAgent.start(); } - SchedulerBuilder schedulerBuilder = new SchedulerBuilder(); - Scheduler scheduler = schedulerBuilder.start(); +// SchedulerBuilder schedulerBuilder = new SchedulerBuilder(); +// Scheduler scheduler = schedulerBuilder.start(); if (BooleanUtils.isTrue(Config.currentNode().autoStart())) { startAll(); @@ -217,11 +215,7 @@ public class Main { matcher = CommandFactory.setPassword_pattern.matcher(cmd); if (matcher.find()) { setPassword(matcher.group(1), matcher.group(2)); - if (config()) { - break; - } else { - continue; - } + continue; } matcher = CommandFactory.control_pattern.matcher(cmd); @@ -242,9 +236,6 @@ public class Main { } System.out.println("unknown command:" + cmd); } - // 关闭定时器 - scheduler.shutdown(); - // SystemOutErrorSideCopyBuilder.stop(); } private static void version() { @@ -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() { try { if (BooleanUtils.isTrue(Servers.dataServerIsRunning())) { diff --git a/o2server/x_console/src/main/java/com/x/server/console/action/ActionConfig.java b/o2server/x_console/src/main/java/com/x/server/console/action/ActionConfig.java deleted file mode 100644 index ebcdf88bbfe10f5afb1af2faf030b031df1b2f65..0000000000000000000000000000000000000000 --- a/o2server/x_console/src/main/java/com/x/server/console/action/ActionConfig.java +++ /dev/null @@ -1,78 +0,0 @@ -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 diff --git a/o2server/x_console/src/main/java/com/x/server/console/action/ActionSetPassword.java b/o2server/x_console/src/main/java/com/x/server/console/action/ActionSetPassword.java index aa13159f342d35faee0bfe12573c3ce635128f76..e5ae6d8fe73d4b848800a1a549a81a777547eb4b 100644 --- a/o2server/x_console/src/main/java/com/x/server/console/action/ActionSetPassword.java +++ b/o2server/x_console/src/main/java/com/x/server/console/action/ActionSetPassword.java @@ -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.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; +import com.x.server.console.server.Servers; 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 { - /** 如果初始密码没有修改就设置为初始密码 */ - if (StringUtils.equals(Config.token().getPassword(), Token.initPassword)) { - oldPassword = Token.initPassword; - } - if (!StringUtils.equals(Config.token().getPassword(), oldPassword)) { - logger.print("old password not match."); - return false; - } - this.changeInternalDataServerPassword(oldPassword, newPassword); - Config.token().setPassword(newPassword); - Config.token().save(); - logger.print("The initial manager password has been modified."); - return true; - } + public boolean execute(String oldPassword, String newPassword) throws Exception { + /** 如果初始密码没有修改就设置为初始密码 */ + if (StringUtils.equals(Config.token().getPassword(), Token.initPassword)) { + oldPassword = Token.initPassword; + } + if (!StringUtils.equals(Config.token().getPassword(), oldPassword)) { + LOGGER.print("old password not match."); + return false; + } + this.changeInternalDataServerPassword(oldPassword, newPassword); + Config.token().setPassword(newPassword); + Config.token().save(); + LOGGER.print("The initial manager password has been modified."); + return true; + } - private void changeInternalDataServerPassword(String oldPassword, String newPassword) throws Exception { - org.h2.Driver.load(); - for (Entry en : Config.nodes().dataServers().entrySet()) { - DataServer o = en.getValue(); - if (BooleanUtils.isTrue(o.getEnable())) { - try (Connection conn = DriverManager.getConnection( - "jdbc:h2:tcp://" + en.getKey() + ":" + o.getTcpPort() + "/X", "sa", oldPassword)) { - RunScript.execute(conn, new StringReader("ALTER USER SA SET PASSWORD '" + newPassword + "'")); - } catch (Exception e) { - throw new IllegalStateException("Verify that the dataServer:" + en.getKey() - + " is started and that the dataServer password is updated synchronously.", e); - } - } - } - } + private void changeInternalDataServerPassword(String oldPassword, String newPassword) throws Exception { + org.h2.Driver.load(); + for (Entry en : Config.nodes().dataServers().entrySet()) { + DataServer o = en.getValue(); + if (BooleanUtils.isTrue(o.getEnable()) && (!Config.externalDataSources().enable())) { + try (Connection conn = DriverManager.getConnection( + "jdbc:h2:tcp://" + en.getKey() + ":" + o.getTcpPort() + "/X", "sa", oldPassword)) { + RunScript.execute(conn, new StringReader("ALTER USER SA SET PASSWORD '" + newPassword + "'")); + } catch (Exception e) { + throw new IllegalStateException("Verify that the dataServer:" + en.getKey() + + " is started and that the dataServer password is updated synchronously.", e); + } + } + } + } } diff --git a/o2server/x_program_center/src/main/java/com/x/program/center/jaxrs/config/ActionChangePassword.java b/o2server/x_program_center/src/main/java/com/x/program/center/jaxrs/config/ActionChangePassword.java index 7cd9bbd7c73330ad2fc2ab002eeaf0d974555c4d..653f05c1c2674645b8dfe7cea16b3916592df7d9 100644 --- a/o2server/x_program_center/src/main/java/com/x/program/center/jaxrs/config/ActionChangePassword.java +++ b/o2server/x_program_center/src/main/java/com/x/program/center/jaxrs/config/ActionChangePassword.java @@ -25,167 +25,167 @@ import io.swagger.v3.oas.annotations.media.Schema; class ActionChangePassword extends BaseAction { - private static final Logger LOGGER = LoggerFactory.getLogger(ActionChangePassword.class); - - ActionResult execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception { - - LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName); - - ActionResult result = new ActionResult<>(); - Wi wi = this.convertToWrapIn(jsonElement, Wi.class); - if (BooleanUtils.isNotTrue(Config.general().getConfigApiEnable())) { - throw new ExceptionModifyConfig(); - } - - check(wi); - - String oldPassword = password(wi.getOldPassword()); - String newPassword = password(wi.getNewPassword()); - - checkPasswordComplexity(wi.getCredential(), newPassword); - - if (Config.ternaryManagement().isAuditManager(wi.getCredential())) { - changeAuditManagerPassword(effectivePerson, wi.getCredential(), oldPassword, newPassword); - } else if (Config.ternaryManagement().isSecurityManager(wi.getCredential())) { - changeSecurityManager(effectivePerson, wi.getCredential(), oldPassword, newPassword); - } else if (Config.ternaryManagement().isSystemManager(wi.getCredential())) { - changeSystemManager(effectivePerson, wi.getCredential(), oldPassword, newPassword); - } else if (StringUtils.equals(wi.getCredential(), Config.token().getInitialManager())) { - changeInitialManager(effectivePerson, oldPassword, newPassword); - } else { - throw new ExceptionInvalidCredential(); - } - - Wo wo = new Wo(); - wo.setValue(true); - result.setData(wo); - return result; - } - - private void changeAuditManagerPassword(EffectivePerson effectivePerson, String credential, String oldPassword, - String newPassword) throws Exception { - if (BooleanUtils.isNotTrue(Config.ternaryManagement().verifyPassword(credential, oldPassword))) { - throw new ExceptionInvalidOldPassword(); - } - Config.ternaryManagement().setAuditManagerPassword(newPassword); - Config.ternaryManagement().save(); - this.configFlush(effectivePerson); - } - - private void changeSecurityManager(EffectivePerson effectivePerson, String credential, String oldPassword, - String newPassword) throws Exception { - if (BooleanUtils.isNotTrue(Config.ternaryManagement().verifyPassword(credential, oldPassword))) { - throw new ExceptionInvalidOldPassword(); - } - Config.ternaryManagement().setSecurityManagerPassword(newPassword); - Config.ternaryManagement().save(); - this.configFlush(effectivePerson); - } - - private void changeSystemManager(EffectivePerson effectivePerson, String credential, String oldPassword, - String newPassword) throws Exception { - if (BooleanUtils.isNotTrue(Config.ternaryManagement().verifyPassword(credential, oldPassword))) { - throw new ExceptionInvalidOldPassword(); - } - Config.ternaryManagement().setSystemManagerPassword(newPassword); - Config.ternaryManagement().save(); - this.configFlush(effectivePerson); - } - - private void changeInitialManager(EffectivePerson effectivePerson, String oldPassword, String newPassword) - throws Exception { - if (BooleanUtils.isNotTrue(StringUtils.equals(Config.token().getPassword(), oldPassword))) { - throw new ExceptionInvalidOldPassword(); - } - this.changeInternalDataServerPassword(oldPassword, newPassword); - Config.token().setPassword(newPassword); - Config.token().save(); - this.configFlush(effectivePerson); - } - - private void changeInternalDataServerPassword(String oldPassword, String newPassword) throws Exception { - org.h2.Driver.load(); - for (Entry en : Config.nodes().dataServers().entrySet()) { - DataServer o = en.getValue(); - if (BooleanUtils.isTrue(o.getEnable())) { - try (Connection conn = DriverManager.getConnection( - "jdbc:h2:tcp://" + en.getKey() + ":" + o.getTcpPort() + "/X", "sa", oldPassword)) { - RunScript.execute(conn, new StringReader("ALTER USER SA SET PASSWORD '" + newPassword + "'")); - } catch (Exception e) { - throw new IllegalStateException("Verify that the dataServer:" + en.getKey() - + " is started and that the dataServer password is updated synchronously.", e); - } - } - } - } - - private void check(Wi wi) throws ExceptionEmptyCredential, ExceptionEmptyOldPassword, ExceptionEmptyNewPassword { - if (StringUtils.isEmpty(wi.getCredential())) { - throw new ExceptionEmptyCredential(); - } - if (StringUtils.isEmpty(wi.getOldPassword())) { - throw new ExceptionEmptyOldPassword(); - } - if (StringUtils.isEmpty(wi.getCredential())) { - throw new ExceptionEmptyNewPassword(); - } - } - - private void checkPasswordComplexity(String credential, String newPassword) throws Exception { - if (!newPassword.matches(Config.person().getPasswordRegex())) { - throw new ExceptionInvalidPassword(credential, Config.person().getPasswordRegexHint()); - } - } - - protected String password(String text) throws Exception { - return BooleanUtils.isTrue(Config.token().getRsaEnable()) ? Crypto.rsaDecrypt(text, Config.privateKey()) : text; - } - - @Schema(name = "com.x.program.center.jaxrs.config.ActionChangePassword$Wo") - public static class Wo extends WrapBoolean { - - private static final long serialVersionUID = -6564786947838509994L; - } - - @Schema(name = "com.x.program.center.jaxrs.config.ActionChangePassword$Wi") - public static class Wi extends GsonPropertyObject { - - private static final long serialVersionUID = -8627814779546541124L; - - @FieldDescribe("用户标识.") - @Schema(description = "用户标识.") - private String credential; - @FieldDescribe("原密码.") - @Schema(description = "原密码.") - private String oldPassword; - @FieldDescribe("新密码.") - @Schema(description = "新密码.") - private String newPassword; - - public String getCredential() { - return credential; - } - - public void setCredential(String credential) { - this.credential = credential; - } - - public String getOldPassword() { - return oldPassword; - } - - public void setOldPassword(String oldPassword) { - this.oldPassword = oldPassword; - } - - public String getNewPassword() { - return newPassword; - } - - public void setNewPassword(String newPassword) { - this.newPassword = newPassword; - } - - } + private static final Logger LOGGER = LoggerFactory.getLogger(ActionChangePassword.class); + + ActionResult execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception { + + LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName); + + ActionResult result = new ActionResult<>(); + Wi wi = this.convertToWrapIn(jsonElement, Wi.class); + if (BooleanUtils.isNotTrue(Config.general().getConfigApiEnable())) { + throw new ExceptionModifyConfig(); + } + + check(wi); + + String oldPassword = password(wi.getOldPassword()); + String newPassword = password(wi.getNewPassword()); + + checkPasswordComplexity(wi.getCredential(), newPassword); + + if (Config.ternaryManagement().isAuditManager(wi.getCredential())) { + changeAuditManagerPassword(effectivePerson, wi.getCredential(), oldPassword, newPassword); + } else if (Config.ternaryManagement().isSecurityManager(wi.getCredential())) { + changeSecurityManager(effectivePerson, wi.getCredential(), oldPassword, newPassword); + } else if (Config.ternaryManagement().isSystemManager(wi.getCredential())) { + changeSystemManager(effectivePerson, wi.getCredential(), oldPassword, newPassword); + } else if (StringUtils.equals(wi.getCredential(), Config.token().getInitialManager())) { + changeInitialManager(effectivePerson, oldPassword, newPassword); + } else { + throw new ExceptionInvalidCredential(); + } + + Wo wo = new Wo(); + wo.setValue(true); + result.setData(wo); + return result; + } + + private void changeAuditManagerPassword(EffectivePerson effectivePerson, String credential, String oldPassword, + String newPassword) throws Exception { + if (BooleanUtils.isNotTrue(Config.ternaryManagement().verifyPassword(credential, oldPassword))) { + throw new ExceptionInvalidOldPassword(); + } + Config.ternaryManagement().setAuditManagerPassword(newPassword); + Config.ternaryManagement().save(); + this.configFlush(effectivePerson); + } + + private void changeSecurityManager(EffectivePerson effectivePerson, String credential, String oldPassword, + String newPassword) throws Exception { + if (BooleanUtils.isNotTrue(Config.ternaryManagement().verifyPassword(credential, oldPassword))) { + throw new ExceptionInvalidOldPassword(); + } + Config.ternaryManagement().setSecurityManagerPassword(newPassword); + Config.ternaryManagement().save(); + this.configFlush(effectivePerson); + } + + private void changeSystemManager(EffectivePerson effectivePerson, String credential, String oldPassword, + String newPassword) throws Exception { + if (BooleanUtils.isNotTrue(Config.ternaryManagement().verifyPassword(credential, oldPassword))) { + throw new ExceptionInvalidOldPassword(); + } + Config.ternaryManagement().setSystemManagerPassword(newPassword); + Config.ternaryManagement().save(); + this.configFlush(effectivePerson); + } + + private void changeInitialManager(EffectivePerson effectivePerson, String oldPassword, String newPassword) + throws Exception { + if (BooleanUtils.isNotTrue(StringUtils.equals(Config.token().getPassword(), oldPassword))) { + throw new ExceptionInvalidOldPassword(); + } + this.changeInternalDataServerPassword(oldPassword, newPassword); + Config.token().setPassword(newPassword); + Config.token().save(); + this.configFlush(effectivePerson); + } + + private void changeInternalDataServerPassword(String oldPassword, String newPassword) throws Exception { + org.h2.Driver.load(); + for (Entry en : Config.nodes().dataServers().entrySet()) { + DataServer o = en.getValue(); + if (BooleanUtils.isTrue(o.getEnable()) && (!Config.externalDataSources().enable())) { + try (Connection conn = DriverManager.getConnection( + "jdbc:h2:tcp://" + en.getKey() + ":" + o.getTcpPort() + "/X", "sa", oldPassword)) { + RunScript.execute(conn, new StringReader("ALTER USER SA SET PASSWORD '" + newPassword + "'")); + } catch (Exception e) { + throw new IllegalStateException("Verify that the dataServer:" + en.getKey() + + " is started and that the dataServer password is updated synchronously.", e); + } + } + } + } + + private void check(Wi wi) throws ExceptionEmptyCredential, ExceptionEmptyOldPassword, ExceptionEmptyNewPassword { + if (StringUtils.isEmpty(wi.getCredential())) { + throw new ExceptionEmptyCredential(); + } + if (StringUtils.isEmpty(wi.getOldPassword())) { + throw new ExceptionEmptyOldPassword(); + } + if (StringUtils.isEmpty(wi.getCredential())) { + throw new ExceptionEmptyNewPassword(); + } + } + + private void checkPasswordComplexity(String credential, String newPassword) throws Exception { + if (!newPassword.matches(Config.person().getPasswordRegex())) { + throw new ExceptionInvalidPassword(credential, Config.person().getPasswordRegexHint()); + } + } + + protected String password(String text) throws Exception { + return BooleanUtils.isTrue(Config.token().getRsaEnable()) ? Crypto.rsaDecrypt(text, Config.privateKey()) : text; + } + + @Schema(name = "com.x.program.center.jaxrs.config.ActionChangePassword$Wo") + public static class Wo extends WrapBoolean { + + private static final long serialVersionUID = -6564786947838509994L; + } + + @Schema(name = "com.x.program.center.jaxrs.config.ActionChangePassword$Wi") + public static class Wi extends GsonPropertyObject { + + private static final long serialVersionUID = -8627814779546541124L; + + @FieldDescribe("用户标识.") + @Schema(description = "用户标识.") + private String credential; + @FieldDescribe("原密码.") + @Schema(description = "原密码.") + private String oldPassword; + @FieldDescribe("新密码.") + @Schema(description = "新密码.") + private String newPassword; + + public String getCredential() { + return credential; + } + + public void setCredential(String credential) { + this.credential = credential; + } + + public String getOldPassword() { + return oldPassword; + } + + public void setOldPassword(String oldPassword) { + this.oldPassword = oldPassword; + } + + public String getNewPassword() { + return newPassword; + } + + public void setNewPassword(String newPassword) { + this.newPassword = newPassword; + } + + } }