List of usage examples for org.dom4j Document getRootElement
Element getRootElement();
From source file:cn.com.sunjiesh.wechat.helper.WechatMessageConvertDocumentHelper.java
/** * ??XML//from w ww . j av a2 s . c o m * @param messageResponse * @return */ public static Document voiceMessageResponseToDocumnet(WechatReceiveReplayVoiceMessageResponse messageResponse) { final String toUserName = messageResponse.getToUserName(); final String fromUserName = messageResponse.getFromUserName(); final String msgType = messageResponse.getMsgType(); Document respDoc = initRespDoc(toUserName, fromUserName, msgType); Element voiceEle = respDoc.getRootElement().addElement("Voice"); Element mediaIdEle = voiceEle.addElement("MediaId"); mediaIdEle.setText(messageResponse.getMediaId()); return respDoc; }
From source file:cn.com.sunjiesh.wechat.helper.WechatMessageConvertDocumentHelper.java
/** * ???XML/*from w w w. j a v a 2 s .co m*/ * * @param messageResponse ? * @return XML */ public static Document newsMessageResponseToDocument(WechatReceiveReplayNewsMessageResponse messageResponse) { final String toUserName = messageResponse.getToUserName(); final String fromUserName = messageResponse.getFromUserName(); final String msgType = messageResponse.getMsgType(); Document respDoc = initRespDoc(toUserName, fromUserName, msgType); Element rootEle = respDoc.getRootElement(); Element articleCountEle = rootEle.addElement("ArticleCount"); Element articlesEle = rootEle.addElement("Articles"); messageResponse.getItemList().stream().forEach((item) -> { Element itemEle = articlesEle.addElement("item"); if (!StringUtils.isEmpty(item.getTitle())) { Element titleEle = itemEle.addElement("Title"); titleEle.setText(item.getTitle()); } if (!StringUtils.isEmpty(item.getDescription())) { Element descriptionEle = itemEle.addElement("Description"); descriptionEle.setText(item.getDescription()); } if (!StringUtils.isEmpty(item.getPicUrl())) { Element picUrlEle = itemEle.addElement("PicUrl"); picUrlEle.setText(item.getPicUrl()); } if (!StringUtils.isEmpty(item.getUrl())) { Element urlEle = itemEle.addElement("Url"); urlEle.setText(item.getUrl()); } }); articleCountEle.setText(String.valueOf(messageResponse.getItemList().size())); return respDoc; }
From source file:cn.com.xdays.xshop.action.admin.InstallAction.java
public String save() throws URISyntaxException, IOException, DocumentException { if (isInstalled()) { return ajaxJsonErrorMessage("SHOP++?????"); }/* www . j a v a 2s . c o m*/ if (StringUtils.isEmpty(databaseHost)) { return ajaxJsonErrorMessage("?!"); } if (StringUtils.isEmpty(databasePort)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(databasePassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseName)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminPassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(installStatus)) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "requiredCheckFinish"); return ajaxJson(jsonMap); } String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName + "?useUnicode=true&characterEncoding=UTF-8"; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { Class.forName("com.mysql.jdbc.Driver"); // ? connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword); DatabaseMetaData databaseMetaData = connection.getMetaData(); String[] types = { "TABLE" }; resultSet = databaseMetaData.getTables(null, databaseName, "%", types); if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "databaseCheckFinish"); return ajaxJson(jsonMap); } // ? if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) { StringBuffer stringBuffer = new StringBuffer(); BufferedReader bufferedReader = null; String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + SQL_INSTALL_FILE_NAME; bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8")); String line = ""; while (null != line) { line = bufferedReader.readLine(); stringBuffer.append(line); if (null != line && line.endsWith(";")) { System.out.println("[SHOP++?]SQL: " + line); preparedStatement = connection.prepareStatement(stringBuffer.toString()); preparedStatement.executeUpdate(); stringBuffer = new StringBuffer(); } } String insertAdminSql = "INSERT INTO `admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','" + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');"; String insertAdminRoleSql = "INSERT INTO `admin_role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');"; preparedStatement = connection.prepareStatement(insertAdminSql); preparedStatement.executeUpdate(); preparedStatement = connection.prepareStatement(insertAdminRoleSql); preparedStatement.executeUpdate(); } } catch (Exception e) { e.printStackTrace(); return ajaxJsonErrorMessage("???!"); } finally { try { if (resultSet != null) { resultSet.close(); resultSet = null; } if (preparedStatement != null) { preparedStatement.close(); preparedStatement = null; } if (connection != null) { connection.close(); connection = null; } } catch (SQLException e) { e.printStackTrace(); } } // ??? String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + JDBC_CONFIG_FILE_NAME; Properties properties = new Properties(); properties.put("jdbc.driver", "com.mysql.jdbc.Driver"); properties.put("jdbc.url", jdbcUrl); properties.put("jdbc.username", databaseUsername); properties.put("jdbc.password", databasePassword); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); properties.put("hibernate.show_sql", "false"); properties.put("hibernate.format_sql", "false"); OutputStream outputStream = new FileOutputStream(configFilePath); properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION); outputStream.close(); // ?? String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + BACKUP_WEB_CONFIG_FILE_NAME; String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String webConfigFilePath = new File( Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/" + WEB_CONFIG_FILE_NAME; String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("") .toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME; String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath)); FileUtils.copyFile(new File(backupApplicationContextConfigFilePath), new File(applicationContextConfigFilePath)); FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath), new File(compassApplicationContextConfigFilePath)); FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath), new File(securityApplicationContextConfigFilePath)); // ?? String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + SystemConfigUtil.CONFIG_FILE_NAME; File systemConfigFile = new File(systemConfigFilePath); SAXReader saxReader = new SAXReader(); Document document = saxReader.read(systemConfigFile); Element rootElement = document.getRootElement(); Element systemConfigElement = rootElement.element("systemConfig"); Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled"); if (isInstalledNode == null) { isInstalledNode = systemConfigElement.addElement("isInstalled"); } isInstalledNode.setText("true"); try { OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML? outputFormat.setEncoding("UTF-8");// XML? outputFormat.setIndent(true);// ? outputFormat.setIndent(" ");// TAB? outputFormat.setNewlines(true);// ?? XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat); xmlWriter.write(document); xmlWriter.close(); } catch (Exception e) { e.printStackTrace(); } return ajaxJsonSuccessMessage("SHOP++?????"); }
From source file:cn.fql.springcontainer.ioc.BeanContext.java
License:Open Source License
public BeanContext() throws Exception { SAXBuilder builder = new SAXBuilder(); Document document = builder.build(this.getClass().getClassLoader().getResource("resource/beans.xml")); Element root = document.getRootElement(); List<Element> list = root.getChildren("bean"); // beanElement for (int i = 0; i < list.size(); i++) { Element element = (Element) list.get(i); String id = element.getAttributeValue("id"); String clazz = element.getAttributeValue("class"); System.out.println(id + " : " + clazz); Object obj = Class.forName(clazz).newInstance(); // 1th.Bean beans.put(id, obj);/*from w w w . j a v a 2 s . c o m*/ /** * <bean id="u" class="com.hzy.dao.impl.UserDAOImpl"/> <bean id="userService" class="com.hzy.service.UserService"> <property name="userDAO" bean="u"/> </bean> */ // 2th.? // property for (Element propertyElement : (List<Element>) element.getChildren("property")) { String name = propertyElement.getAttributeValue("name"); // userDAO String injectBean = propertyElement.getAttributeValue("bean"); // u; Object propertyObj = beans.get(injectBean); // 3th.userService userDAO setter // name.substring( 0, 1 ).toUpperCase() u ?? String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); System.out.println("method name = " + methodName); /** * getMethod ..?? ?? * Returns a Method object that reflects the specified * public member method of the class or interface represented by this Class object. */ Method m = obj.getClass().getMethod(methodName, propertyObj.getClass().getInterfaces()); // 4th. m.invoke(obj, propertyObj); } } }
From source file:cn.ict.zyq.bestConf.util.ParseXMLToYaml.java
License:Open Source License
public static HashMap parseXMLToHashmap(String filePath) { HashMap result = new HashMap(); try {// w w w . j a v a 2 s . c o m File f = new File(filePath); SAXReader reader = new SAXReader(); Document doc = reader.read(f); Element root = doc.getRootElement(); Element foo; for (Iterator i = root.elementIterator("property"); i.hasNext();) { foo = (Element) i.next(); String value; if (foo.elementText("value") != null) { value = foo.elementText("value"); Pattern pattern = Pattern.compile("^-?[0-9]\\d*$"); Matcher matcher = pattern.matcher(value); if (matcher.find()) { result.put(foo.elementText("name"), value); } else if (Pattern.compile("^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)$").matcher(value) .find()) { result.put(foo.elementText("name"), value); } else { } } } } catch (Exception e) { e.printStackTrace(); } return result; }
From source file:cn.ict.zyq.bestConf.util.ParseXMLToYaml.java
License:Open Source License
public static void appendXMLByDOM4J(HashMap target, String source, String destination) throws IOException { SAXReader reader = new SAXReader(); try {// w ww .j av a 2 s .c o m Document document = reader.read(new File(source)); Element configStore = document.getRootElement(); Iterator iter = target.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String key = entry.getKey().toString(); String val = entry.getValue().toString(); Element property = configStore.addElement("property"); Element name = property.addElement("name"); name.setText(key); Element value = property.addElement("value"); value.setText(val); } OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileOutputStream(destination), format); writer.write(document); writer.close(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:cn.kee.engine.common.SystemInitServlet.java
/** * *//*from w ww. ja v a2s . c o m*/ private void changeReportConfig(PropertiesFactory pf) { File config_file = new File(getClassPath(), "reportConfig.xml"); Document doc = readerDom(config_file); Element root = doc.getRootElement(); //home Node oCfg = root.selectSingleNode("config[name='reportFileHome']/value"); if (pf.getParam("reportFileHome") != null) { oCfg.setText(pf.getParam("reportFileHome")); File file = new File(pf.getParam("reportFileHome")); if (!file.exists()) { file.mkdirs(); } } //license Node license = root.selectSingleNode("config[name='license']/value"); if (pf.getParam("license") != null) { license.setText(pf.getParam("license")); } writeConfig(doc.asXML(), config_file); }
From source file:com.aesirteam.smep.adc.message.CorpBindReq.java
@SuppressWarnings("unchecked") public CorpBindReq(String msg) throws Exception { MsgRequest request = new MsgRequest(msg); //??/*from ww w .j a v a 2 s .c o m*/ this.header = request.getHeader(); //?? String bodyText; if (null == (bodyText = request.getBody())) { throw new Exception("CorpBindReq??"); } try { Document document = DocumentHelper.parseText(bodyText); Element root = document.getRootElement(); this.corpName = root.element("CORPNAME").getTextTrim(); this.corpAccount = root.element("CORPACCOUNT").getTextTrim(); this.license = root.element("LICENSE").getTextTrim(); this.optype = root.element("OPTYPE").getTextTrim(); this.opnote = root.element("OPNOTE").getTextTrim(); //PARAMMAP paramMap = new HashMap<String, String>(); if (null != root.element("PARAMLIST").element("PARAMMAP")) { for (Iterator<Element> it = root.element("PARAMLIST").elementIterator("PARAMMAP"); it.hasNext();) { Element e = it.next(); String name = e.element("PARAMNAME").getTextTrim(); String value = e.element("PARAMVALUE").getTextTrim(); if (0 < name.length() && 0 < value.length()) paramMap.put(name, value); } } //CORPINFOMAP corpInfoMap = new HashMap<String, String>(); if (null != root.element("CORPINFOLIST").element("CORPINFOMAP")) { for (Iterator<Element> it = root.element("CORPINFOLIST").elementIterator("CORPINFOMAP"); it .hasNext();) { Element e = it.next(); String name = e.element("CORPINFONAME").getTextTrim(); String value = e.element("CORPINFOVALUE").getTextTrim(); if (0 < name.length() && 0 < value.length()) { corpInfoMap.put(name, value); if ("CORP_SHORTNAME".equals(name)) this.corpShortName = value; else if ("CORP_LINKMAN".equals(name)) this.corpLinkMan = value; else if ("CORP_LINKPHONE".equals(name)) this.corpLinkPhone = value; else if ("CORP_LINKMOBILE".equals(name)) this.corpLinkMobile = value; } } } //ORDERPOINTMAP orderPointMap = new HashMap<String, String>(); int count = 1; if (null != root.element("POINTLIST").element("ORDERPOINTMAP")) { for (Iterator<Element> it = root.element("POINTLIST").elementIterator("ORDERPOINTMAP"); it .hasNext();) { Element e = it.next(); String name = e.element("POINTNAME").getTextTrim(); String value = e.element("POINTVALUE").getTextTrim(); if (0 < name.length() && 0 < value.length()) { orderPointMap.put(name, value); this.point = (count == 1) ? name : String.format("%s,%s", point, name); count++; } } } } catch (Exception ex) { throw new Exception(ex.getMessage()); } }
From source file:com.ah.be.ls.stat.StatManager.java
private static List<StatConfig> readStatConfig() { if (stats != null && !stats.isEmpty()) { return stats; }// w w w . j ava2 s . com stats = new ArrayList<StatConfig>(); // read from stat-config.xml SAXReader reader = new SAXReader(); File ff = new File(System.getenv("HM_ROOT") + "/resources/stat-config.xml"); if (!ff.exists()) { // for test ff = new File("stat-config.xml"); } try { Document doc = reader.read(ff); Element roota = doc.getRootElement(); log.info("StatManager", "roota..nodcount=" + roota.nodeCount()); Iterator<?> iters = roota.elementIterator("feature"); while (iters.hasNext()) { StatConfig stat = new StatConfig(); Element foo = (Element) iters.next(); if (foo.attribute("ignore") != null) { continue; } stat.setFeatureId(Integer.valueOf(foo.attributeValue("id"))); stat.setFeatureName(foo.attributeValue("name")); Element e2 = foo.element("bo-class"); Element e4 = foo.element("search-rule"); stat.setBoClassName(e2.attributeValue("name")); stat.setSearchRule(e4.attributeValue("value")); stat.setSearchType(e4.attributeValue("type")); stats.add(stat); } return stats; } catch (ClassNotFoundException e) { log.error("StatManager", "readStatConfig: ClassNotFoundException", e); } catch (Exception e) { log.error("StatManager", "readStatConfig: Exception", e); } return null; }
From source file:com.ah.be.parameter.BeParaModuleDefImpl.java
private void changeOsVersionFile() { String fingerprints = ImportTextFileAction.OS_VERSION_FILE_PATH + ImportTextFileAction.OS_VERSION_FILE_NAME; String fingerprintsChg = ImportTextFileAction.OS_VERSION_FILE_PATH + ImportTextFileAction.OS_VERSION_FILE_NAME_CHG; FileWriter fWriter = null;// www.j a v a 2 s .c o m try { if (new File(fingerprints).exists() && new File(fingerprintsChg).exists()) { List<String> lines = NmsUtil.readFileByLines(fingerprints); List<String> replaceOsName = new ArrayList<>(); List<String> replaceOption55 = new ArrayList<>(); String preHmVer = NmsUtil.getHiveOSVersion(NmsUtil .getVersionInfo(BeAdminCentOSTools.ahBackupdir + File.separatorChar + "hivemanager.ver")); // parse os_dhcp_fingerprints_changes.xml SAXReader reader = new SAXReader(); Document document = reader.read(new File(fingerprintsChg)); Element root = document.getRootElement(); List<?> fingerprintElems = root.elements(); for (Object obj : fingerprintElems) { Element fingerprintElem = (Element) obj; String osName = fingerprintElem.attributeValue("osname"); for (Iterator<?> iterator = fingerprintElem.elementIterator(); iterator.hasNext();) { Element option55Elem = (Element) iterator.next(); String node_option55_text = option55Elem.getText(); Attribute version = option55Elem.attribute("version"); String version_text = version.getText(); if (NmsUtil.compareSoftwareVersion(preHmVer, version_text) <= 0) { if (!replaceOption55.contains(node_option55_text)) { replaceOsName.add(osName); replaceOption55.add(node_option55_text); } } } } if (replaceOption55.isEmpty()) { log.debug("No need to modify os_dhcp_fingerprints.txt."); FileUtils.deleteQuietly(new File(fingerprintsChg)); return; } for (String option55 : replaceOption55) { int size = lines.size(); boolean remove = false; for (int i = size - 1; i >= 0; i--) { if (remove) { lines.remove(i); remove = false; } else { if (option55.equals(lines.get(i))) { if (i < size - 1 && i > 0 && lines.get(i - 1).startsWith(ImportTextFileAction.OS_STR) && lines.get(i + 1).equals(ImportTextFileAction.END_STR)) { lines.remove(i + 1); lines.remove(i); remove = true; } else { lines.remove(i); } } } } } //insert for (int i = 0; i < replaceOption55.size(); i++) { String option55 = replaceOption55.get(i); String osName = ImportTextFileAction.OS_STR + replaceOsName.get(i); if (!lines.contains(option55)) { if (lines.contains(osName)) { List<String> temp = lines.subList(lines.indexOf(osName), lines.size()); int index = lines.indexOf(osName) + temp.indexOf(ImportTextFileAction.END_STR); lines.add(index, option55); } else { lines.add(osName); lines.add(option55); lines.add(ImportTextFileAction.END_STR); } } } fWriter = new FileWriter(fingerprints, false); for (String line : lines) { if (line != null && line.startsWith(ImportTextFileAction.VERSION_STR)) { String version = line.substring(line.indexOf(ImportTextFileAction.VERSION_STR) + ImportTextFileAction.VERSION_STR.length()); BigDecimal b1 = new BigDecimal(version); BigDecimal b2 = new BigDecimal("0.1"); float fVer = b1.add(b2).floatValue(); String versionStr = ImportTextFileAction.VERSION_STR + String.valueOf(fVer) + "\r\n"; fWriter.write(versionStr); } else { fWriter.write(line + "\r\n"); } } fWriter.close(); //compress file String strCmd = ""; StringBuffer strCmdBuf = new StringBuffer(); strCmdBuf.append("tar zcvf "); strCmdBuf.append( ImportTextFileAction.OS_VERSION_FILE_PATH + ImportTextFileAction.OS_VERSION_FILE_NAME_TAR); strCmdBuf.append(" -C "); strCmdBuf.append(ImportTextFileAction.OS_VERSION_FILE_PATH); strCmdBuf.append(" " + ImportTextFileAction.OS_VERSION_FILE_NAME); strCmd = strCmdBuf.toString(); boolean compressResult = BeAdminCentOSTools.exeSysCmd(strCmd); if (!compressResult) { log.error("compress os_dhcp_fingerprints.txt error."); return; } FileUtils.deleteQuietly(new File(fingerprintsChg)); } else { if (new File(fingerprintsChg).exists()) { FileUtils.deleteQuietly(new File(fingerprintsChg)); } } } catch (Exception e) { setDebugMessage("change OsVersionFile error: ", e); } finally { if (fWriter != null) { try { fWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } }