public static String setGraphXml(String sourceNode, Map<String, String> map, String xml) throws IOException { Document doc = Dom4jUtil.loadXml(xml); Element root = doc.getRootElement(); Element node = (Element) root.selectSingleNode("//bg:Gateway[@id='" + sourceNode + "']"); Element portsEl = node.element("ports"); List portList = portsEl.elements(); for (int i = 0; i < portList.size(); i++) { Element portEl = (Element) portList.get(i); if ((portEl.attribute("x") != null) || (portEl.attribute("y") != null)) { String id = portEl.attributeValue("id"); Element outNode = (Element) root.selectSingleNode("//bg:SequenceFlow[@startPort='" + id + "']"); if (outNode != null) { String outPort = outNode.attributeValue("endPort"); Element tmpNode = (Element) root.selectSingleNode("//ciied:Port[@id='" + outPort + "']"); Element taskNode = tmpNode.getParent().getParent(); String taskId = taskNode.attributeValue("id"); Element conditionEl = outNode.element("condition"); if (conditionEl != null) { outNode.remove(conditionEl); } if (map.containsKey(taskId)) { String condition = (String) map.get(taskId); Element elAdd = outNode.addElement("condition"); elAdd.addText(condition); } } } } return doc.asXML(); }
/** Adds the test to the suite report given an XML test document */ public void addTest(Document test) { Element root = test.getRootElement(); // Add to the number of tests in this suite if not seen and not null String testMethod = root.attributeValue(NAME_ATTRIBUTE); if (!recordedRuns.contains(testMethod) && !testMethod.equals("null")) { recordedRuns.add(testMethod); suite.addTest(); } // add test time to total time long time = Long.parseLong(root.attributeValue(TIME_ATTRIBUTE)); suite.addTime(time); root.attribute(TIME_ATTRIBUTE).setText(formatTime(time)); // If the test method name is null, then make it the classname if (root.attributeValue(NAME_ATTRIBUTE).equals("null")) { root.attribute(NAME_ATTRIBUTE).setText(root.attributeValue(CLASSNAME_ATTRIBUTE)); } // Add the test to the report document document.getRootElement().add(root); // Check for special status adjustments to make to suite checkForStatus(test); // remove status attribute since it's only used by the report root.remove(root.attribute(STATUS_ATTRIBUTE)); }
/** * 生成sel的document * * @param normalName normal普通状态的图片名 * @param specialName 特殊状态(pressed按下/checked选中)的图片名 * @param end 特殊状态(pressed按下/checked选中)后缀名 * @return */ public static Document createSelector(String normalName, String specialName, String end) { Document doc = XmlUtil.read("res\\drawable\\sel.xml"); Element rootElement = doc.getRootElement(); List<Element> elements = XmlUtil.getAllElements(doc); for (Element element : elements) { Attribute attr = element.attribute("drawable"); if (attr == null) { continue; } String value = attr.getStringValue(); if (value.contains(end)) { // 替换特殊状态(pressed/checked)的item加后缀 value = value.replace(end, specialName); attr.setValue(value); } else if (element.attributeCount() > 1) { // 移除不需要的element rootElement.remove(element); } else { // normal状态的item不加后缀 value = value.replace("normal", normalName); attr.setValue(value); } } return doc; }
/** * 修改XML文件中内容,并另存为一个新文件 重点掌握dom4j中如何添加节点,修改节点,删除节点 * * @param filename 修改对象文件 * @param newfilename 修改后另存为该文件 * @return 返回操作结果, 0表失败, 1表成功 */ public int modifyXMLFile(String filename, String newfilename) { int returnValue = 0; SAXReader saxReader = new SAXReader(); Document doc = null; try { /** 修改内容之一:如果book节点中show参数的内容为yes,则修改成no */ /** 先用xpath查找对象 */ doc = saxReader.read(new File(filename)); List list = doc.selectNodes("/books/book/@show"); Iterator iter = list.iterator(); while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); if ("yes".equals(attr.getValue())) { attr.setValue("no"); } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } /** 修改内容之二:把owner项内容改为Tshinghua 并在owner节点中加入date节点,date节点的内容为2004-09-11,还为date节点添加一个参数type */ List list = doc.selectNodes("/books/owner"); Iterator iter = list.iterator(); if (iter.hasNext()) { Element ownEle = (Element) iter.next(); ownEle.setText("Tshinghua"); Element dateEle = ownEle.addElement("date"); dateEle.setText("2012-12-17"); dateEle.addAttribute("type", "Gregorian calendar"); } /** 修改内容之三:若title内容为Dom4j Tutorials,则删除该节点 */ List list2 = doc.selectNodes("/books/book"); Iterator iter2 = list2.iterator(); while (iter2.hasNext()) { Element bookEle = (Element) iter2.next(); Iterator iterator = bookEle.elementIterator("title"); while (iterator.hasNext()) { Element titleElement = (Element) iterator.next(); if (titleElement.getText().equals("Dom4j Tutorials")) { bookEle.remove(titleElement); } } } try { /** 将document中的内容写入文件中 */ XMLWriter writer = new XMLWriter(new FileWriter(new File(newfilename))); writer.write(doc); writer.close(); /** 执行成功,需返回1 */ returnValue = 1; } catch (Exception ex) { ex.printStackTrace(); } return returnValue; }
/** * Sets the packet error. Calling this method will automatically set the packet "type" attribute * to "error". * * @param error the packet error. */ public void setError(PacketError error) { if (element == null) { throw new NullPointerException("Error cannot be null"); } // Force the packet type to "error". element.addAttribute("type", "error"); // Remove an existing error packet. if (element.element("error") != null) { element.remove(element.element("error")); } // Add the error element. element.add(error.getElement()); }
// Logs a new entry in the library RSS file public static synchronized void addRSSEntry( String title, String link, String description, File rssFile) { // File rssFile=new File("nofile.xml"); try { System.out.println("Looking for RSS file: " + rssFile.getCanonicalPath()); if (rssFile.exists()) { SAXReader reader = new SAXReader(); Document document = reader.read(rssFile); Element root = document.getRootElement(); Element channel = root.element("channel"); List items = channel.elements("item"); int numItems = items.size(); items = null; if (numItems > 9) { Element removeThisItem = channel.element("item"); channel.remove(removeThisItem); } Element newItem = channel.addElement("item"); Element newTitle = newItem.addElement("title"); Element newLink = newItem.addElement("link"); Element newDescription = newItem.addElement("description"); newTitle.setText(title); newDescription.setText(description); newLink.setText(link); Element pubDate = channel.element("pubDate"); pubDate.setText((new java.util.Date()).toString()); // now save changes FileWriter mywriter = new FileWriter(rssFile); OutputFormat format = OutputFormat.createPrettyPrint(); format.setLineSeparator(System.getProperty("line.separator")); XMLWriter writer = new XMLWriter(mywriter, format); writer.write(document); writer.close(); } } catch (IOException ioe) { System.out.println("ERROR: Could not find the RSS file."); ioe.printStackTrace(); } catch (DocumentException de) { System.out.println("ERROR: Could not read the RSS file."); de.printStackTrace(); } catch (Exception e) { System.out.println("Unknown exception trying to add an entry to the RSS file."); e.printStackTrace(); } }
private static void delNode(String qbPath, String type, HashMap<String, String> map) { leidaEle = doc.getRootElement().element("雷达"); esmEle = doc.getRootElement().element("esm"); String zhanhao = map.get("站号"); if (type.equals("radar")) { boolean flag = isZhanHaoExist(type, map); if (!flag) { System.out.println("删除节点失败"); return; } List list = doc.selectNodes("root/雷达/模拟器"); Iterator iter = list.iterator(); while (iter.hasNext()) { Element delEle = (Element) iter.next(); if (delEle.attribute("站号").getValue().equals(zhanhao)) { leidaEle.remove(delEle); } } } if (type.equals("esm")) { boolean flag = isZhanHaoExist(type, map); if (!flag) { System.out.println("删除节点失败"); return; } List list = doc.selectNodes("root/esm/模拟器"); Iterator iter = list.iterator(); while (iter.hasNext()) { Element delEle = (Element) iter.next(); if (delEle.attribute("站号").getValue().equals(zhanhao)) { esmEle.remove(delEle); } } } writeXml(doc, qbPath); System.out.println("成功删除" + type + " 站号为 " + zhanhao + " 的模拟器"); }
/** * Returns a Document representation of a Hibernate configuration file with the mapping elements * removed. * * @param hibernateConfigurationResoruce the Hibernate configuration file * @return a org.dom4j.Document representing the Hibernate configuration * @throws DocumentException if an Exception occurs while manipulating the XML document */ public static Document removeMappingElements(String hibernateConfigurationResoruce) throws DocumentException { Document d = XmlUtil.parse(HibernateUtil.class.getResource(hibernateConfigurationResoruce)); Element root = d.getRootElement(); Element sessionFactory = root.element("session-factory"); List mappingElements = sessionFactory.elements("mapping"); for (Object element : mappingElements) { if (element instanceof Element) { sessionFactory.remove((Element) element); } } return d; }
/** * 方法名: </br> 详述: </br>修改版本号和package 开发人员:谭明</br> 创建时间:Apr 1, 2014</br> * * @param pageName * @param project_path * @throws Exception */ public static void update_AndroidManifest_xml( String project_path, String enterpriseId, String appId, String appKey) throws Exception { File file = new File(project_path + File.separator + "AndroidManifest.xml"); String pageName = "app" + enterpriseId; String package_value = "com.cndatacom." + pageName; if (!file.exists()) { throw new Exception("项目AndroidManifest.xml文件不存在!"); } Document doc = null; try { doc = new SAXReader().read(file); Element root = doc.getRootElement(); root.setAttributeValue("package", package_value); logger.info("修改后的AndroidManifest.xml文件::" + doc.asXML()); List<Element> elementList = root.element("application").elements("meta-data"); for (Element childElement : elementList) { List<Attribute> aList = childElement.attributes(); String name = ""; Attribute a = null; for (Attribute attribute : aList) { String attributeName = attribute.getName(); if ("value".equals(attributeName)) { a = attribute; } else if ("name".equals(attributeName)) { name = attribute.getValue(); } } childElement.remove(a); if ("app_info".equals(name)) childElement.setAttributeValue("android:value", appId); else if ("app_key".equals(name)) childElement.setAttributeValue("android:value", appKey); } } catch (DocumentException e) { e.printStackTrace(); throw new Exception("读取项目AndroidManifest.xml文件出错!"); } try { XMLWriter writer = new XMLWriter(new FileOutputStream(file)); writer.write(doc); writer.close(); } catch (Exception e) { throw new Exception("输出项目AndroidManifest.xml文件出错!"); } }
/** * 自动生成shape(只考虑shape,corner,stroke,solid参数) * * @param shape 形状,一共有四种:rectangle矩形,oval圆,line线,ring环 * @param cornersRadius 圆角边半径,需要带单位,比如4dp * @param strokeWidth 边线宽度,需要带单位,比如1px(stroke为可选,不要边线时传入空即可) * @param strokeColor 边线颜色(可以是#ARGB或者是@color/颜色名) * @param solidColor 填充颜色(可以是#ARGB或者是@color/颜色名) * @return */ public static Document createShape( String shape, String cornersRadius, String strokeWidth, String strokeColor, String solidColor) { // <?xml version="1.0" encoding="utf-8"?> // <shape xmlns:android="http://schemas.android.com/apk/res/android" // android:shape="rectangle" > // // <corners android:radius="4dp" /> // // <stroke // android:width="1px" // android:color="@color/white" /> // // <solid android:color="@color/transparent" /> // // </shape> Document doc = XmlUtil.read("res\\drawable\\shape_correct.xml"); Element rootElement = doc.getRootElement(); rootElement.attribute("shape").setValue(shape); Element cornerElement = rootElement.element("corners"); cornerElement.attribute("radius").setValue(cornersRadius); Element strokeElement = rootElement.element("stroke"); if (strokeWidth == null || strokeWidth.length() == 0) { rootElement.remove(strokeElement); } else { strokeElement.attribute("width").setValue(strokeWidth); strokeElement.attribute("color").setValue(strokeColor); } Element solidElement = rootElement.element("solid"); solidElement.attribute("color").setValue(solidColor); return doc; }
public void setMap(Map map) { Element element = DocumentHelper.createElement(namespace); final Iterator i = element.elementIterator(); while (i.hasNext()) { element.remove((Element) i.next()); } final Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); String value = (String) map.get(key); Element elem = DocumentHelper.createElement("entry"); elem.addElement(key).setText(value); element.add(elem); } try { workgroupSettings.add(workgroup.getJID().toBareJID(), element); } catch (Exception ex) { Log.error(ex.getMessage(), ex); } }
/** * Loads the vCard using the LDAP vCard Provider and re-adds the avatar from the database. * * @param username * @return LDAP vCard re-added avatar element */ synchronized Element mergeAvatar(String username, Element vcardFromSipX, Element vcardFromDB) { logger.info("merge avatar for user '" + username + "' ..."); // get the vcard from ldap // Element vCardElement = super.loadVCard(username); // only add avatar if it doesn't exist already if (vcardFromDB != null && vcardFromDB.element(AVATAR_ELEMENT) != null) { Element avatarElement = getAvatarCopy(vcardFromDB); if (avatarElement != null) { if (getAvatar(vcardFromSipX) != null) { vcardFromSipX.remove(getAvatar(vcardFromSipX)); } vcardFromSipX.add(avatarElement); logger.info("Avatar merged from DB into sipX vCard"); } else { logger.info("No vCard found in database"); } } return vcardFromSipX; }
/** * 修改XML文件中内容,并另存为一个新文件 重点掌握dom4j中如何添加节点,修改节点,删除节点 * * @param filename 修改对象文件 * @param newfilename 修改后另存为该文件 * @return 返回操作结果, 0表失败, 1表成功 */ public int modiXMLFile(String filename, String newfilename) { int returnValue = 0; try { SAXReader saxReader = new SAXReader(); Document document = saxReader.read(new java.io.File(filename)); /** 修改内容之一: 如果book节点中show属性的内容为yes,则修改成no */ /** 先用xpath查找对象 */ List list = document.selectNodes("/books/book/@show"); Iterator iter = list.iterator(); while (iter.hasNext()) { Attribute attribute = (Attribute) iter.next(); if (attribute.getValue().equals("yes")) { attribute.setValue("no"); } } /** 修改内容之二: 把owner项内容改为"测试修改" 并在owner节点中加入date节点,date节点的内容为2004-09-11,还为date节点添加一个属性type */ list = document.selectNodes("/books/owner"); iter = list.iterator(); if (iter.hasNext()) { Element ownerElement = (Element) iter.next(); ownerElement.setText("测试修改"); Element dateElement = ownerElement.addElement("date"); dateElement.setText("2008-09-11"); dateElement.addAttribute("type", "日期"); } /** 修改内容之三: 若title内容为Dom4j Tutorials,则删除该节点 */ list = document.selectNodes("/books/book"); iter = list.iterator(); while (iter.hasNext()) { Element bookElement = (Element) iter.next(); Iterator iterator = bookElement.elementIterator("title"); while (iterator.hasNext()) { Element titleElement = (Element) iterator.next(); if (titleElement.getText().equals("Dom4j Tutorials")) { bookElement.remove(titleElement); } } } try { /** 格式化输出,类型IE浏览一样 */ OutputFormat format = OutputFormat.createPrettyPrint(); /** 指定XML编码 */ // format.setEncoding("GBK"); /** 将document中的内容写入文件中 */ // XMLWriter writer = new XMLWriter(new FileWriter(new // File(newfilename)),format); // 保证编码为UTF-8,支持中文写入 XMLWriter writer = new XMLWriter(new FileOutputStream(new File(newfilename)), format); writer.write(document); writer.close(); /** 执行成功,需返回1 */ returnValue = 1; } catch (Exception ex) { ex.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } return returnValue; }
public void save() { String siteID = String.valueOf(Application.getCurrentSiteID()); SAXReader sax = new SAXReader(); Document doc = null; try { String configXML = new QueryBuilder("select ConfigXML from zcsite where id = ?", siteID).executeString(); StringReader reader = new StringReader(configXML); doc = sax.read(reader); } catch (DocumentException e1) { this.Response.setLogInfo(0, "保存失败"); e1.printStackTrace(); return; } Element root = doc.getRootElement(); Element ImageLibConfig = root.element("ImageLibConfig"); if (ImageLibConfig != null) { root.remove(ImageLibConfig); } ImageLibConfig = root.addElement("ImageLibConfig"); ImageLibConfig.addComment("原图水印"); Element WaterMark = ImageLibConfig.addElement("WaterMark") .addAttribute("HasWaterMark", ($V("HasWaterMark") == null) ? "0" : $V("HasWaterMark")) .addAttribute("WaterMarkType", $V("WaterMarkType")) .addAttribute("Position", $V("Position")); WaterMark.addElement("Image").addAttribute("src", $V("Image")); WaterMark.addElement("Text") .addAttribute("FontName", "宋体") .addAttribute("FontSize", $V("FontSize")) .addAttribute("FontColor", $V("FontColor")) .addText($V("Text")); ImageLibConfig.addComment("多缩略图"); int count = Integer.parseInt($V("Count")); Element AbbrImages = ImageLibConfig.addElement("AbbrImages").addAttribute("Count", String.valueOf(count)); for (int i = 1; i <= count; ++i) { String index = $V("AbbrImageIndex" + i); Element AbbrImage = AbbrImages.addElement("AbbrImage") .addAttribute("ID", String.valueOf(i)) .addAttribute("HasAbbrImage", $V("HasAbbrImage" + index)) .addAttribute("SizeType", $V("SizeType" + index)) .addAttribute("Width", $V("Width" + index)) .addAttribute("Height", $V("Height" + index)); WaterMark = AbbrImage.addElement("WaterMark") .addAttribute( "HasWaterMark", ($V("HasWaterMark" + index) == null) ? "0" : $V("HasWaterMark" + index)) .addAttribute("WaterMarkType", $V("WaterMarkType" + index)) .addAttribute("Position", $V("Position" + index)); WaterMark.addElement("Image").addAttribute("src", $V("Image" + index)); WaterMark.addElement("Text") .addAttribute("FontName", "宋体") .addAttribute("FontSize", $V("FontSize" + index)) .addAttribute("FontColor", $V("FontColor" + index)) .addText($V("Text" + index)); } try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(Constant.GlobalCharset); StringWriter sw = new StringWriter(); XMLWriter writer = new XMLWriter(sw, format); writer.write(doc); writer.flush(); writer.close(); new QueryBuilder("update zcsite set ConfigXML=? where ID = ?", sw.toString(), siteID) .executeNoQuery(); } catch (IOException e) { this.Response.setLogInfo(0, "保存失败"); e.printStackTrace(); return; } imageLibConfigMap.remove(siteID); getImageLibConfig(siteID); this.Response.setLogInfo(1, "保存成功"); }
public static MavenProject copySrc(MavenProject project) throws KoalaException { MavenProject destProject = project.clone(); String parentPath = project.getPath() + "/target/" + project.getName() + WS + "/"; // 文件的复制工作 FileCopyAction.clearDir(parentPath); FileCopyAction.clearDir(project.getPath() + "/target/ws-client"); FileCopyAction.copyFile(project.getPath() + "/pom.xml", parentPath + "/pom.xml"); // 获取需要修改的依赖关系 List<Dependency> changes = new ArrayList<Dependency>(); // 获取需要复制生成的子项目 List<MavenProject> changesProject = new ArrayList<MavenProject>(); for (MavenProject childProject : project.getChilds()) { if (childProject.getType().equals(ModuleType.Impl) || childProject.getType().equals(ModuleType.BizModel) || childProject.getType().equals(ModuleType.Infra) || childProject.getType().equals(ModuleType.Application) || childProject.getType().equals(ModuleType.Other) || childProject.getType().equals(ModuleType.conf)) { changesProject.add(childProject); Dependency dependency = new Dependency( childProject.getGroupId(), childProject.getArtifactId(), childProject.getVersion()); changes.add(dependency); } } // 新子项目名称 List<String> newModules = new ArrayList<String>(); String confModulePath = ""; for (MavenProject change : changesProject) { newModules.add(change.getName() + WS); // 进行复制 FileCopyAction.copyDir( change.getPath(), parentPath + change.getName() + WS, MavenFileFilter.newInstance()); if (change.getType().equals(ModuleType.conf)) { confModulePath = parentPath + change.getName() + WS; } } if (!confModulePath.isEmpty()) { String confModuleRootXmlPath = confModulePath + "/src/main/resources/META-INF/spring/root.xml"; Document confModuleRootXml = DocumentUtil.readDocument(confModuleRootXmlPath); Element root = confModuleRootXml.getRootElement(); for (Iterator i = root.elementIterator("import"); i.hasNext(); ) { Element element = (Element) i.next(); if (element .attributeValue("resource") .equals("classpath*:META-INF/spring/security-persistence-context.xml")) { root.remove(element); } } // // root.addElement("import").addAttribute("resource","classpath*:META-INF/spring/security-application.xml"); DocumentUtil.document2Xml(confModuleRootXmlPath, confModuleRootXml); } newModules.add("war-ws"); // 开始修改文件 // 第一步,修改父项目的pom.xml,需要修改artifactId以及module Document parentPomXmlDocument = DocumentUtil.readDocument(parentPath + "/pom.xml"); PomXmlWriter.updatePomArtifactId(parentPomXmlDocument, project.getArtifactId() + WS); PomXmlWriter.updateModules(parentPomXmlDocument, newModules); DocumentUtil.document2Xml(parentPath + "/pom.xml", parentPomXmlDocument); destProject.setPath(parentPath); destProject.setArtifactId(project.getArtifactId() + WS); destProject.getChilds().clear(); // 第二步,开始修改子项目 for (MavenProject change : changesProject) { String implPomXml = parentPath + "/" + change.getName() + WS + "/pom.xml"; Document modulePomXmlDocument = DocumentUtil.readDocument(implPomXml); PomXmlWriter.updatePomArtifactId(modulePomXmlDocument, change.getArtifactId() + WS); PomXmlWriter.updatePomParentArtifactId(modulePomXmlDocument, project.getArtifactId() + WS); for (Dependency depen : changes) { Dependency newDepen = new Dependency(depen.getGroupId(), depen.getArtifactId() + WS, depen.getVersion()); PomXmlWriter.updateDependency(modulePomXmlDocument, depen, newDepen); } PomXmlWriter.addDependencies("org.apache.cxf", "cxf-api", "2.6.2", modulePomXmlDocument); PomXmlWriter.addDependencies( "org.apache.cxf", "cxf-rt-transports-http", "2.6.2", modulePomXmlDocument); PomXmlWriter.addDependencies( "org.apache.cxf", "cxf-rt-frontend-jaxrs", "2.6.2", modulePomXmlDocument); PomXmlWriter.addDependencies("wsdl4j", "wsdl4j", "1.6.2", modulePomXmlDocument); PomXmlWriter.addDependencies("javax.ws.rs", "jsr311-api", "1.0", modulePomXmlDocument); PomXmlWriter.addDependencies("javax.jws", "jsr181-api", "1.0-MR1", modulePomXmlDocument); DocumentUtil.document2Xml(implPomXml, modulePomXmlDocument); MavenProject destImpl = change.clone(); destImpl.setPath(parentPath + "/" + change.getName() + WS); destImpl.setArtifactId(change.getArtifactId() + WS); destImpl.setParent(destProject); destProject.getChilds().add(destImpl); } // 生成war-ws项目 Map params = new HashMap(); params.put("path", parentPath); params.put("Project", project); params.put("Dependencys", changesProject); // VelocityUtil.velocityDirParse("vm/ws/war-ws", parentPath+"war-ws", // VelocityUtil.getVelocityContext(params)); XmlParseUtil.parseXml("xml/ws-security-copy.xml", params); return destProject; }
private void refreshConfigurationFormValues() { room.lock.readLock().lock(); try { FormField field = configurationForm.getField("muc#roomconfig_roomname"); field.clearValues(); field.addValue(room.getNaturalLanguageName()); field = configurationForm.getField("muc#roomconfig_roomdesc"); field.clearValues(); field.addValue(room.getDescription()); field = configurationForm.getField("muc#roomconfig_changesubject"); field.clearValues(); field.addValue((room.canOccupantsChangeSubject() ? "1" : "0")); field = configurationForm.getField("muc#roomconfig_maxusers"); field.clearValues(); field.addValue(Integer.toString(room.getMaxUsers())); field = configurationForm.getField("muc#roomconfig_presencebroadcast"); field.clearValues(); for (String roleToBroadcast : room.getRolesToBroadcastPresence()) { field.addValue(roleToBroadcast); } field = configurationForm.getField("muc#roomconfig_publicroom"); field.clearValues(); field.addValue((room.isPublicRoom() ? "1" : "0")); field = configurationForm.getField("muc#roomconfig_persistentroom"); field.clearValues(); field.addValue((room.isPersistent() ? "1" : "0")); field = configurationForm.getField("muc#roomconfig_moderatedroom"); field.clearValues(); field.addValue((room.isModerated() ? "1" : "0")); field = configurationForm.getField("muc#roomconfig_membersonly"); field.clearValues(); field.addValue((room.isMembersOnly() ? "1" : "0")); field = configurationForm.getField("muc#roomconfig_allowinvites"); field.clearValues(); field.addValue((room.canOccupantsInvite() ? "1" : "0")); field = configurationForm.getField("muc#roomconfig_passwordprotectedroom"); field.clearValues(); field.addValue((room.isPasswordProtected() ? "1" : "0")); field = configurationForm.getField("muc#roomconfig_roomsecret"); field.clearValues(); field.addValue(room.getPassword()); field = configurationForm.getField("muc#roomconfig_whois"); field.clearValues(); field.addValue((room.canAnyoneDiscoverJID() ? "anyone" : "moderators")); field = configurationForm.getField("muc#roomconfig_enablelogging"); field.clearValues(); field.addValue((room.isLogEnabled() ? "1" : "0")); field = configurationForm.getField("x-muc#roomconfig_reservednick"); field.clearValues(); field.addValue((room.isLoginRestrictedToNickname() ? "1" : "0")); field = configurationForm.getField("x-muc#roomconfig_canchangenick"); field.clearValues(); field.addValue((room.canChangeNickname() ? "1" : "0")); field = configurationForm.getField("x-muc#roomconfig_registration"); field.clearValues(); field.addValue((room.isRegistrationEnabled() ? "1" : "0")); field = configurationForm.getField("muc#roomconfig_roomadmins"); field.clearValues(); for (JID jid : room.getAdmins()) { field.addValue(jid.toString()); } field = configurationForm.getField("muc#roomconfig_roomowners"); field.clearValues(); for (JID jid : room.getOwners()) { field.addValue(jid.toString()); } // Remove the old element probeResult.remove(probeResult.element(QName.get("x", "jabber:x:data"))); // Add the new representation of configurationForm as an element probeResult.add(configurationForm.getElement()); } finally { room.lock.readLock().unlock(); } }
/* * This method intentionally does not use XStream or any of the objects * associated with various elements in the config.xml file, dealing * instead with the "raw" XML, because the objects and their methods * have too many unforseeable side effects. */ private InputStream fixConfigFile(XmlFile file, String oldTeam, String newTeam, String email) { InputStream in = null; String oldPrefix = oldTeam + TeamManager.TEAM_SEPARATOR; String newPrefix = newTeam + TeamManager.TEAM_SEPARATOR; try { in = new FileInputStream(file.getFile()); SAXReader reader = new SAXReader(); Document doc = reader.read(in); Element root = doc.getRootElement(); // The root element name varies by project type, e.g., // project, matrix-project, etc. Code assumes that // following elements are common to all project types. // Cascading Element cascadingParent = root.element("cascadingProjectName"); if (cascadingParent != null) { fixTeamName(cascadingParent, oldPrefix, newPrefix); } Element cascadingChildren = root.element("cascadingChildrenNames"); if (cascadingChildren != null) { for (Object elem : cascadingChildren.elements("string")) { fixTeamName((Element) elem, oldPrefix, newPrefix); } } // Properties (open-ended problem) Element properties = root.element("project-properties"); if (properties == null) { throw new Failure("Project has no <project-properties>"); } List<Element> removeEntries = new ArrayList<Element>(); for (Object ent : properties.elements("entry")) { Element entry = (Element) ent; Element extProp = entry.element("external-property"); Element origValue = extProp != null ? extProp.element("originalValue") : null; Element str = entry.element("string"); if (str != null) { String propName = str.getTextTrim(); if ("hudson-tasks-Mailer".equals(propName)) { // email if (extProp != null) { if (email == null) { // A recent fix removes entries that are not specified removeEntries.add(entry); /* // Replace entire entry entry.remove(extProp); extProp = entry.addElement("external-property"); Element propOver = extProp.addElement("propertyOverridden"); propOver.setText("false"); Element modified = extProp.addElement("modified"); modified.setText("false"); */ } else if (origValue != null) { fixEmailProperty(origValue, email); } } } else if ("hudson-tasks-BuildTrigger".equals(propName)) { // trigger if (origValue != null) { fixTriggerProperty(origValue, oldPrefix, newPrefix); } } else if ("builders".equals(propName)) { // can be many of these Element describableList = entry.element("describable-list-property"); origValue = describableList != null ? describableList.element("originalValue") : null; // copyartifact List artifacts = origValue != null ? origValue.elements("hudson.plugins.copyartifact.CopyArtifact") : null; if (artifacts != null) { for (Object obj : artifacts) { Element copyArtifact = (Element) obj; Element projectName = copyArtifact.element("projectName"); fixTeamName(projectName, oldPrefix, newPrefix); } } // multijob List multiJob = origValue != null ? origValue.elements("com.tikal.jenkins.plugins.multijob.MultiJobBuilder") : null; for (Object obj : multiJob) { Element builder = (Element) obj; List jobs = builder.elements("phaseJobs"); if (jobs != null) { for (Object j : jobs) { Element job = (Element) j; List configs = job.elements("com.tikal.jenkins.plugins.multijob.PhaseJobsConfig"); if (configs != null) { for (Object c : configs) { Element config = (Element) c; Element jobName = config.element("jobName"); fixTeamName(jobName, oldPrefix, newPrefix); } } } } } } else if ("hudson-plugins-redmine-RedmineProjectProperty".equals(propName)) { Element baseProp = entry.element("base-property"); Element projectName = baseProp != null ? baseProp.element("projectName") : null; if (projectName != null) { fixTeamName(projectName, oldPrefix, newPrefix); } } } } for (Element entry : removeEntries) { properties.remove(entry); } StringWriter writer = new StringWriter(); doc.write(writer); return new ByteArrayInputStream(writer.toString().getBytes("UTF-8")); } catch (FileNotFoundException ex) { throw new Failure("File not found"); } catch (DocumentException ex) { throw new Failure("Unable to parse document"); } catch (IOException ex) { throw new Failure("Document write failed"); } finally { try { in.close(); } catch (IOException ex) {; } } }
/** Exposes the bean as XML. */ public void doXml( StaplerRequest req, StaplerResponse rsp, @QueryParameter String xpath, @QueryParameter String wrapper, @QueryParameter String tree, @QueryParameter int depth) throws IOException, ServletException { setHeaders(rsp); String[] excludes = req.getParameterValues("exclude"); if (xpath == null && excludes == null) { // serve the whole thing rsp.serveExposedBean(req, bean, Flavor.XML); return; } StringWriter sw = new StringWriter(); // first write to String Model p = MODEL_BUILDER.get(bean.getClass()); TreePruner pruner = (tree != null) ? new NamedPathPruner(tree) : new ByDepth(1 - depth); p.writeTo(bean, pruner, Flavor.XML.createDataWriter(bean, sw)); // apply XPath Object result; try { Document dom = new SAXReader().read(new StringReader(sw.toString())); // apply exclusions if (excludes != null) { for (String exclude : excludes) { List<org.dom4j.Node> list = (List<org.dom4j.Node>) dom.selectNodes(exclude); for (org.dom4j.Node n : list) { Element parent = n.getParent(); if (parent != null) parent.remove(n); } } } if (xpath == null) { result = dom; } else { List list = dom.selectNodes(xpath); if (wrapper != null) { Element root = DocumentFactory.getInstance().createElement(wrapper); for (Object o : list) { if (o instanceof String) { root.addText(o.toString()); } else { root.add(((org.dom4j.Node) o).detach()); } } result = root; } else if (list.isEmpty()) { rsp.setStatus(HttpServletResponse.SC_NOT_FOUND); rsp.getWriter().print(Messages.Api_NoXPathMatch(xpath)); return; } else if (list.size() > 1) { rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); rsp.getWriter().print(Messages.Api_MultipleMatch(xpath, list.size())); return; } else { result = list.get(0); } } } catch (DocumentException e) { LOGGER.log(Level.FINER, "Failed to do XPath/wrapper handling. XML is as follows:" + sw, e); throw new IOException2( "Failed to do XPath/wrapper handling. Turn on FINER logging to view XML.", e); } OutputStream o = rsp.getCompressedOutputStream(req); try { if (result instanceof CharacterData || result instanceof String || result instanceof Number || result instanceof Boolean) { if (INSECURE) { rsp.setContentType("text/plain;charset=UTF-8"); String text = result instanceof CharacterData ? ((CharacterData) result).getText() : result.toString(); o.write(text.getBytes("UTF-8")); } else { rsp.sendError( HttpURLConnection.HTTP_FORBIDDEN, "primitive XPath result sets forbidden; can use -Dhudson.model.Api.INSECURE=true if you run without security"); } return; } // otherwise XML rsp.setContentType("application/xml;charset=UTF-8"); new XMLWriter(o).write(result); } finally { o.close(); } }