List of usage examples for org.dom4j Element remove
boolean remove(Text text);
Text
if the node is an immediate child of this element. From source file:org.efaps.webdav4vfs.data.DavResource.java
License:Apache License
protected boolean addLockDiscoveryProperty(final Element _root, final boolean _ignoreValue) { Element lockdiscoveryEl = _root.addElement(PROP_LOCK_DISCOVERY); try {//w w w . j a v a 2 s . com List<Lock> locks = LockManager.getInstance().discoverLock(object); if (locks != null && !locks.isEmpty()) { for (Lock lock : locks) { if (lock != null && !_ignoreValue) { lock.serializeToXml(lockdiscoveryEl); } } } return true; } catch (FileSystemException e) { _root.remove(lockdiscoveryEl); e.printStackTrace(); return false; } }
From source file:org.esupportail.lecture.domain.model.ChannelConfig.java
/** * Check syntax file that cannot be checked by DTD. * @param xmlFileChecked/*from w w w. j a v a 2s. c o m*/ * @return xmlFileLoading */ @SuppressWarnings("unchecked") private synchronized static Document checkConfigFile(Document xmlFileChecked) { if (LOG.isDebugEnabled()) { LOG.debug("checkXmlFile()"); } // Merge categoryProfilesUrl and check number of contexts + categories Document xmlFileLoading = xmlFileChecked; Element channelConfig = xmlFileLoading.getRootElement(); List<Element> contexts = channelConfig.selectNodes("context"); nbContexts = contexts.size(); if (nbContexts == 0) { LOG.warn("No context declared in channel config (esup-lecture.xml)"); } // 1. merge categoryProfilesUrls and refCategoryProfile for (Element context : contexts) { List<Node> nodes = context.selectNodes("categoryProfilesUrl|refCategoryProfile"); for (Node node : nodes) { //Is a refCategoryProfile ? if (node.getName().equals("refCategoryProfile")) { //remove from context (from its current place in original XML file) context.remove(node); //add to context (at the end of new constructed context: With merged refCategoryProfile from categoryProfilesUrl) context.add(node); } else { String categoryProfilesUrlPath = node.valueOf("@url"); //URL url = ChannelConfig.class.getResource(categoryProfilesUrlPath); String idPrefix = node.valueOf("@idPrefix"); if ((categoryProfilesUrlPath == null) || (categoryProfilesUrlPath == "")) { String errorMsg = "URL of : categoryProfilesUrl with prefix " + idPrefix + " is null or empty."; LOG.warn(errorMsg); } else { Document categoryProfilesFile = getFreshConfigFile(categoryProfilesUrlPath); if (categoryProfilesFile == null) { String errorMsg = "Impossible to load categoryProfilesUrl " + categoryProfilesUrlPath; LOG.warn(errorMsg); } else { // merge one categoryProfilesUrl // add categoryProfile Element rootCategoryProfilesFile = categoryProfilesFile.getRootElement(); // replace ids with IdPrefix + "-" + id List<Element> categoryProfiles = rootCategoryProfilesFile.elements(); for (Element categoryProfile : categoryProfiles) { String categoryProfileId = idPrefix + "-" + categoryProfile.valueOf("@id"); //String categoryProfileName = categoryProfile.valueOf("@name"); categoryProfile.addAttribute("id", categoryProfileId); Element categoryProfileAdded = categoryProfile.createCopy(); channelConfig.add(categoryProfileAdded); // delete node categoryProfilesUrl ? // add refCategoryProfile context.addElement("refCategoryProfile").addAttribute("refId", categoryProfileId); } } } //remove now unneeded categoryProfilesUrl context.remove(node); } } } List<Node> categoryProfiles = channelConfig.selectNodes("categoryProfile"); nbProfiles = categoryProfiles.size(); if (nbProfiles == 0) { LOG.warn("checkXmlConfig :: No managed category profile declared in channel config"); } return xmlFileLoading; }
From source file:org.etudes.component.app.melete.MeleteImportServiceImpl.java
License:Apache License
private org.dom4j.Element checkModuleItem(org.dom4j.Element eleItem, org.dom4j.Element eleParentOrganization) throws Exception { org.dom4j.Attribute identifierref = eleItem.attribute("identifierref"); if (identifierref == null) return null; List elements = eleParentOrganization.elements(); org.dom4j.Element newModuleElement = eleParentOrganization.addElement("item"); for (Iterator iter = elements.iterator(); iter.hasNext();) { org.dom4j.Element e = (org.dom4j.Element) iter.next(); newModuleElement.add(e.createCopy()); eleParentOrganization.remove(e); }/*w w w .ja v a2 s. co m*/ return newModuleElement; }
From source file:org.firesoa.common.jxpath.model.dom4j.Dom4JNodePointer.java
License:Open Source License
public void remove() { Element parent = nodeParent(node); if (parent == null) { throw new JXPathException("Cannot remove root Dom4J node"); }/*from w ww . j a v a 2 s . c om*/ parent.remove(node); }
From source file:org.hightides.annotations.util.SpringXMLUtil.java
License:Apache License
/** * Method to add url mapping to a spring configuration. * Assumes bean is declared as SimpleUrlHandlerMapping with id of applicationUrlMapping. * @param xmlFilename - location of configuration file * @param property - Dom4j Element to insert * @param backup/*w ww . ja v a 2s. c om*/ * @return */ @SuppressWarnings("unchecked") public static Element addURLMapProperty(String xmlFilename, Element property, boolean backup) { String filename = FileUtil.getFilename(xmlFilename); String beanId = UrlMappingId; Document doc = readXMLDocument(xmlFilename); if (doc == null) return null; Element root = doc.getRootElement(); boolean inserted = false; Element mapElement = null; List<Element> elements = root.elements(); for (Element element : elements) { if (beanId.equals(element.attributeValue("id"))) { mapElement = element; break; } } if (mapElement == null) { _log.warn("Cannot find element with id [" + beanId + "] in [" + filename + "]"); return null; } else { List<Element> properties = mapElement.elements("property"); List<Element> backupBeans = new ArrayList<Element>(); for (Element prop : properties) { if (UrlMappingProperty.equals(prop.attributeValue("name"))) { Element props = prop.element("props"); boolean found = false; // inside props, remove existing mapping for (Element el : (List<Element>) props.elements()) { if (property.attributeValue("key").equals(el.attributeValue("key"))) { props.remove(el); found = true; } else if (found) { backupBeans.add(el); props.remove(el); } } // add new props cloneChildElement(prop.element("props"), property); if (backupBeans != null) { for (Element backUpBean : backupBeans) { cloneChildElement(prop.element("props"), backUpBean); } } if (saveXMLDocument(xmlFilename, doc, backup)) { if (found) _log.info("Updated URL mapping for [" + property.attributeValue("key") + "]."); else _log.info("Added URL mapping for [" + property.attributeValue("key") + "]."); inserted = true; } } } } if (inserted) { return property; } else return null; }
From source file:org.hightides.annotations.util.SpringXMLUtil.java
License:Apache License
/** * Method to add a bean to a spring configuration. * @param xmlFilename/* w w w . jav a 2s . c o m*/ * @param bean * @param backup * @return */ @SuppressWarnings("unchecked") public static Element addBean(String xmlFilename, Element bean, boolean backup, String syncMode) { String filename = FileUtil.getFilename(xmlFilename); // some checking first if (StringUtil.isEmpty(bean.attributeValue("id"))) { _log.warn("Attempt to insert empty bean id on [" + filename + "]."); return null; } Document doc = readXMLDocument(xmlFilename); if (doc == null) return null; Element root = doc.getRootElement(); // beans List<Element> elements = root.elements(); List<Element> backupBeans = new ArrayList<Element>(); boolean found = false; for (Element element : elements) { // check if bean already exist if (bean.attributeValue("id").equals(element.attributeValue("id"))) { if (syncMode.equals("UPDATE")) { // copy all the attributes bean.setAttributes(element.attributes()); // inside bean (property) List<Element> properties = element.elements(); List<Element> beanProperties = bean.elements(); for (Element property : properties) { found = false; for (Element beanProperty : beanProperties) { // check if property already exists in bean if (beanProperty.attributeValue("name").equals(property.attributeValue("name"))) { // remove existing property in bean bean.remove(beanProperty); cloneChildElement(bean, property); found = true; break; } } if (!found) { // add property to bean cloneChildElement(bean, property); } } } root.remove(element); found = true; } else if (found) { backupBeans.add(element); root.remove(element); } } cloneChildElement(root, bean); if (backupBeans != null) { for (Element backUpBean : backupBeans) { cloneChildElement(root, backUpBean); } } if (saveXMLDocument(xmlFilename, doc, backup)) { if (found) _log.info("Updated bean [" + bean.attributeValue("id") + "] on [" + filename + "]."); else _log.info("Added bean [" + bean.attributeValue("id") + "] on [" + filename + "]."); } return bean; }
From source file:org.hudsonci.plugins.team.cli.CopyTeamCommand.java
License:Open Source License
private InputStream fixConfigFile(XmlFile file, String oldTeam, String newTeam, String email) { InputStream in = null;/*from ww w. j a va2 s . c om*/ 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) { ; } } }
From source file:org.infoglue.cms.webservices.RemoteUserPropertiesServiceImpl.java
License:Open Source License
/** * Inserts a new UserProperty./*from w w w. java 2 s . c om*/ */ public Boolean updateUserProperties(final String principalName, int languageId, int contentTypeDefinitionId, boolean forcePublication, boolean allowHTMLContent, boolean allowExternalLinks, boolean allowDollarSigns, boolean allowAnchorSigns, boolean keepExistingAttributes, boolean keepExistingCategories, boolean updateExistingAssets, final Object[] inputsArray, final Object[] assetsArray) { if (!ServerNodeController.getController().getIsIPAllowed(getRequest())) { logger.error("A client with IP " + getRequest().getRemoteAddr() + " was denied access to the webservice. Could be a hack attempt or you have just not configured the allowed IP-addresses correct."); return new Boolean(false); } Boolean status = new Boolean(true); int newUserPropertiesId = 0; logger.info("***********************************************"); logger.info("Creating user properties through webservice...."); logger.info("***********************************************"); try { final DynamicWebserviceSerializer serializer = new DynamicWebserviceSerializer(); Map userPropertiesAttributesMap = (Map) serializer.deserialize(inputsArray); List assets = (List) serializer.deserialize(assetsArray); initializePrincipal(principalName); logger.info("principalName:" + principalName); logger.info("principal:" + principal); logger.info("languageId:" + languageId); logger.info("contentTypeDefinitionId:" + contentTypeDefinitionId); UserPropertiesVO userPropertiesVO = new UserPropertiesVO(); userPropertiesVO.setUserName(principal.getName()); Collection userPropertiesVOList = UserPropertiesController.getController() .getUserPropertiesVOList(principal.getName(), languageId); Iterator userPropertiesVOListIterator = userPropertiesVOList.iterator(); while (userPropertiesVOListIterator.hasNext()) { UserPropertiesVO userProperties = (UserPropertiesVO) userPropertiesVOListIterator.next(); if (userProperties != null && userProperties.getLanguageId().equals(languageId) && userProperties.getValue() != null) { userPropertiesVO = userProperties; break; } } logger.info("userPropertiesAttributesMap:" + userPropertiesAttributesMap.size()); DOMBuilder domBuilder = new DOMBuilder(); Document document = domBuilder.createDocument(); Element rootElement = null; Element attributesRoot = null; logger.info("keepExistingAttributes:" + keepExistingAttributes); if (keepExistingAttributes && userPropertiesVO.getValue() != null) { String propertyXML = userPropertiesVO.getValue(); document = domBuilder.getDocument(propertyXML); attributesRoot = (Element) document.getRootElement().element("attributes"); } else { rootElement = domBuilder.addElement(document, "article"); attributesRoot = domBuilder.addElement(rootElement, "attributes"); } logger.info("attributesRoot:" + attributesRoot); logger.info("XML before:" + document.asXML()); Iterator attributesIterator = userPropertiesAttributesMap.keySet().iterator(); while (attributesIterator.hasNext()) { String attributeName = (String) attributesIterator.next(); String attributeValue = (String) userPropertiesAttributesMap.get(attributeName); logger.info(attributeName + "=" + attributeValue); List<Element> elements = attributesRoot.elements(attributeName); logger.info("elements:" + elements.size()); for (Element attribute : elements) { logger.info("attribute:" + attribute); if (attribute != null) attributesRoot.remove(attribute); } Element attribute = domBuilder.addElement(attributesRoot, attributeName); logger.info("attribute after:" + attribute); domBuilder.addCDATAElement(attribute, attributeValue); } logger.info("XML:" + document.asXML()); userPropertiesVO.setValue(document.asXML()); UserPropertiesVO newUserPropertiesVO = userPropertiesController.update(new Integer(languageId), new Integer(contentTypeDefinitionId), userPropertiesVO); newUserPropertiesId = newUserPropertiesVO.getId().intValue(); List existingDigitalAssetVOList = userPropertiesController.getDigitalAssetVOList(newUserPropertiesId); List digitalAssets = assets; logger.info("digitalAssets:" + digitalAssets); //logger.info("digitalAssets:" + digitalAssets.size()); if (digitalAssets != null) { Iterator digitalAssetIterator = digitalAssets.iterator(); while (digitalAssetIterator.hasNext()) { RemoteAttachment remoteAttachment = (RemoteAttachment) digitalAssetIterator.next(); logger.info("digitalAssets in ws:" + remoteAttachment); //logger.info("remoteAttachment:" + remoteAttachment.getName() + ":" + remoteAttachment.getSize() + ":" + remoteAttachment.getFilePath()); DigitalAssetVO newAsset = new DigitalAssetVO(); newAsset.setAssetContentType(remoteAttachment.getContentType()); newAsset.setAssetKey(remoteAttachment.getName()); newAsset.setAssetFileName(remoteAttachment.getFileName()); newAsset.setAssetFilePath(remoteAttachment.getFilePath()); newAsset.setAssetFileSize(new Integer(new Long(remoteAttachment.getBytes().length).intValue())); //is = new FileInputStream(renamedFile); InputStream is = new ByteArrayInputStream(remoteAttachment.getBytes()); Iterator existingDigitalAssetVOListIterator = existingDigitalAssetVOList.iterator(); while (existingDigitalAssetVOListIterator.hasNext()) { DigitalAssetVO assetVO = (DigitalAssetVO) existingDigitalAssetVOListIterator.next(); //logger.info("assetVO:" + assetVO.getAssetKey()); if (assetVO.getAssetKey().equals(newAsset.getAssetKey())) { //logger.info("Removing:" + assetVO.getAssetKey() + ":" + assetVO.getAssetFileName()); DigitalAssetController.getController().delete(assetVO.getId(), UserProperties.class.getName(), newUserPropertiesId); } } DigitalAssetController.create(newAsset, is, UserProperties.class.getName(), newUserPropertiesVO.getId()); } } if (forcePublication) { NotificationMessage notificationMessage = new NotificationMessage( "RemoteUserProperties.updateUserProperties", UserPropertiesImpl.class.getName(), principalName, NotificationMessage.PUBLISHING, newUserPropertiesVO.getId(), newUserPropertiesVO.getUserName()); ChangeNotificationController.getInstance().addNotificationMessage(notificationMessage); } } catch (Throwable e) { status = new Boolean(false); logger.error("En error occurred when we tried to create a new userProperty:" + e.getMessage(), e); } updateCaches(); return status; }
From source file:org.infoglue.common.labels.controllers.LabelsController.java
License:Open Source License
public void updateLabels(String nameSpace, String languageCode, Map properties, Session session) throws Exception { Document document = getPropertyDocument(nameSpace, session); //String xml1 = domBuilder.getFormattedDocument(document, "UTF-8"); //log.debug("xml1:" + xml1); String xpath = "/languages/language[@languageCode='" + languageCode + "']/labels"; //String xpath = "/languages/language[@languageCode='" + languageCode +"']/labels"; //log.debug("xpath:" + xpath); Element labelsElement = (Element) document.selectSingleNode(xpath); //log.debug("labelsElement:" + labelsElement); Iterator keyInterator = properties.keySet().iterator(); while (keyInterator.hasNext()) { String key = (String) keyInterator.next(); String value = (String) properties.get(key); if (!Character.isLetter(key.charAt(0))) key = "NP" + key; if (key != null && value != null) { Element labelElement = labelsElement.element(key); if (labelElement == null) labelElement = domBuilder.addElement(labelsElement, key); labelElement.clearContent(); List elements = labelElement.elements(); Iterator elementsIterator = elements.iterator(); while (elementsIterator.hasNext()) { Element element = (Element) elementsIterator.next(); //log.debug("Removing element:" + element.asXML()); labelElement.remove(element); }// ww w. j a v a2 s .c o m domBuilder.addCDATAElement(labelElement, value); } } String xml = domBuilder.getFormattedDocument(document, "UTF-8"); //log.debug("xml:" + xml); labelsPersister.updateProperty(nameSpace, "systemLabels", xml, session); CacheController.clearCache(LABELSPROPERTIESCACHENAME); }
From source file:org.infoglue.common.settings.controllers.CastorSettingsController.java
License:Open Source License
public void updateSettings(String nameSpace, String name, String id, Map properties, Database database) throws Exception { if (id == null || id.equals("-1")) id = "default"; Document document = getPropertyDocument(nameSpace, name, database); //String xml1 = domBuilder.getFormattedDocument(document, "UTF-8"); //log.debug("xml1:" + xml1); String xpath = "/variations/variation[@id='" + id + "']/setting"; //log.debug("xpath:" + xpath); Element labelsElement = (Element) document.selectSingleNode(xpath); //log.debug("labelsElement:" + labelsElement); Iterator keyInterator = properties.keySet().iterator(); while (keyInterator.hasNext()) { String key = (String) keyInterator.next(); String value = (String) properties.get(key); if (!Character.isLetter(key.charAt(0))) key = "NP" + key; if (key != null && value != null && labelsElement != null) { Element labelElement = labelsElement.element(key); if (labelElement == null) { labelElement = domBuilder.addElement(labelsElement, key); } else { labelElement.clearContent(); List elements = labelElement.elements(); Iterator elementsIterator = elements.iterator(); while (elementsIterator.hasNext()) { Element element = (Element) elementsIterator.next(); //log.debug("Removing element:" + element.asXML()); labelElement.remove(element); }/*from w w w.ja v a2 s .co m*/ } domBuilder.addCDATAElement(labelElement, value); } } String xml = domBuilder.getFormattedDocument(document, "UTF-8"); settingsPersister.updateProperty(nameSpace, name, xml, database); CacheController.clearCache(CacheController.SETTINGSPROPERTIESCACHENAME); CacheController.clearCache(CacheController.SETTINGSPROPERTIESDOCUMENTCACHENAME); }