Example usage for org.jdom2 Element detach

List of usage examples for org.jdom2 Element detach

Introduction

In this page you can find the example usage for org.jdom2 Element detach.

Prototype

@Override
    public Element detach() 

Source Link

Usage

From source file:org.universaal.tools.configurationEditor.editors.ConfigurationEditor.java

License:Apache License

private void createCategoryList(Element root) {

    catListItem = new ExpandItem(mainBar, SWT.NONE, 1);
    catListItem.setText("Categories");

    catListItem.setExpanded(true);//  w  w  w  .  jav a2 s . co  m

    catListComp = new Composite(mainBar, SWT.NONE);
    GridLayout catLayout = new GridLayout(2, false);
    catListComp.setLayout(catLayout);

    // ----------------------------------- Menu -----------------------------------

    final Menu treeMenu = new Menu(catListComp.getShell(), SWT.POP_UP);

    // ----------------------------------- Category -----------------------------------      
    MenuItem categoryItem = new MenuItem(treeMenu, SWT.PUSH);
    categoryItem.setText("New category");

    categoryItem.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            CategoryDialog cd = new CategoryDialog(getSite().getShell());
            cd.create();
            cd.open();

            if (cd.getReturnCode() == Window.OK) {
                //create new category
                Element newCat = new Element("category", doc.getRootElement().getNamespacePrefix(),
                        doc.getRootElement().getNamespaceURI());
                newCat.setAttribute("id", cd.getId());
                newCat.setAttribute("label", cd.getLabel());

                //add to doc
                doc.getRootElement().addContent(newCat);

                //add to the tree
                TreeItem catItem = new TreeItem(tree, tree.getItemCount());
                catItem.setText(cd.getId());

                WidgetMapping.put(catItem, newCat);

                //dirty
                setDirty(true);
            }
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);
        }
    });

    // ----------------------------------- SimpleConfigItem -----------------------------------
    MenuItem simpleConfigItem = new MenuItem(treeMenu, SWT.PUSH);
    simpleConfigItem.setText("New SimpleConfigItem");

    simpleConfigItem.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            SimpleConfigItemDialog cd = new SimpleConfigItemDialog(getSite().getShell());
            cd.create();
            cd.open();

            if (cd.getReturnCode() == Window.OK) {
                //get selected tree item
                TreeItem selectedTreeItem = tree.getSelection()[0];
                if (selectedTreeItem != null) {

                    Element selectedElement = WidgetMapping.getElement(selectedTreeItem);

                    //add element to a category only
                    if (selectedElement.getName().equals("category")) {

                        //create new configItem
                        Element configItem = new Element("SimpleConfigItem",
                                doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());
                        configItem.setAttribute("cardinality", cd.getCardinality());
                        configItem.setAttribute("id", cd.getId());
                        configItem.setAttribute("type", cd.getType());

                        Element label = new Element("label", doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());
                        label.setText(cd.getLabel());
                        configItem.addContent(label);

                        Element description = new Element("description",
                                doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());
                        description.setText(cd.getDescription());
                        configItem.addContent(description);

                        Element defValue = new Element("defaultValue",
                                doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());
                        defValue.setText(cd.getDefaultValue());
                        configItem.addContent(defValue);

                        //add to doc
                        selectedElement.addContent(configItem);

                        //add to the tree
                        TreeItem simpleConfigItem = new TreeItem(selectedTreeItem,
                                selectedTreeItem.getItemCount());
                        simpleConfigItem.setText(cd.getId());

                        WidgetMapping.put(simpleConfigItem, configItem);

                        //set drity
                        setDirty(true);
                    }

                }
            }

        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);

        }
    });

    // ----------------------------------- MapConfigItem -----------------------------------
    MenuItem mapConfigItem = new MenuItem(treeMenu, SWT.PUSH);
    mapConfigItem.setText("New MapConfigItem");

    mapConfigItem.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            MapConfigItemDialog cd = new MapConfigItemDialog(getSite().getShell());
            cd.create();
            cd.open();

            if (cd.getReturnCode() == Window.OK) {
                //get selected tree item
                TreeItem selectedTreeItem = tree.getSelection()[0];
                if (selectedTreeItem != null) {

                    Element selectedElement = WidgetMapping.getElement(selectedTreeItem);

                    //add element to a category only
                    if (selectedElement.getName().equals("category")) {

                        //create new configItem
                        Element configItem = new Element("MapConfigItem",
                                doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());
                        configItem.setAttribute("cardinality", cd.getCardinality());
                        configItem.setAttribute("id", cd.getId());
                        configItem.setAttribute("active", cd.getActive());

                        Element label = new Element("label", doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());
                        label.setText(cd.getLabel());
                        configItem.addContent(label);

                        Element description = new Element("description",
                                doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());
                        description.setText(cd.getDescription());
                        configItem.addContent(description);

                        Element options = new Element("options", doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());

                        //add options
                        int i = 1;
                        for (String attr : cd.getOptions()) {
                            Element optionElement = new Element("option",
                                    doc.getRootElement().getNamespacePrefix(),
                                    doc.getRootElement().getNamespaceURI());
                            optionElement.setAttribute("key", "" + i++);
                            optionElement.setText(attr);

                            options.addContent(optionElement);
                        }

                        configItem.addContent(options);

                        //add to doc
                        selectedElement.addContent(configItem);

                        //add to the tree
                        TreeItem simpleConfigItem = new TreeItem(selectedTreeItem,
                                selectedTreeItem.getItemCount());
                        simpleConfigItem.setText(cd.getId());

                        WidgetMapping.put(simpleConfigItem, configItem);

                        //set drity
                        setDirty(true);

                    }
                }
            }

        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);

        }

    });

    // ----------------------------------- SPARQLConfigItem -----------------------------------
    MenuItem SPARQLConfigItem = new MenuItem(treeMenu, SWT.PUSH);
    SPARQLConfigItem.setText("New SPARQLConfigItem");

    SPARQLConfigItem.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            SPARQLConfigItemDialog cd = new SPARQLConfigItemDialog(getSite().getShell());
            cd.create();
            cd.open();

            if (cd.getReturnCode() == Window.OK) {
                //get selected tree item
                TreeItem selectedTreeItem = tree.getSelection()[0];
                if (selectedTreeItem != null) {

                    Element selectedElement = WidgetMapping.getElement(selectedTreeItem);

                    //add element to a category only
                    if (selectedElement.getName().equals("category")) {

                        //create new configItem
                        Element configItem = new Element("SPARQLConfigItem",
                                doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());
                        configItem.setAttribute("cardinality", cd.getCardinality());
                        configItem.setAttribute("id", cd.getId());
                        configItem.setAttribute("active", cd.getActive());

                        Element label = new Element("label", doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());
                        label.setText(cd.getLabel());
                        configItem.addContent(label);

                        Element description = new Element("description",
                                doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());
                        description.setText(cd.getDescription());
                        configItem.addContent(description);

                        Element query = new Element("query", doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());
                        query.setText(cd.getQuery());
                        configItem.addContent(query);

                        //add to doc
                        selectedElement.addContent(configItem);

                        //add to the tree
                        TreeItem simpleConfigItem = new TreeItem(selectedTreeItem,
                                selectedTreeItem.getItemCount());
                        simpleConfigItem.setText(cd.getId());

                        WidgetMapping.put(simpleConfigItem, configItem);

                        //set drity
                        setDirty(true);

                    }
                }
            }

        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);
        }

    });
    // ----------------------------------- Validator -----------------------------------
    MenuItem newValidatorItem = new MenuItem(treeMenu, SWT.PUSH);
    newValidatorItem.setText("New validator");

    newValidatorItem.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            ValidatorDialog cd = new ValidatorDialog(getSite().getShell());
            cd.create();
            cd.open();

            if (cd.getReturnCode() == Window.OK) {
                //get selected tree item
                TreeItem selectedTreeItem = tree.getSelection()[0];
                if (selectedTreeItem != null) {

                    Element selectedElement = WidgetMapping.getElement(selectedTreeItem);
                    //add element to a configItem only
                    if (selectedElement.getName().contains("ConfigItem")) {
                        //validator element
                        Element validator = new Element("validator", doc.getRootElement().getNamespacePrefix(),
                                doc.getRootElement().getNamespaceURI());
                        validator.setAttribute("class", cd.getValidatorClass());

                        //add attributes
                        for (String attr : cd.getAttributes()) {
                            Element attrElement = new Element("attribute",
                                    doc.getRootElement().getNamespacePrefix(),
                                    doc.getRootElement().getNamespaceURI());
                            attrElement.setText(attr);

                            validator.addContent(attrElement);
                        }

                        //check validators node
                        Element validators = selectedElement.getChild("validators",
                                doc.getRootElement().getNamespace());
                        if (validators == null) {
                            validators = new Element("validators", doc.getRootElement().getNamespacePrefix(),
                                    doc.getRootElement().getNamespaceURI());
                            selectedElement.addContent(validators);
                        }

                        //add validator
                        validators.addContent(validator);

                        //add to the tree
                        TreeItem validatorItem = new TreeItem(selectedTreeItem,
                                selectedTreeItem.getItemCount());
                        validatorItem.setText("Validator");

                        WidgetMapping.put(validatorItem, validator);

                        //set drity
                        setDirty(true);
                    }
                }
            }
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);

        }

    });

    //----------------------- Add Element ----------------------

    final ToolBar toolBar = new ToolBar(catListComp, SWT.NONE);

    GridData gd = new GridData();
    gd.horizontalSpan = 2;

    toolBar.setLayoutData(gd);

    final ToolItem addItem = new ToolItem(toolBar, SWT.DROP_DOWN);

    //addItem.setText("Add...");

    ImageDescriptor image = Activator.getImageDescriptor("icons/new_con.gif");
    addItem.setImage(image.createImage());

    addItem.addListener(SWT.Selection, new Listener() {
        @Override
        public void handleEvent(Event event) {
            if (event.detail == SWT.ARROW) {
                Rectangle rect = addItem.getBounds();
                Point pt = new Point(rect.x, rect.y + rect.height);
                pt = toolBar.toDisplay(pt);
                treeMenu.setLocation(pt.x, pt.y);
                treeMenu.setVisible(true);
            } else {
                //default click
                CategoryDialog cd = new CategoryDialog(getSite().getShell());
                cd.create();
                cd.open();

                //create new category
                Element newCat = new Element("category", doc.getRootElement().getNamespacePrefix(),
                        doc.getRootElement().getNamespaceURI());
                newCat.setAttribute("id", cd.getId());
                newCat.setAttribute("label", cd.getLabel());
                //newCat.setNamespace(Namespace.getNamespace("universaal"));

                //add to doc
                doc.getRootElement().addContent(newCat);

                //add to the tree
                TreeItem catItem = new TreeItem(tree, tree.getItemCount());
                catItem.setText(cd.getId());

                WidgetMapping.put(catItem, newCat);

                //dirty
                setDirty(true);
            }
        }
    });

    final ToolItem removeItem = new ToolItem(toolBar, SWT.PUSH);

    //      removeItem.setText("Remove");

    image = Activator.getImageDescriptor("icons/delete_obj.gif");
    removeItem.setImage(image.createImage());

    removeItem.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {

            TreeItem selectedItem = tree.getSelection()[0];
            selectedItem.dispose();

            //remove element and set drity
            Element el = WidgetMapping.removeElement(selectedItem);
            el.detach();
            //doc.removeContent(el);
            editorChanged();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);

        }
    });

    //tree
    tree = new Tree(catListComp, SWT.BORDER | SWT.SINGLE);

    gd = new GridData();
    gd.verticalAlignment = GridData.FILL;
    gd.horizontalAlignment = GridData.FILL;
    //      gd.horizontalSpan = 2;
    gd.grabExcessVerticalSpace = true;
    gd.grabExcessHorizontalSpace = true;

    tree.setLayoutData(gd);

    //categories
    int i = 0;
    for (Element catEl : root.getChildren()) {
        TreeItem catItem = new TreeItem(tree, i++);
        catItem.setText(catEl.getAttributeValue("id"));

        WidgetMapping.put(catItem, catEl);

        //configItems
        int j = 0;
        for (Element catElChild : catEl.getChildren()) {
            TreeItem catChildItem = new TreeItem(catItem, j++);
            catChildItem.setText(catElChild.getAttributeValue("id"));

            WidgetMapping.put(catChildItem, catElChild);

            //validators
            int k = 0;
            for (Element validators : catElChild.getChildren()) {
                if (validators.getName().equals("validators")) {
                    for (Element validator : validators.getChildren()) {
                        TreeItem validatorItem = new TreeItem(catChildItem, k++);
                        //validatorItem.setText(validator.getAttributeValue("class"));
                        validatorItem.setText("Validator");

                        WidgetMapping.put(validatorItem, validator);
                    }

                }
            }

        }

    }

    tree.addListener(SWT.Selection, new TreeListener(this));

    selectedItemGroup = new Group(catListComp, SWT.NONE);

    gd = new GridData();
    gd.verticalAlignment = GridData.FILL;
    gd.horizontalAlignment = GridData.FILL;
    gd.grabExcessHorizontalSpace = true;
    gd.grabExcessVerticalSpace = true;

    selectedItemGroup.setLayoutData(gd);

    selectedItemGroup.setLayout(new GridLayout(2, false));

    selectedItemGroup.setVisible(false);

    //height & control

    catListItem.setControl(catListComp);

    catListItem.setHeight(treeHeight);

}

From source file:org.xcri.types.DescriptiveTextType.java

License:Open Source License

@Override
public void fromXml(Element element) throws InvalidElementException {
    super.fromXml(element);

    ///*from ww  w .jav  a2s  . com*/
    // Add XHTML content if present
    //
    Element div = Lax.getChildQuietly(element, "div", Namespaces.XHTML_NAMESPACE_NS, log);
    if (div != null) {
        div = (Element) div.detach();
        processXhtml(div);
    }

    //
    // How about some CDATA with HTML in it?
    //
    for (Object child : element.getContent()) {
        if (child instanceof CDATA) {
            if (ParserConfiguration.getInstance().fixCDATA()) {
                log.warn(
                        "description: uses CDATA instead of XHTML. Attempting to convert inline HTML into XHTML.");
                processCDATA((CDATA) child);
            } else {
                throw new InvalidElementException(
                        "description: contains CDATA. To allow CDATA to be converted to XHTML, run with fixCDATA=true");
            }
        }
    }

    //
    // Add HREF
    //
    this.setHref(element.getAttributeValue("href"));

    //
    // Cannot have both linked and inline content
    //
    if ((this.getValue() != null && this.getValue().length() > 0) || this.xhtml != null) {
        if (this.getHref() != null && this.getHref().length() > 0) {
            throw new InvalidElementException(
                    "Description contains both text content and href attribute; only one or the other may be used");
        }
    }
}

From source file:org.xflatdb.xflat.convert.converters.JavaBeansPojoConverter.java

License:Apache License

private static <U> Converter<Element, U> getDecoder(Class<U> clazz) {
    return new Converter<Element, U>() {

        final String version = System.getProperty("java.version");

        @Override/*from w  w  w . ja  va  2 s . c om*/
        public U convert(Element source) throws ConversionException {
            byte[] bytes;
            try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {

                Document doc = new Document();
                doc.setRootElement(new Element("java").setAttribute("version", version).setAttribute("class",
                        "java.beans.XMLDecoder"));

                doc.getRootElement().addContent(source.detach());

                XMLOutputter outputter = new XMLOutputter();
                outputter.output(doc, os);

                bytes = os.toByteArray();
            } catch (IOException ex) {
                throw new ConversionException("Error reading object of class " + source.getClass(), ex);
            }

            try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {

                try (XMLDecoder decoder = new XMLDecoder(is)) {
                    return (U) decoder.readObject();
                }
            } catch (IOException ex) {
                throw new ConversionException("Error reading object of class " + source.getClass(), ex);
            }
        }
    };
}

From source file:org.yawlfoundation.yawl.elements.YTask.java

License:Open Source License

private void addDefaultValuesAsRequired(Document dataDoc) {
    if (dataDoc == null)
        return;/*ww  w .  j  a  v  a 2 s  .  co  m*/
    Element dataElem = dataDoc.getRootElement();
    for (YParameter param : _decompositionPrototype.getOutputParameters().values()) {
        String defaultValue = param.getDefaultValue();
        if (!StringUtil.isNullOrEmpty(defaultValue)) {
            Element paramData = dataElem.getChild(param.getPreferredName());

            // if there's an element, but no value, add the default
            if (paramData != null) {
                if (StringUtil.isNullOrEmpty(paramData.getText())) {
                    paramData.setText(defaultValue);
                }
            }

            // else if there's no element at all, add it with the default value
            else {
                Element defElem = JDOMUtil
                        .stringToElement(StringUtil.wrap(defaultValue, param.getPreferredName()));
                defElem.setNamespace(dataElem.getNamespace());
                dataElem.addContent(Math.min(dataElem.getContentSize(), param.getOrdering()), defElem.detach());
            }
        }
    }
}

From source file:org.yawlfoundation.yawl.elements.YTask.java

License:Open Source License

public Element getStartingDataSnapshot() throws YDataStateException, YStateException, YQueryException {

    logger.debug("--> getStartingDataSnapshot");
    if (null == getDecompositionPrototype())
        return null;

    Element dataForChildCase = produceDataRootElement();
    List<YParameter> inputParams = new ArrayList<YParameter>(
            _decompositionPrototype.getInputParameters().values());
    Collections.sort(inputParams);
    for (YParameter parameter : inputParams) {
        String inputParamName = parameter.getPreferredName();
        String expression = _dataMappingsForTaskStarting.get(inputParamName);
        if (this.isMultiInstance() && inputParamName.equals(_multiInstAttr.getMIFormalInputParam())) {
            if (_multiInstanceSpecificParamsIterator == null)
                continue;

            Element specificMIData = (Element) _multiInstanceSpecificParamsIterator.next();

            if (specificMIData != null) {
                if (YEngine.getInstance().generateUIMetaData()) {

                    // Add in attributes for input parameter
                    specificMIData.setAttributes(parameter.getAttributes().toJDOM());
                }/*from w ww  .ja v  a 2s .  c om*/
                dataForChildCase.addContent(specificMIData.detach());
            }
        } else {
            Element result = ExternalDBGatewayFactory.isExternalDBMappingExpression(expression)
                    ? performExternalDataExtraction(expression, parameter)
                    : performDataExtraction(expression, parameter);

            if (result != null) {
                if (YEngine.getInstance().generateUIMetaData()) {
                    result.setAttributes(parameter.getAttributes().toJDOM());
                }
                dataForChildCase.addContent(result.clone());
            }
        }
    }

    if (YEngine.getInstance().generateUIMetaData()) {
        /**
         * AJH: Add in task level attributes for specifcation to XMLdoclet pass-thru.
         * Note that we skip processing of the YAWL standard task attributes as we only
         * pass-thru the additional (user interface hints) attributes.
         */
        for (String attrName : getDecompositionPrototype().getAttributes().keySet()) {
            String attrValue = getDecompositionPrototype().getAttributes().get(attrName);
            if (!STANDARD_TASK_ATTRIBUTES.contains("/" + attrName + "/")) {
                dataForChildCase.setAttribute(attrName, attrValue);
            }
        }
    }
    logger.debug("<-- getStartingDataSnapshot");
    return dataForChildCase;
}

