import com.dassault_systemes.platform.ven.jackson.databind.ObjectMapper; import com.dassault_systemes.platform.ven.jackson.databind.node.ArrayNode; import com.dassault_systemes.platform.ven.jackson.databind.node.ObjectNode; import com.matrixone.apps.domain.util.MqlUtil; import matrix.db.Context; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; public class TMLProjectAttrManagement_mxJPO { // 配置文件路径 - 使用你指定的路径 private static final String CONFIG_FILE_PATH = "/jpo/File/liangqi.txt"; public String getTrialProductSeries(Context context, String[] args) throws Exception { String itemValue = args[0]; List list = new ArrayList<>(); String getProductSeriesRangeValue = "print attribute TrialProductSeries select range dump |"; String productSeriesRangeValue = MqlUtil.mqlCommand(context, getProductSeriesRangeValue); String[] arrValue = dealItemValue(context, productSeriesRangeValue); // 处理数据并生成JSON String jsonResult = processDataAndGenerateJson(context, arrValue); // 将JSON结果添加到list list.add(jsonResult); // 使用JSON库序列化list ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(list); } public String delRangeValue(Context context, String[] args) throws Exception { String attrValue = args[0]; String attrRange = args[1]; String updateAttrRange = "modify attribute TrialProductSeries remove range = " + attrRange; MqlUtil.mqlCommand(context, updateAttrRange); // 同时从配置文件删除对应的键值 if (attrRange != null && !attrRange.trim().isEmpty()) { boolean deleted = deleteFromConfigFile(attrRange.trim()); System.out.println("从配置文件删除结果:" + (deleted ? "成功" : "失败")); } return "删除完成"; } public String addRangeValue(Context context, String[] args) throws Exception { String attrValue = args[0]; String attrRange = args[1]; String attrRangeDes = args[2]; String addAttrRange = "add attribute TrialProductSeries add range = " + attrRange; MqlUtil.mqlCommand(context, addAttrRange); // 同时添加到配置文件 if (attrRange != null && !attrRange.trim().isEmpty() && attrRangeDes != null && !attrRangeDes.trim().isEmpty()) { boolean added = addToConfigFile(attrRange.trim(), attrRangeDes.trim()); System.out.println("添加到配置文件结果:" + (added ? "成功" : "失败")); } return "添加完成"; } /** * 向配置文件添加键值对 * @param key 英文键名 * @param value 中文值 * @return 是否添加成功 */ public boolean addToConfigFile(String key, String value) { try { if (key == null || key.trim().isEmpty() || value == null || value.trim().isEmpty()) { System.err.println("错误:键和值都不能为空"); return false; } File configFile = new File(CONFIG_FILE_PATH); // 如果文件不存在,创建文件 if (!configFile.exists()) { createDefaultConfigFile(); } // 检查键是否已存在 try (BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(configFile), "UTF-8"))) { String line; while ((line = reader.readLine()) != null) { if (line.trim().startsWith(key + "=")) { System.out.println("键已存在:" + key); return false; } } } // 追加到文件末尾 try (BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(configFile, true), "UTF-8"))) { writer.write(key + "=" + value); writer.newLine(); System.out.println("成功添加键值对:" + key + "=" + value); return true; } catch (Exception e) { System.err.println("写入文件失败:" + e.getMessage()); return false; } } catch (Exception e) { System.err.println("添加文件内容时出错:" + e.getMessage()); return false; } } /** * 删除配置文件中的指定键值 * @param keyToDelete 要删除的英文键名 * @return 是否删除成功 */ public boolean deleteFromConfigFile(String keyToDelete) { try { if (keyToDelete == null || keyToDelete.trim().isEmpty()) { System.err.println("错误:要删除的键不能为空"); return false; } File configFile = new File(CONFIG_FILE_PATH); // 检查文件是否存在 if (!configFile.exists()) { System.err.println("配置文件不存在:" + CONFIG_FILE_PATH); return false; } // 读取文件内容 List lines = new ArrayList<>(); boolean keyFound = false; try (BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(configFile), "UTF-8"))) { String line; while ((line = reader.readLine()) != null) { if (!keyFound && line.trim().startsWith(keyToDelete + "=")) { // 找到要删除的行,跳过不加入列表 keyFound = true; System.out.println("找到并删除键:" + keyToDelete); continue; } lines.add(line); } } if (!keyFound) { System.out.println("未找到要删除的键:" + keyToDelete); return false; } // 写回文件 try (BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(configFile), "UTF-8"))) { for (String line : lines) { writer.write(line); writer.newLine(); } } System.out.println("成功删除键:" + keyToDelete); return true; } catch (Exception e) { System.err.println("删除文件内容时出错:" + e.getMessage()); return false; } } public String[] dealItemValue(Context context, String itemValue) { if (itemValue == null || itemValue.trim().isEmpty()) { return new String[0]; } String[] values = itemValue.split("\\s*\\|=\\s*"); // 创建新数组,跳过第一个空元素 String[] result = new String[values.length - 1]; System.arraycopy(values, 1, result, 0, values.length - 1); // 打印结果(调试用) System.out.println("解析到的原始值:"); for (String value : result) { System.out.println(" - " + value); } return result; } /** * 主处理方法 - 处理 arrValue 并生成 JSON */ public String processDataAndGenerateJson(Context context, String[] arrValue) throws Exception { System.out.println("=== 开始处理数据 ==="); System.out.println("接收到 arrValue 数量: " + (arrValue != null ? arrValue.length : 0)); System.out.println("配置文件路径: " + CONFIG_FILE_PATH); // 1. 从文件读取中文映射(优先使用文件,如果文件不存在则使用默认数据) Map chineseMapping = loadMappingFromFile(); // 2. 打印映射数据(用于调试) System.out.println("使用的映射数据大小: " + chineseMapping.size()); System.out.println("映射数据内容:"); for (Map.Entry entry : chineseMapping.entrySet()) { System.out.println(" " + entry.getKey() + " -> " + entry.getValue()); } // 3. 处理 arrValue,构建数据列表 List deviceItems = new ArrayList<>(); if (arrValue != null) { for (int i = 0; i < arrValue.length; i++) { String englishKey = arrValue[i].trim(); String chineseName = chineseMapping.getOrDefault(englishKey, englishKey); System.out.println("处理项 " + (i + 1) + ": " + englishKey + " -> " + chineseName); DeviceItem item = new DeviceItem(); item.setId(i + 1); item.setName(englishKey); item.setDescription(chineseName); deviceItems.add(item); } } // 4. 生成 JSON String jsonResult = generateSimpleJson(deviceItems); // 5. 打印结果 System.out.println("处理完成,生成 " + deviceItems.size() + " 条记录"); return jsonResult; } /** * 从文件加载映射数据 */ private Map loadMappingFromFile() { Map mapping = new HashMap<>(); File configFile = new File(CONFIG_FILE_PATH); System.out.println("尝试从文件加载映射数据: " + CONFIG_FILE_PATH); System.out.println("文件绝对路径: " + configFile.getAbsolutePath()); System.out.println("文件是否存在: " + configFile.exists()); System.out.println("文件可读: " + configFile.canRead()); if (configFile.exists()) { try { // 使用 Properties 加载 Properties props = new Properties(); try (FileInputStream fis = new FileInputStream(configFile); InputStreamReader isr = new InputStreamReader(fis, "UTF-8")) { props.load(isr); // 转换为Map for (String key : props.stringPropertyNames()) { String value = props.getProperty(key).trim(); mapping.put(key.trim(), value); System.out.println(" 加载: " + key.trim() + " = " + value); } System.out.println("✓ 成功从文件加载 " + mapping.size() + " 条映射记录"); } catch (IOException e) { System.err.println("✗ 读取文件失败: " + e.getMessage()); mapping = getDefaultMapping(); System.out.println("使用默认映射数据"); } } catch (Exception e) { System.err.println("✗ 加载配置文件异常: " + e.getMessage()); e.printStackTrace(); mapping = getDefaultMapping(); } } else { System.out.println("✗ 配置文件不存在: " + CONFIG_FILE_PATH); mapping = getDefaultMapping(); System.out.println("使用默认映射数据"); // 创建默认配置文件 createDefaultConfigFile(); } return mapping; } /** * 创建默认配置文件 */ private void createDefaultConfigFile() { try { File configFile = new File(CONFIG_FILE_PATH); File parentDir = configFile.getParentFile(); System.out.println("尝试创建配置文件: " + CONFIG_FILE_PATH); System.out.println("父目录: " + (parentDir != null ? parentDir.getAbsolutePath() : "null")); // 确保目录存在 if (parentDir != null && !parentDir.exists()) { boolean created = parentDir.mkdirs(); System.out.println("创建配置目录: " + (created ? "成功" : "失败")); } // 创建配置文件 Properties props = new Properties(); Map defaultMap = getDefaultMapping(); for (Map.Entry entry : defaultMap.entrySet()) { props.setProperty(entry.getKey(), entry.getValue()); } try (FileOutputStream fos = new FileOutputStream(configFile); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8")) { props.store(osw, "设备类型映射表\n# 英文键名 = 中文名称"); System.out.println("✓ 已创建默认配置文件: " + CONFIG_FILE_PATH); System.out.println("文件大小: " + configFile.length() + " bytes"); } catch (IOException e) { System.err.println("✗ 创建配置文件失败: " + e.getMessage()); e.printStackTrace(); } } catch (Exception e) { System.err.println("✗ 创建配置文件异常: " + e.getMessage()); e.printStackTrace(); } } /** * 创建配置文件工具方法(可单独调用) */ public void createConfigFile() { createDefaultConfigFile(); } /** * 从指定路径加载映射文件 */ public Map loadMappingFromSpecificFile(String filePath) { Map mapping = new HashMap<>(); try { Properties props = new Properties(); try (FileInputStream fis = new FileInputStream(filePath); InputStreamReader isr = new InputStreamReader(fis, "UTF-8")) { props.load(isr); for (String key : props.stringPropertyNames()) { mapping.put(key.trim(), props.getProperty(key).trim()); } System.out.println("从指定文件加载了 " + mapping.size() + " 条映射记录"); } catch (IOException e) { System.err.println("读取指定文件失败: " + e.getMessage()); } } catch (Exception e) { System.err.println("加载指定文件异常: " + e.getMessage()); } return mapping; } /** * 默认映射数据(当文件不存在时使用) */ private Map getDefaultMapping() { Map defaultMap = new HashMap<>(); defaultMap.put("SmallWalkInTestChamber", "小型步入式试验箱"); defaultMap.put("LargeWalkInTestChamber", "大型步入式试验箱(大舱)"); defaultMap.put("TemperatureAndHumidityChamber", "恒温恒湿箱"); defaultMap.put("HighAndLowTemperatureChamber", "高低温箱"); defaultMap.put("RackBox", "台架箱"); defaultMap.put("RapidTemperatureChange", "快温变"); defaultMap.put("TwoImpactBoxes", "两箱冲击箱"); defaultMap.put("ThreeImpactBoxes", "三箱冲击箱"); defaultMap.put("ThreeComprehensiveBoxes", "三箱综合"); defaultMap.put("DirectCoolingMachine", "直冷机"); defaultMap.put("Chiller", "冷水机"); defaultMap.put("Other", "其它"); return defaultMap; } private String generateSimpleJson(List items) { try { ObjectMapper mapper = new ObjectMapper(); ArrayNode array = mapper.createArrayNode(); for (DeviceItem item : items) { ObjectNode node = mapper.createObjectNode(); node.put("id", item.getId()); node.put("name", item.getName()); node.put("description", item.getDescription()); array.add(node); } return mapper.writeValueAsString(array); } catch (Exception e) { System.err.println("生成JSON失败: " + e.getMessage()); return "[]"; } } class DeviceItem { private int id; private String name; private String description; // getters and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } }