Kaynağa Gözat

增加删除数据源方法

郭志波 6 yıl önce
ebeveyn
işleme
15bd484d66

+ 197 - 9
src/main/java/com/leanwo/management/DataSourceSettingFrame.java

@@ -202,7 +202,11 @@ public class DataSourceSettingFrame extends JFrame {
 		StringBuilder stringBuilder = new StringBuilder();
 		stringBuilder.append("您修改了程序管理器的配置,");
 		//修ServerManagement程序管理器application.yml的参数
-		updateYml( dataSourceConfigs);
+		try {
+			updateYml( dataSourceConfigs);
+		} catch (Exception e) {
+			JOptionPane.showMessageDialog(this, "错误。", e.getMessage(), JOptionPane.INFORMATION_MESSAGE);
+		}
 		//
 		updateApplicationXml(map);
 		// 根据dataSourceConfigs修改各个服务器中applicationContext.xml里面的数据
@@ -343,8 +347,9 @@ public class DataSourceSettingFrame extends JFrame {
 	 * 修ServerManagement程序管理器application.yml的参数
 	 * @param dataSourceConfigs
 	 * @author GuoZhiBo 20200522
+	 * @throws Exception 
 	 */
-	private void updateYml(List<DataSourceConfig> dataSourceConfigs) {
+	private void updateYml(List<DataSourceConfig> dataSourceConfigs) throws Exception {
 		// 根据dataSourceConfigs修改yml
 		Yaml yaml = new Yaml();
 	    File file = new File("resources/Application.yml");
@@ -373,12 +378,7 @@ public class DataSourceSettingFrame extends JFrame {
 			    e.printStackTrace();
 			}
 	    }else {
-	    	try {
-				throw new ServerException("地址错误,请确认是服务器还是本地再修改。");
-			} catch (ServerException e) {
-				// TODO Auto-generated catch block
-				e.printStackTrace();
-			}
+	    	throw new Exception("地址错误,请确认是服务器还是本地再修改。");
 	    }
 	}
 	
@@ -406,11 +406,199 @@ public class DataSourceSettingFrame extends JFrame {
 		//如果这个整数等于JOptionPane.YES_OPTION,则说明你点击的是“确定”按钮,则允许继续操作,否则结束
 		if(isDelete == JOptionPane.YES_OPTION){
 		    // 添加业务逻辑。
-			
+			try {
+				deleteApplicationXml(dataSourceConfig);
+				deleteYml(dataSourceConfig);
+			} catch (Exception e) {
+				JOptionPane.showMessageDialog(this, "错误。", e.getMessage(), JOptionPane.INFORMATION_MESSAGE);
+			}
 			tableModel.removeRow(selectedRow);
 			// 执行删除的业务逻辑
 		    JOptionPane.showMessageDialog(null, "删除成功");
 		}
 			
 	}
+	
+	/**
+	 * 删除选中的数据源
+	 * 本地使用:src/main/resources/Application.yml
+	 * 服务器使用:resources/Application.yml
+	 * @param dataSourceConfig
+	 * @author GuoZhiBo 20200528
+	 * @throws Exception 
+	 */
+	private void deleteYml(DataSourceConfig dataSourceConfig) throws Exception {
+		// 根据dataSourceConfigs修改yml
+		Yaml yaml = new Yaml();
+	    File file = new File("src/main/resources/Application.yml");
+	    String path = file.getAbsolutePath();
+	    if(file.exists()) {
+	    	try {
+				Map m1 = (Map) yaml.load(new FileInputStream(file));
+				Map m2 = (Map) m1.get("data-source");
+				List m3 = (List)m2.get("items");
+				for(int i = 0; i < m3.size(); i ++) {
+					Map mapi = (Map)m3.get(i);
+					String dataSource = mapi.get("beanId").toString();
+					if(dataSourceConfig.getBeanId().equals(dataSource)) {
+						m3.remove(i);
+						break;
+					}
+				}
+				FileWriter fileWriter = new FileWriter(file);
+				fileWriter.write(yaml.dump(m1));
+			    fileWriter.flush();
+			    fileWriter.close();
+			} catch (FileNotFoundException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			} catch (Exception e) {
+			    e.printStackTrace();
+			}
+	    }else {
+	    	throw new Exception("地址错误,请确认是服务器还是本地再修改。");
+	    }
+	}
+	
+	/**
+	 * 只用于正式服务器
+	 * 删除其他服务器所对应的application.xml参数
+	 * url、password、userName
+	 * @param map
+	 * @author GuoZhiBo 20200528
+	 * @throws Exception 
+	 */
+	private void deleteApplicationXml(DataSourceConfig dataSourceConfig) throws Exception {
+		File directory = new File(""); 
+		String path = directory.getAbsolutePath();
+		File parentPath = new File(path).getParentFile();
+		 // 取 文件/文件夹
+        File files[] = parentPath.listFiles();
+        // 对象为空 直接返回
+        if(files != null){
+        	// 存在文件 遍历 判断
+            for (File f : files) {
+                // 判断是否为 文件夹
+                if(f.isDirectory()){
+                   String filePath = f.getAbsolutePath(); 
+                   if(path.equals(filePath)) {
+                	   continue;
+                   }
+                   File applicationContextXml = new File(filePath + "\\resources\\applicationContext.xml"); 
+                   if(!applicationContextXml.exists()) {
+                	   continue;
+                   }
+                   deleteXml(applicationContextXml, dataSourceConfig);
+                } 
+                
+            }
+        }
+	}
+	
+	private void deleteXml(File file, DataSourceConfig dataSourceConfig) throws Exception {
+		// 1、创建 DocumentBuilderFactory 对象,用来创建 DocumentBuilder  对象
+		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+		try {
+			// 2、创建 DocumentBuilder 对象,用来将 XML 文件 转化为 Document 对象
+			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
+			// 3、创建 Document 对象,解析 XML 文件
+			Document document = documentBuilder.parse(file);
+			NodeList beanList = document.getElementsByTagName("bean");
+			if(beanList != null && beanList.getLength() > 0) {
+				for(int i = 0 ; i < beanList.getLength() ; i ++) {
+					// 获取第一个对象
+					Node bean = beanList.item(i);
+					Element beanElement = (Element) bean;
+					//获取所有属性
+					NamedNodeMap namedNodeMap = bean.getAttributes();
+					//获取id
+					Node idNode = namedNodeMap.getNamedItem("id");
+					if(idNode == null) {
+						continue;
+					}
+					String id = idNode.getTextContent();
+					if(id != null && id.length() > 0) {
+						if(id.equals("dataSource")) {
+							NodeList propertyList = beanElement.getElementsByTagName("property");
+							if(propertyList != null && propertyList.getLength() > 0) {
+								for(int j = 0 ; j < propertyList.getLength() ; j ++) {
+									//获取property第一个对象
+									Node property = propertyList.item(j);
+									//获取property所有属性
+									NamedNodeMap propertyMap = property.getAttributes();
+									//获取name
+									Node propertyNameNode = propertyMap.getNamedItem("name");
+									String propertyName = propertyNameNode.getTextContent();
+									if(propertyName.equals("defaultTargetDataSource")) {
+										Node propertyRefNode = propertyMap.getNamedItem("ref");
+										String propertyRef = propertyRefNode.getTextContent();
+										if(propertyRef.equals(dataSourceConfig.getBeanId())) {
+											throw new Exception("不能删除默认数据源");
+										}
+									}
+									//删除数据源
+									if(propertyName.equals("targetDataSources")) {
+										Element propertyElement = (Element) property;
+										NodeList mapList = propertyElement.getElementsByTagName("map");
+										if(mapList != null && mapList.getLength() > 0) {
+											for(int a = 0 ; a < mapList.getLength() ; a ++) {
+												Node map = mapList.item(a);
+												Element mapElement = (Element) map;
+												NodeList entryList = mapElement.getElementsByTagName("entry");
+												if(entryList != null && entryList.getLength() > 0) {
+													for(int b = 0 ; b < entryList.getLength() ; b ++) {
+														Node entry = entryList.item(b);
+														NamedNodeMap entryMap = entry.getAttributes();
+														Node entryNode = entryMap.getNamedItem("key");
+														String key = entryNode.getTextContent();
+														if(key.equals(dataSourceConfig.getBeanId())) {
+															entry.getParentNode().removeChild(entry);
+															break;
+														}
+													}
+												}
+											}
+										}
+										
+									}
+								}
+							}
+						}
+						//找到bean的Id是否在数据源中
+						if(dataSourceConfig.getBeanId().equals(id)) {
+							bean.getParentNode().removeChild(bean);
+						}
+					}
+					
+				}
+			}
+			// 创建 TransformerFactory 对象
+			TransformerFactory transformerFactory = TransformerFactory.newInstance();
+			// 创建 Transformer 对象
+			Transformer transformer = transformerFactory.newTransformer();
+			// 创建 DOMSource 对象
+			DOMSource domSource = new DOMSource(document);
+			// 创建 StreamResult 对象
+			StreamResult reStreamResult = new StreamResult(file);
+			transformer.transform(domSource, reStreamResult);
+			
+		} catch (ParserConfigurationException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (SAXException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (TransformerConfigurationException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (TransformerException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		
+		
+	}
 }