From source file:org.yawlfoundation.yawl.engine.interfce.Marshaller.java

License:Open Source License

public static String getMergedOutputData(Element inputData, Element outputData) {
    try {//from w w w.j  a va2  s .  c  om
        Element merged = inputData.clone();
        JDOMUtil.stripAttributes(merged);
        JDOMUtil.stripAttributes(outputData);

        List<Element> children = outputData.getChildren();

        // iterate through the output vars and add them to the merged doc.
        for (int i = children.size() - 1; i >= 0; i--) {
            Element child = children.get(i);

            // the input data will be removed from the merged doc and
            // the output data will be added.
            merged.removeChild(child.getName());
            merged.addContent(child.detach());
        }
        return JDOMUtil.elementToString(merged);
    } catch (Exception e) {
        return "";
    }
}

From source file:org.yawlfoundation.yawl.scheduling.util.XMLUtils.java

License:Open Source License

/**
 * merges content of two elements recursively into element minor following
 * content will be copied: Text, Element, Attribute if conflicts, minor will
 * be overwrite with content of major//from  w w w. j  av  a 2  s  .c  o m
 * 
 * @param minor
 * @param major
 */
public static boolean mergeElements(Element minor, Element major) throws Exception {
    // logger.debug("minor: " + Utils.element2String(minor, false));
    // logger.debug("major: " + Utils.element2String(major, false));
    boolean changed = false;
    if (minor == null) {
        minor = major;
        // logger.debug("set minor = " + Utils.element2String(major, false));
        changed = true;
    } else if (major != null) {
        if (!minor.getText().equals(major.getText())) {
            minor.setText(major.getText());
            // logger.debug("minor.setText("+major.getText()+")");
            changed = true;
        }

        for (Attribute a : (List<Attribute>) major.getAttributes()) {
            Attribute aCopy = (Attribute) Utils.deepCopy(a);
            if (minor.getAttribute(a.getName()) == null
                    || !minor.getAttributeValue(a.getName()).equals(a.getValue())) {
                minor.setAttribute(aCopy.detach());
                // logger.debug("minor.setAttribute("+Utils.toString(a)+")");
                changed = true;
            }
        }

        for (Element e : (List<Element>) major.getChildren()) {
            Element eCopy = (Element) Utils.deepCopy(e);
            List<Element> minorChildren = minor.getChildren(e.getName());
            // logger.debug("minorChildren: " + Utils.toString(minorChildren));
            // logger.debug("e: " + Utils.toString(e));
            Element firstInList = existInList(minorChildren, e);
            if (firstInList == null) {
                // logger.debug("minor.addContent: " +
                // Utils.toString(eCopy.detach()));
                minor = minor.addContent(eCopy.detach());
                // logger.debug("minor.addContent("+Utils.element2String(e,
                // false)+")");
                changed = true;
            } else {
                changed = mergeElements(firstInList, eCopy) || changed;
            }
        }
    }

    return changed;
}

