@Test public void testCreateXML() { // Creation of the root Element root = new Element("root"); // Child of the root Element article = new Element("article"); Element title = new Element("title").setText("Description"); title.setAttribute("valoration", "5"); Person person = new Person(23); article.addContent(title).addContent(person); // Modification of the element Person person2 = new Person(24); article.removeContent(person); article.addContent(person2); root.addContent(article); Document doc = new Document(root); // Creation of the xml document log.info("Storing and displaying the xml document..."); try { XMLOutputter out = new XMLOutputter(); FileOutputStream file = new FileOutputStream("ExampleDom.xml"); out.output(doc, file); file.flush(); file.close(); out.output(doc, System.out); } catch (Exception e) { e.printStackTrace(); } }
/** * Update the map-elements in the datasource that are below <i>parent</i>. * * @param parent Parent element to add / update * @param configuration configuration that holds the properties * @param mapName the name of the map-property in the configuration that holds the elements * @param propertyElementName the name of the element to write below <i>parent</i> */ private static void updateMap( Element parent, Configuration configuration, String mapName, String propertyElementName) { PropertyMap map = configuration.getMap(mapName); // Wrap in ArrayList to avoid ConcurrentModificationException when adding or removing children // while iterating. List<Element> mapElements = new ArrayList<Element>(parent.getChildren(propertyElementName)); if ((map == null) || map.getMap().isEmpty()) { if (!mapElements.isEmpty()) { parent.removeChildren(propertyElementName); } return; } Map<String, Element> elements = new HashMap<String, Element>(); for (Element el : mapElements) { elements.put(el.getAttributeValue("name"), el); if (map.get(el.getAttributeValue("name")) == null) { parent.removeContent(el); } } for (Property prop : map.getMap().values()) { Element element = elements.get(prop.getName()); if (element == null) { element = new Element(propertyElementName); element.setAttribute("name", prop.getName()); parent.addContent(element); } element.setText(((PropertySimple) prop).getStringValue()); } }
public static void removeDuplicatedOptions(final Element element) { List<Element> children = new ArrayList<Element>(element.getChildren(OPTION_ELEMENT)); Set<String> names = new HashSet<String>(); for (Element child : children) { if (!names.add(child.getAttributeValue(NAME_ATTRIBUTE))) { element.removeContent(child); } } }
public static List<Element> removeChildren( final Element element, final Condition<Element> filter) { List<Element> toRemove = new ArrayList<Element>(); final List<Element> list = element.getChildren(); for (Element e : list) { if (filter.value(e)) { toRemove.add(e); } } for (Element e : toRemove) { element.removeContent(e); } return toRemove; }
public void assignTo(Element element, String metadataFormatName, String classNameList) { if (!element.getName().equals(metadataFormatName)) { throw new IllegalArgumentException("root not found: " + metadataFormatName); } final Element ifd1 = element.getChild(IIO_TIFF_IFD_ELEMENT_NAME); if (ifd1 == null) { throw new IllegalArgumentException("child not found: " + IIO_TIFF_IFD_ELEMENT_NAME); } final Element ifd2 = createIFD(classNameList); ifd1.setAttribute(IIO_TIFF_TAGSETS_ATT_NAME, ifd2.getAttributeValue(IIO_TIFF_TAGSETS_ATT_NAME)); final Element[] childElems = (Element[]) ifd2.getChildren().toArray(new Element[0]); for (Element child : childElems) { ifd2.removeContent(child); ifd1.addContent(child); } }
private static void updateElement(Element parent, Configuration config, String name) { String value = config.getSimpleValue(name, null); Element child = parent.getChild(name); if (value == null) { if (child != null) { parent.removeContent(child); } } else { if (child == null) { child = new Element(name); parent.addContent(child); } child.setText(value); } }
/** * 替换宏 * * @param element * @param macroId * @return 仅当成功的进行宏替换后返回真 */ private boolean doReplaceMacros(Element element, String macroId) { if (!StringUtils.isEmpty(macroId)) { if (!macros.containsKey(macroId)) { logger.error("消息配置错误,不存在这样的宏定义:" + macroId); return false; } // 防止子macro被重复替换 if (element.getChildren().size() > 0) { return false; } Element macro = macros.get(macroId); Element macroClone = (Element) macro.clone(); element.addContent(macroClone.removeContent()); return true; } return false; }
public static void collapseChildren(Element e, boolean firstHeader) { if (e == null) return; List<String> labels = new ArrayList<String>(); for (Object o : e.getChildren()) { String name = ((Element) o).getName(); if (!labels.contains(name)) labels.add(name); } for (String label : labels) { if (e.getChildren(label).size() > 1) { Element temp = e.getChild(label); e.removeContent(temp); for (Element c : typeAsElement(e.getChildren(label))) { temp = fusionContent(temp, c, firstHeader); } e.removeChildren(label); e.addContent(temp); } } }
public static void suppressRedundantChildren(Element e, boolean keepLast) { if (e == null) return; List<String> labels = new ArrayList<String>(); for (Object o : e.getChildren()) { String name = ((Element) o).getName(); if (!labels.contains(name)) labels.add(name); } for (String label : labels) { if (e.getChildren(label).size() > 1) { Element temp = e.getChild(label); e.removeContent(temp); // to avoid exploring it again in loop if (keepLast) for (Element c : typeAsElement(e.getChildren(label))) { temp = c; } e.removeChildren(label); e.addContent(temp); } } }
public static void addComponent(final Element root, final Element component) { String componentName = component.getAttributeValue(NAME_ATTRIBUTE); final Element old = findComponent(root, componentName); if (old != null) { root.removeContent(old); } for (int i = 0; i < root.getContent().size(); i++) { Object o = root.getContent().get(i); if (o instanceof Element) { Element element = (Element) o; if (element.getName().equals(COMPONENT_ELEMENT)) { final String name = element.getAttributeValue(NAME_ATTRIBUTE); if (componentName.compareTo(name) < 0) { root.addContent(i, component); return; } } } } root.addContent(component); }
/** * Resolve the content of a tag. * * @param tagName : Tag name of job XML i.e. <timeout> 10 </timeout> * @param elem : Element where the tag exists. * @param eval : EL evealuator * @return Resolved tag content. * @throws CoordinatorJobException thrown if failed to resolve tag content */ @SuppressWarnings("unchecked") private String resolveTagContents(String tagName, Element elem, ELEvaluator eval) throws CoordinatorJobException { String ret = ""; if (elem != null) { for (Element tagElem : (List<Element>) elem.getChildren(tagName, elem.getNamespace())) { if (tagElem != null) { String updated; try { updated = CoordELFunctions.evalAndWrap(eval, tagElem.getText().trim()); } catch (Exception e) { throw new CoordinatorJobException(ErrorCode.E1004, e.getMessage(), e); } tagElem.removeContent(); tagElem.addContent(updated); ret += updated; } } } return ret; }
public static void deleteDataSource(File deploymentFile, String name) { Document doc; Element root; if (deploymentFile == null) { log.error("DeleteDatasource: passed file is null"); return; } if (deploymentFile.exists()) { try { SAXBuilder builder = new SAXBuilder(); SelectiveSkippingEntityResolver entityResolver = SelectiveSkippingEntityResolver.getDtdAndXsdSkippingInstance(); builder.setEntityResolver(entityResolver); doc = builder.build(deploymentFile); root = doc.getRootElement(); if (root != null) { if (!root.getName().equals("datasources")) { throw new RuntimeException( "Datasource file format exception on [" + deploymentFile + "], expected [datasources] element but found [" + root.getName() + "]"); } Element datasourceElement = findDatasourceElement(root, name); root.removeContent(datasourceElement); } updateFile(deploymentFile, doc); } catch (JDOMException e) { log.error("Parsing error occurred while deleting datasource at file: " + deploymentFile, e); } catch (IOException e) { log.error("IO error occurred while deleting datasource at file: " + deploymentFile, e); } } }
/** * Apply a list of changes to the metadata record in current editing session. * * <p>The changes are a list of KVP. A key contains at least the element identifier from the * meta-document. A key starting with an "X" should contain an XML fragment for the value. The * following KVP combinations are allowed: * * <ul> * <li>ElementId=ElementValue * <li>ElementId_AttributeName=AttributeValue * <li>ElementId_AttributeNamespacePrefixCOLONAttributeName=AttributeValue * <li>XElementId=ElementValue * <li>XElementId_ElementName=ElementValue * </ul> * * ElementName MUST contain "{@value #COLON_SEPARATOR}" instead of ":" for prefixed elements. * * <p>When using X key, value could contains many XML fragments (eg. <gmd:keywords * .../>{@value #XML_FRAGMENT_SEPARATOR}<gmd:keywords .../>) separated by {@link * #XML_FRAGMENT_SEPARATOR}. All those fragments are inserted to the last element of this type in * its parent if ElementName is set. If not, the element with ElementId is replaced. * * <p> * * @param dbms * @param id Metadata internal identifier. * @param changes List of changes to apply. * @return The update metadata record * @throws Exception */ protected Element applyChangesEmbedded(Dbms dbms, String id, Hashtable changes) throws Exception { String schema = dataManager.getMetadataSchema(dbms, id); EditLib editLib = dataManager.getEditLib(); // --- get metadata from session Element md = getMetadataFromSession(session, id); // Store XML fragments to be handled after other elements update Map<String, String> xmlInputs = new HashMap<String, String>(); // --- update elements for (Enumeration e = changes.keys(); e.hasMoreElements(); ) { String ref = ((String) e.nextElement()).trim(); String value = ((String) changes.get(ref)).trim(); String attribute = null; // Avoid empty key if (ref.equals("")) { continue; } // Catch element starting with a X to replace XML fragments if (ref.startsWith("X")) { ref = ref.substring(1); xmlInputs.put(ref, value); continue; } if (updatedLocalizedTextElement(md, ref, value, editLib)) { continue; } int at = ref.indexOf('_'); if (at != -1) { attribute = ref.substring(at + 1); ref = ref.substring(0, at); } Element el = editLib.findElement(md, ref); if (el == null) { Log.error(Geonet.EDITOR, MSG_ELEMENT_NOT_FOUND_AT_REF + ref); continue; } // Process attribute if (attribute != null) { Pair<Namespace, String> attInfo = parseAttributeName(attribute, COLON_SEPARATOR, id, md, dbms, editLib); String localname = attInfo.two(); Namespace attrNS = attInfo.one(); if (el.getAttribute(localname, attrNS) != null) { el.setAttribute(new Attribute(localname, value, attrNS)); } } else { // Process element value List content = el.getContent(); for (int i = 0; i < content.size(); i++) { if (content.get(i) instanceof Text) { el.removeContent((Text) content.get(i)); i--; } } el.addContent(value); } } // Deals with XML fragments to insert or update if (!xmlInputs.isEmpty()) { // Loop over each XML fragments to insert or replace for (String ref : xmlInputs.keySet()) { String value = xmlInputs.get(ref); String name = null; int addIndex = ref.indexOf('_'); if (addIndex != -1) { name = ref.substring(addIndex + 1); ref = ref.substring(0, addIndex); } // Get element to fill Element el = editLib.findElement(md, ref); if (el == null) { Log.error(Geonet.EDITOR, MSG_ELEMENT_NOT_FOUND_AT_REF + ref); continue; } if (value != null && !value.equals("")) { String[] fragments = value.split(XML_FRAGMENT_SEPARATOR); for (String fragment : fragments) { if (name != null) { if (Log.isDebugEnabled(Geonet.EDITOR)) Log.debug( Geonet.EDITOR, "Add XML fragment; " + fragment + " to element with ref: " + ref); name = name.replace(COLON_SEPARATOR, ":"); editLib.addFragment(schema, el, name, fragment); } else { if (Log.isDebugEnabled(Geonet.EDITOR)) Log.debug( Geonet.EDITOR, "Add XML fragment; " + fragment + " to element with ref: " + ref + " replacing content."); // clean before update el.removeContent(); fragment = addNamespaceToFragment(fragment); // Add content el.addContent(Xml.loadString(fragment, false)); } } } } } // --- remove editing info editLib.removeEditingInfo(md); editLib.contractElements(md); return (Element) md.detach(); }
/** * For Ajax Editing : removes an element from a metadata ([del] link). * * @param dbms * @param session * @param id * @param ref * @param parentRef * @return * @throws Exception */ public synchronized Element deleteElementEmbedded( Dbms dbms, UserSession session, String id, String ref, String parentRef) throws Exception { String schema = dataManager.getMetadataSchema(dbms, id); // --- get metadata from session Element md = getMetadataFromSession(session, id); // --- locate the geonet:info element and clone for later re-use Element info = (Element) (md.getChild(Edit.RootChild.INFO, Edit.NAMESPACE)).clone(); md.removeChild(Edit.RootChild.INFO, Edit.NAMESPACE); // --- get element to remove EditLib editLib = dataManager.getEditLib(); Element el = editLib.findElement(md, ref); if (el == null) throw new IllegalStateException(MSG_ELEMENT_NOT_FOUND_AT_REF + ref); String uName = el.getName(); Namespace ns = el.getNamespace(); Element parent = el.getParentElement(); Element result = null; if (parent != null) { int me = parent.indexOf(el); // --- check and see whether the element to be deleted is the last one of its kind Filter elFilter = new ElementFilter(uName, ns); if (parent.getContent(elFilter).size() == 1) { // --- get geonet child element with attribute name = unqualified name Filter chFilter = new ElementFilter(Edit.RootChild.CHILD, Edit.NAMESPACE); List children = parent.getContent(chFilter); for (int i = 0; i < children.size(); i++) { Element ch = (Element) children.get(i); String name = ch.getAttributeValue("name"); if (name != null && name.equals(uName)) { result = (Element) ch.clone(); break; } } // -- now delete the element as requested parent.removeContent(me); // --- existing geonet child element not present so create it and insert it // --- where the last element was deleted if (result == null) { result = editLib.createElement(schema, el, parent); parent.addContent(me, result); } result.setAttribute(Edit.ChildElem.Attr.PARENT, parentRef); result.addContent(info); } // --- if not the last one then just delete it else { parent.removeContent(me); } } else { throw new IllegalStateException("Element at ref = " + ref + " doesn't have a parent"); } // if we don't need a child then create a geonet:null element if (result == null) { result = new Element(Edit.RootChild.NULL, Edit.NAMESPACE); result.addContent(info); } // --- reattach the info element to the metadata md.addContent((Element) info.clone()); // --- store the metadata in the session again setMetadataIntoSession(session, (Element) md.clone(), id); return result; }
private void handleTmxProp(TmxProp tmxProp, LinguisticProperty ling, Element tuv, Object data) { if (tmxProp != null) { if (ling.getPropStatus().equals(LinguisticProperty.PropStatus.DELETED)) { // now handle associations with Elements and Attributes if (data != null) { if (data.getClass().getCanonicalName().equals("org.jdom.Element")) { Element element = (Element) data; if (element != null) { Element parent = element.getParentElement(); if (parent != null) parent.removeContent(element); } } else if (data.getClass().getCanonicalName().equals("org.jdom.Attribute")) { Attribute attribute = (Attribute) data; if (attribute != null) { Element parent = attribute.getParent(); if (parent != null) parent.removeAttribute(attribute); } } } return; } @SuppressWarnings("unused") String id = tmxProp.getId() + ""; String content = tmxProp.getContent(); String language = tmxProp.getLang(); String o_encoding = tmxProp.getO_encoding(); PropType propType = tmxProp.getPropType(); String type = tmxProp.getType(); // this is actually the property name, e.g. creation-id // now we must check if contained in the tuv // we must check if CORE or PROP OR NOTE attribute if (propType.equals(PropType.CORE)) { Attribute attr = tuv.getAttribute(type); if (!attr.getValue().equals(content)) attr.setValue(content); } else if (propType.equals(PropType.PROP)) { Element prop = tuv.getChild(type); // we identify based on the child if (prop == null) // a new one { prop = new Element("prop"); prop.setText(content); if (type != null) prop.setAttribute("type", type); if (language != null) { prop.setAttribute("lang", language, Namespace.XML_NAMESPACE); } if (o_encoding != null) prop.setAttribute("o-encoding", o_encoding); tuv.addContent(prop); } else { // we only allow the content to change! if (!prop.getText().equals(content)) prop.setText(content); } } else if (propType.equals(PropType.NOTE)) { Element prop = tuv.getChild(type); // we identify based on the child if (prop == null) // a new one { prop = new Element("note"); prop.setText(content); if (type != null) prop.setAttribute("type", type); if (language != null) { prop.setAttribute("lang", language, Namespace.XML_NAMESPACE); } if (o_encoding != null) prop.setAttribute("o-encoding", o_encoding); tuv.addContent(prop); } else { // we only allow the content to change! if (!prop.getText().equals(content)) prop.setText(content); } } ling.setPropStatus(LinguisticProperty.PropStatus.OLD); } }
public void sync() throws SynchronizationException { Properties serviceProps = new Properties(); // load up the service properties if (getServiceInformation().getServiceProperties() != null && getServiceInformation().getServiceProperties().getProperty() != null) { for (int i = 0; i < getServiceInformation().getServiceProperties().getProperty().length; i++) { ServicePropertiesProperty prop = getServiceInformation().getServiceProperties().getProperty(i); if (prop.getValue() == null) { serviceProps.put(prop.getKey(), ""); } else { serviceProps.put(prop.getKey(), prop.getValue()); } } } // write the service propertis out try { serviceProps.store( new FileOutputStream( new File( getBaseDirectory().getAbsolutePath() + File.separator + IntroduceConstants.INTRODUCE_SERVICE_PROPERTIES)), "service deployment properties"); } catch (Exception ex) { throw new SynchronizationException(ex.getMessage(), ex); } // update the JNDI file to have all the right properties and thier // values.... File jndiConfigF = new File(getBaseDirectory().getAbsolutePath() + File.separator + "jndi-config.xml"); try { Document doc = XMLUtilities.fileNameToDocument(jndiConfigF.getAbsolutePath()); List serviceEls = doc.getRootElement().getChildren("service", doc.getRootElement().getNamespace()); for (int serviceI = 0; serviceI < serviceEls.size(); serviceI++) { Element serviceEl = (Element) serviceEls.get(serviceI); String serviceName = serviceEl.getAttributeValue("name"); int startOfServiceName = serviceName.lastIndexOf("/"); serviceName = serviceName.substring(startOfServiceName + 1); ServiceType service = CommonTools.getService(getServiceInformation().getServices(), serviceName); if (service == null) { service = CommonTools.getService( getServiceInformation().getServices(), serviceName + "Service"); if (service == null) { throw new SynchronizationException( "Could not find service in the service information in SyncProperties: " + serviceName); } } List resourceEls = serviceEl.getChildren("resource", serviceEl.getNamespace()); for (int resourceI = 0; resourceI < resourceEls.size(); resourceI++) { Element resourceEl = (Element) resourceEls.get(resourceI); if (serviceI == serviceEls.size() - 1 && resourceEl.getAttributeValue("name").equals("serviceconfiguration")) { // located a serviceconfiguration element, need to // populate it's attributes now... JNDIConfigServicePropertiesTemplate serviceConfTemp = new JNDIConfigServicePropertiesTemplate(); String confXMLString = serviceConfTemp.generate( new SpecificServiceInformation(getServiceInformation(), service)); Element newResourceEl = XMLUtilities.stringToDocument(confXMLString).getRootElement(); serviceEl.removeContent(resourceEl); serviceEl.addContent(resourceI, newResourceEl.detach()); } else if (resourceEl.getAttributeValue("name").equals("configuration")) { // located a configuration element, need to // populate it's attributes now... JNDIConfigServiceResourcePropertiesTemplate serviceResourceConfTemp = new JNDIConfigServiceResourcePropertiesTemplate(); String confXMLString = serviceResourceConfTemp.generate( new SpecificServiceInformation(getServiceInformation(), service)); Element newResourceEl = XMLUtilities.stringToDocument(confXMLString).getRootElement(); serviceEl.removeContent(resourceEl); serviceEl.addContent(resourceI, newResourceEl.detach()); } } } try { FileWriter fw = new FileWriter(jndiConfigF); fw.write(XMLUtilities.formatXML(XMLUtilities.documentToString(doc))); fw.close(); } catch (IOException e) { throw new SynchronizationException(e.getMessage(), e); } } catch (Exception e) { throw new SynchronizationException(e.getMessage(), e); } }
/** * TODO javadoc. * * @param dbms * @param id * @param changes * @param currVersion * @return * @throws Exception */ private Element applyChanges(Dbms dbms, String id, Hashtable changes, String currVersion) throws Exception { Lib.resource.checkEditPrivilege(context, id); Element md = xmlSerializer.select(dbms, "Metadata", id, context); // --- check if the metadata has been deleted if (md == null) { return null; } EditLib editLib = dataManager.getEditLib(); String schema = dataManager.getMetadataSchema(dbms, id); editLib.expandElements(schema, md); editLib.enumerateTree(md); // --- check if the metadata has been modified from last time if (currVersion != null && !editLib.getVersion(id).equals(currVersion)) { return null; } // --- update elements for (Enumeration e = changes.keys(); e.hasMoreElements(); ) { String ref = ((String) e.nextElement()).trim(); String val = ((String) changes.get(ref)).trim(); String attr = null; if (updatedLocalizedTextElement(md, ref, val, editLib)) { continue; } int at = ref.indexOf('_'); if (at != -1) { attr = ref.substring(at + 1); ref = ref.substring(0, at); } boolean xmlContent = false; if (ref.startsWith("X")) { ref = ref.substring(1); xmlContent = true; } Element el = editLib.findElement(md, ref); if (el == null) throw new IllegalStateException("Element not found at ref = " + ref); if (attr != null) { // The following work-around decodes any attribute name that has a COLON in it // The : is replaced by the word COLON in the xslt so that it can be processed // by the XML Serializer when an update is submitted - a better solution is // to modify the argument handler in Jeeves to store arguments with their name // as a value rather than as the element itself Integer indexColon = attr.indexOf("COLON"); if (indexColon != -1) { String prefix = attr.substring(0, indexColon); String localname = attr.substring(indexColon + 5); String namespace = editLib.getNamespace(prefix + ":" + localname, md, dataManager.getSchema(schema)); Namespace attrNS = Namespace.getNamespace(prefix, namespace); if (el.getAttribute(localname, attrNS) != null) { el.setAttribute(new Attribute(localname, val, attrNS)); } // End of work-around } else { if (el.getAttribute(attr) != null) el.setAttribute(new Attribute(attr, val)); } } else if (xmlContent) { if (Log.isDebugEnabled(Geonet.EDITOR)) Log.debug(Geonet.EDITOR, "replacing XML content"); el.removeContent(); val = addNamespaceToFragment(val); el.addContent(Xml.loadString(val, false)); } else { List content = el.getContent(); for (int i = 0; i < content.size(); i++) { if (content.get(i) instanceof Text) { el.removeContent((Text) content.get(i)); i--; } } el.addContent(val); } } // --- remove editing info added by previous call editLib.removeEditingInfo(md); editLib.contractElements(md); return md; }