From source file:password.pwm.config.stored.StoredConfigurationImpl.java

License:Open Source License

@Override
public void writeConfigProperty(final ConfigurationProperty propertyName, final String value) {
    domModifyLock.writeLock().lock();/* w  w  w.j a va 2 s. c o m*/
    try {

        final XPathExpression xp = XPathBuilder.xpathForConfigProperty(propertyName);
        final List<Element> propertyElements = xp.evaluate(document);
        for (final Element propertyElement : propertyElements) {
            propertyElement.detach();
        }

        final Element propertyElement = new Element(XML_ELEMENT_PROPERTY);
        propertyElement.setAttribute(new Attribute(XML_ATTRIBUTE_KEY, propertyName.getKey()));
        propertyElement.setContent(new Text(value));

        if (null == XPathBuilder.xpathForConfigProperties().evaluateFirst(document)) {
            final Element configProperties = new Element(XML_ELEMENT_PROPERTIES);
            configProperties.setAttribute(new Attribute(XML_ATTRIBUTE_TYPE, XML_ATTRIBUTE_VALUE_CONFIG));
            document.getRootElement().addContent(configProperties);
        }

        final XPathExpression xp2 = XPathBuilder.xpathForConfigProperties();
        final Element propertiesElement = (Element) xp2.evaluateFirst(document);
        propertyElement.setAttribute(XML_ATTRIBUTE_MODIFY_TIME, JavaHelper.toIsoDate(Instant.now()));
        propertiesElement.setAttribute(XML_ATTRIBUTE_MODIFY_TIME, JavaHelper.toIsoDate(Instant.now()));
        propertiesElement.addContent(propertyElement);
    } finally {
        domModifyLock.writeLock().unlock();
    }
}

From source file:password.pwm.config.stored.StoredConfigurationImpl.java

License:Open Source License

public void resetLocaleBundleMap(final String bundleName, final String keyName) {
    preModifyActions();//  w w  w  .j  a  va  2s  . c om
    domModifyLock.writeLock().lock();
    try {
        final XPathExpression xp = XPathBuilder.xpathForLocaleBundleSetting(bundleName, keyName);
        final List<Element> oldBundleElements = xp.evaluate(document);
        if (oldBundleElements != null) {
            for (final Element element : oldBundleElements) {
                element.detach();
            }
        }
    } finally {
        domModifyLock.writeLock().unlock();
    }
}

From source file:password.pwm.config.StoredConfiguration.java

License:Open Source License

public void writeConfigProperty(final ConfigProperty propertyName, final String value) {
    domModifyLock.writeLock().lock();/* w ww .  ja  va  2  s.  c  o  m*/
    try {

        final XPathExpression xp = XPathBuilder.xpathForConfigProperty(propertyName);
        final List<Element> propertyElements = xp.evaluate(document);
        for (final Element propertyElement : propertyElements) {
            propertyElement.detach();
        }

        final Element propertyElement = new Element(XML_ELEMENT_PROPERTY);
        propertyElement.setAttribute(new Attribute(XML_ATTRIBUTE_KEY, propertyName.getKey()));
        propertyElement.setContent(new Text(value));

        if (null == XPathBuilder.xpathForConfigProperties().evaluateFirst(document)) {
            Element configProperties = new Element(XML_ELEMENT_PROPERTIES);
            configProperties.setAttribute(new Attribute(XML_ATTRIBUTE_TYPE, XML_ATTRIBUTE_VALUE_CONFIG));
            document.getRootElement().addContent(configProperties);
        }

        final XPathExpression xp2 = XPathBuilder.xpathForConfigProperties();
        final Element propertiesElement = (Element) xp2.evaluateFirst(document);
        propertyElement.setAttribute(XML_ATTRIBUTE_MODIFY_TIME,
                PwmConstants.DEFAULT_DATETIME_FORMAT.format(new Date()));
        propertiesElement.setAttribute(XML_ATTRIBUTE_MODIFY_TIME,
                PwmConstants.DEFAULT_DATETIME_FORMAT.format(new Date()));
        propertiesElement.addContent(propertyElement);
    } finally {
        domModifyLock.writeLock().unlock();
    }
}