Example usage for org.jdom2 Element setContent

List of usage examples for org.jdom2 Element setContent

Introduction

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

Prototype

public Element setContent(final Content child) 

Source Link

Document

Set this element's content to be the supplied child.

Usage

From source file:org.goobi.production.export.ExportXmlLog.java

License:Open Source License

/**
 * This method creates a new xml document with process metadata
 * /* w  w w . ja v a  2 s .  c  om*/
 * @param process the process to export
 * @return a new xml document
 * @throws ConfigurationException
 */
public Document createDocument(Process process, boolean addNamespace) {

    Element processElm = new Element("process");
    Document doc = new Document(processElm);

    processElm.setAttribute("processID", String.valueOf(process.getId()));

    Namespace xmlns = Namespace.getNamespace("http://www.goobi.io/logfile");
    processElm.setNamespace(xmlns);
    // namespace declaration
    if (addNamespace) {

        Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        processElm.addNamespaceDeclaration(xsi);
        Attribute attSchema = new Attribute("schemaLocation",
                "http://www.goobi.io/logfile" + " XML-logfile.xsd", xsi);
        processElm.setAttribute(attSchema);
    }
    // process information

    ArrayList<Element> processElements = new ArrayList<>();
    Element processTitle = new Element("title", xmlns);
    processTitle.setText(process.getTitel());
    processElements.add(processTitle);

    Element project = new Element("project", xmlns);
    project.setText(process.getProjekt().getTitel());
    processElements.add(project);

    Element date = new Element("time", xmlns);
    date.setAttribute("type", "creation date");
    date.setText(String.valueOf(process.getErstellungsdatum()));
    processElements.add(date);

    Element ruleset = new Element("ruleset", xmlns);
    ruleset.setText(process.getRegelsatz().getDatei());
    processElements.add(ruleset);

    Element comment = new Element("comments", xmlns);
    List<LogEntry> log = process.getProcessLog();
    for (LogEntry entry : log) {
        Element commentLine = new Element("comment", xmlns);
        commentLine.setAttribute("type", entry.getType().getTitle());
        commentLine.setAttribute("user", entry.getUserName());
        commentLine.setText(entry.getContent());
        if (StringUtils.isNotBlank(entry.getSecondContent())) {
            comment.setAttribute("secondField", entry.getSecondContent());
        }
        if (StringUtils.isNotBlank(entry.getThirdContent())) {
            comment.setAttribute("thirdField", entry.getThirdContent());
        }
        comment.addContent(commentLine);
    }

    processElements.add(comment);

    if (process.getBatch() != null) {
        Element batch = new Element("batch", xmlns);
        batch.setText(String.valueOf(process.getBatch().getBatchId()));
        if (StringUtils.isNotBlank(process.getBatch().getBatchName())) {
            batch.setAttribute("batchName", process.getBatch().getBatchName());
        }
        if (process.getBatch().getStartDate() != null) {
            batch.setAttribute("startDate", Helper.getDateAsFormattedString(process.getBatch().getStartDate()));
        }

        if (process.getBatch().getEndDate() != null) {
            batch.setAttribute("endDate", Helper.getDateAsFormattedString(process.getBatch().getEndDate()));
        }

        processElements.add(batch);
    }

    List<Element> processProperties = new ArrayList<>();
    List<ProcessProperty> propertyList = PropertyParser.getInstance().getPropertiesForProcess(process);
    for (ProcessProperty prop : propertyList) {
        Element property = new Element("property", xmlns);
        property.setAttribute("propertyIdentifier", prop.getName());
        if (prop.getValue() != null) {
            property.setAttribute("value", prop.getValue());
        } else {
            property.setAttribute("value", "");
        }

        Element label = new Element("label", xmlns);

        label.setText(prop.getName());
        property.addContent(label);
        processProperties.add(property);
    }
    if (processProperties.size() != 0) {
        Element properties = new Element("properties", xmlns);
        properties.addContent(processProperties);
        processElements.add(properties);
    }

    // step information
    Element steps = new Element("steps", xmlns);
    List<Element> stepElements = new ArrayList<>();
    for (Step s : process.getSchritteList()) {
        Element stepElement = new Element("step", xmlns);
        stepElement.setAttribute("stepID", String.valueOf(s.getId()));

        Element steptitle = new Element("title", xmlns);
        steptitle.setText(s.getTitel());
        stepElement.addContent(steptitle);

        Element state = new Element("processingstatus", xmlns);
        state.setText(s.getBearbeitungsstatusAsString());
        stepElement.addContent(state);

        Element begin = new Element("time", xmlns);
        begin.setAttribute("type", "start time");
        begin.setText(s.getBearbeitungsbeginnAsFormattedString());
        stepElement.addContent(begin);

        Element end = new Element("time", xmlns);
        end.setAttribute("type", "end time");
        end.setText(s.getBearbeitungsendeAsFormattedString());
        stepElement.addContent(end);

        if (s.getBearbeitungsbenutzer() != null && s.getBearbeitungsbenutzer().getNachVorname() != null) {
            Element user = new Element("user", xmlns);
            user.setText(s.getBearbeitungsbenutzer().getNachVorname());
            stepElement.addContent(user);
        }
        Element editType = new Element("edittype", xmlns);
        editType.setText(s.getEditTypeEnum().getTitle());
        stepElement.addContent(editType);

        stepElements.add(stepElement);
    }
    if (stepElements != null) {
        steps.addContent(stepElements);
        processElements.add(steps);
    }

    // template information
    Element templates = new Element("originals", xmlns);
    List<Element> templateElements = new ArrayList<>();
    for (Template v : process.getVorlagenList()) {
        Element template = new Element("original", xmlns);
        template.setAttribute("originalID", String.valueOf(v.getId()));

        List<Element> templateProperties = new ArrayList<>();
        for (Templateproperty prop : v.getEigenschaftenList()) {
            Element property = new Element("property", xmlns);
            property.setAttribute("propertyIdentifier", prop.getTitel());
            if (prop.getWert() != null) {
                property.setAttribute("value", prop.getWert());
            } else {
                property.setAttribute("value", "");
            }

            Element label = new Element("label", xmlns);

            label.setText(prop.getTitel());
            property.addContent(label);

            templateProperties.add(property);
            if (prop.getTitel().equals("Signatur")) {
                Element secondProperty = new Element("property", xmlns);
                secondProperty.setAttribute("propertyIdentifier", prop.getTitel() + "Encoded");
                if (prop.getWert() != null) {
                    secondProperty.setAttribute("value", "vorl:" + prop.getWert());
                    Element secondLabel = new Element("label", xmlns);
                    secondLabel.setText(prop.getTitel());
                    secondProperty.addContent(secondLabel);
                    templateProperties.add(secondProperty);
                }
            }
        }
        if (templateProperties.size() != 0) {
            Element properties = new Element("properties", xmlns);
            properties.addContent(templateProperties);
            template.addContent(properties);
        }
        templateElements.add(template);
    }
    if (templateElements != null) {
        templates.addContent(templateElements);
        processElements.add(templates);
    }

    // digital document information
    Element digdoc = new Element("digitalDocuments", xmlns);
    List<Element> docElements = new ArrayList<>();
    for (Masterpiece w : process.getWerkstueckeList()) {
        Element dd = new Element("digitalDocument", xmlns);
        dd.setAttribute("digitalDocumentID", String.valueOf(w.getId()));

        List<Element> docProperties = new ArrayList<>();
        for (Masterpieceproperty prop : w.getEigenschaftenList()) {
            Element property = new Element("property", xmlns);
            property.setAttribute("propertyIdentifier", prop.getTitel());
            if (prop.getWert() != null) {
                property.setAttribute("value", prop.getWert());
            } else {
                property.setAttribute("value", "");
            }

            Element label = new Element("label", xmlns);

            label.setText(prop.getTitel());
            property.addContent(label);
            docProperties.add(property);
        }
        if (docProperties.size() != 0) {
            Element properties = new Element("properties", xmlns);
            properties.addContent(docProperties);
            dd.addContent(properties);
        }
        docElements.add(dd);
    }
    if (docElements != null) {
        digdoc.addContent(docElements);
        processElements.add(digdoc);
    }
    // history
    List<HistoryEvent> eventList = HistoryManager.getHistoryEvents(process.getId());
    if (eventList != null && !eventList.isEmpty()) {
        List<Element> eventElementList = new ArrayList<>(eventList.size());

        for (HistoryEvent event : eventList) {
            Element element = new Element("historyEvent", xmlns);
            element.setAttribute("id", "" + event.getId());
            element.setAttribute("date", Helper.getDateAsFormattedString(event.getDate()));
            element.setAttribute("type", event.getHistoryType().getTitle());

            if (event.getNumericValue() != null) {
                element.setAttribute("numeric_value", "" + event.getNumericValue());
            }
            if (event.getStringValue() != null) {
                element.setText(event.getStringValue());
            }
            eventElementList.add(element);
        }

        if (!eventElementList.isEmpty()) {
            Element metadataElement = new Element("history", xmlns);
            metadataElement.addContent(eventElementList);
            processElements.add(metadataElement);
        }
    }

    // metadata
    List<StringPair> metadata = MetadataManager.getMetadata(process.getId());
    if (metadata != null && !metadata.isEmpty()) {
        List<Element> mdlist = new ArrayList<>();
        for (StringPair md : metadata) {
            String name = md.getOne();
            String value = md.getTwo();
            if (StringUtils.isNotBlank(value) && StringUtils.isNotBlank(name)) {
                Element element = new Element("metadata", xmlns);
                element.setAttribute("name", name);
                element.addContent(value);
                mdlist.add(element);
            }
        }
        if (!mdlist.isEmpty()) {
            Element metadataElement = new Element("metadatalist", xmlns);
            metadataElement.addContent(mdlist);
            processElements.add(metadataElement);
        }
    }
    // METS information
    Element metsElement = new Element("metsInformation", xmlns);
    List<Element> metadataElements = new ArrayList<>();

    try {
        String filename = process.getMetadataFilePath();
        Document metsDoc = new SAXBuilder().build(filename);
        Document anchorDoc = null;
        String anchorfilename = process.getMetadataFilePath().replace("meta.xml", "meta_anchor.xml");
        Path anchorFile = Paths.get(anchorfilename);
        if (StorageProvider.getInstance().isFileExists(anchorFile)
                && StorageProvider.getInstance().isReadable(anchorFile)) {
            anchorDoc = new SAXBuilder().build(anchorfilename);
        }

        List<Namespace> namespaces = getNamespacesFromConfig();

        HashMap<String, String> fields = getMetsFieldsFromConfig(false);
        for (String key : fields.keySet()) {
            List<Element> metsValues = getMetsValues(fields.get(key), metsDoc, namespaces);
            for (Element element : metsValues) {
                Element ele = new Element("property", xmlns);
                ele.setAttribute("name", key);
                ele.addContent(element.getTextTrim());
                metadataElements.add(ele);
            }
        }

        if (anchorDoc != null) {
            fields = getMetsFieldsFromConfig(true);
            for (String key : fields.keySet()) {
                List<Element> metsValues = getMetsValues(fields.get(key), anchorDoc, namespaces);
                for (Element element : metsValues) {
                    Element ele = new Element("property", xmlns);
                    ele.setAttribute("name", key);
                    ele.addContent(element.getTextTrim());
                    metadataElements.add(ele);
                }
            }
        }

        if (metadataElements != null) {
            metsElement.addContent(metadataElements);
            processElements.add(metsElement);
        }

    } catch (SwapException e) {
        logger.error(e);
    } catch (DAOException e) {
        logger.error(e);
    } catch (IOException e) {
        logger.error(e);
    } catch (InterruptedException e) {
        logger.error(e);
    } catch (JDOMException e) {
        logger.error(e);
    } catch (JaxenException e) {
        logger.error(e);
    }

    processElm.setContent(processElements);
    return doc;
}

From source file:org.kitodo.docket.ExportXmlLog.java

License:Open Source License

/**
 * This method creates a new xml document with process metadata.
 *
 * @param docketData/*from   ww w  .  j  a va  2 s  . c o m*/
 *            the docketData to export
 * @return a new xml document
 */
private Document createDocument(DocketData docketData, boolean addNamespace) {

    Element processElm = new Element("process");
    final Document doc = new Document(processElm);

    processElm.setAttribute("processID", String.valueOf(docketData.getProcessId()));

    Namespace xmlns = Namespace.getNamespace(NAMESPACE);
    processElm.setNamespace(xmlns);
    // namespace declaration
    if (addNamespace) {

        Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        processElm.addNamespaceDeclaration(xsi);
        Attribute attSchema = new Attribute("schemaLocation", NAMESPACE + " XML-logfile.xsd", xsi);
        processElm.setAttribute(attSchema);
    }
    // process information

    ArrayList<Element> processElements = new ArrayList<>();
    Element processTitle = new Element("title", xmlns);
    processTitle.setText(docketData.getProcessName());
    processElements.add(processTitle);

    Element project = new Element("project", xmlns);
    project.setText(docketData.getProjectName());
    processElements.add(project);

    Element date = new Element("time", xmlns);
    date.setAttribute("type", "creation date");
    date.setText(String.valueOf(docketData.getCreationDate()));
    processElements.add(date);

    Element ruleset = new Element("ruleset", xmlns);
    ruleset.setText(docketData.getRulesetName());
    processElements.add(ruleset);

    Element comment = new Element("comment", xmlns);
    comment.setText(docketData.getComment());
    processElements.add(comment);

    List<Element> processProperties = prepareProperties(docketData.getProcessProperties(), xmlns);

    if (!processProperties.isEmpty()) {
        Element properties = new Element(PROPERTIES, xmlns);
        properties.addContent(processProperties);
        processElements.add(properties);
    }

    // template information
    ArrayList<Element> templateElements = new ArrayList<>();
    Element template = new Element("original", xmlns);

    ArrayList<Element> templateProperties = new ArrayList<>();
    if (docketData.getTemplateProperties() != null) {
        for (Property prop : docketData.getTemplateProperties()) {
            Element property = new Element(PROPERTY, xmlns);
            property.setAttribute(PROPERTY_IDENTIFIER, prop.getTitle());
            if (prop.getValue() != null) {
                property.setAttribute(VALUE, replacer(prop.getValue()));
            } else {
                property.setAttribute(VALUE, "");
            }

            Element label = new Element(LABEL, xmlns);

            label.setText(prop.getTitle());
            property.addContent(label);

            templateProperties.add(property);
            if (prop.getTitle().equals("Signatur")) {
                Element secondProperty = new Element(PROPERTY, xmlns);
                secondProperty.setAttribute(PROPERTY_IDENTIFIER, prop.getTitle() + "Encoded");
                if (prop.getValue() != null) {
                    secondProperty.setAttribute(VALUE, "vorl:" + replacer(prop.getValue()));
                    Element secondLabel = new Element(LABEL, xmlns);
                    secondLabel.setText(prop.getTitle());
                    secondProperty.addContent(secondLabel);
                    templateProperties.add(secondProperty);
                }
            }
        }
    }
    if (!templateProperties.isEmpty()) {
        Element properties = new Element(PROPERTIES, xmlns);
        properties.addContent(templateProperties);
        template.addContent(properties);
    }
    templateElements.add(template);

    Element templates = new Element("originals", xmlns);
    templates.addContent(templateElements);
    processElements.add(templates);

    // digital document information
    ArrayList<Element> docElements = new ArrayList<>();
    Element dd = new Element("digitalDocument", xmlns);

    List<Element> docProperties = prepareProperties(docketData.getWorkpieceProperties(), xmlns);

    if (!docProperties.isEmpty()) {
        Element properties = new Element(PROPERTIES, xmlns);
        properties.addContent(docProperties);
        dd.addContent(properties);
    }
    docElements.add(dd);

    Element digdoc = new Element("digitalDocuments", xmlns);
    digdoc.addContent(docElements);
    processElements.add(digdoc);

    processElm.setContent(processElements);
    return doc;
}

From source file:org.polago.deployconf.task.AbstractTask.java

License:Open Source License

/**
 * Create a JDOM Text Element with the given name and possibly text.
 *
 * @param name the element name/*  w w w .  j  a  v  a 2s .com*/
 * @param text the element text or null
 * @return a JDOM Element instance
 */
protected Element createJDOMTextElement(String name, String text) {
    Element result = new Element(name);
    if (text != null) {
        result.setContent(new Text(text));
    }

    return result;
}

From source file:org.rometools.feed.module.content.io.ContentModuleGenerator.java

License:Open Source License

public void generate(com.sun.syndication.feed.module.Module module, org.jdom2.Element element) {
    // this is not necessary, it is done to avoid the namespace definition in every item.
    Element root = element;//from  w ww  .j av  a2  s  .c om

    while ((root.getParent() != null) && root.getParent() instanceof Element) {
        root = (Element) root.getParent();
    }

    root.addNamespaceDeclaration(CONTENT_NS);

    if (!(module instanceof ContentModule)) {
        return;
    }

    ContentModule cm = (ContentModule) module;

    List encodeds = cm.getEncodeds();

    //
    if (encodeds != null) {
        System.out.println(cm.getEncodeds().size());
        for (int i = 0; i < encodeds.size(); i++) {
            element.addContent(generateCDATAElement("encoded", encodeds.get(i).toString()));
        }
    }

    List contentItems = cm.getContentItems();

    if ((contentItems != null) && (contentItems.size() > 0)) {
        Element items = new Element("items", CONTENT_NS);
        Element bag = new Element("Bag", RDF_NS);
        items.addContent(bag);

        for (int i = 0; i < contentItems.size(); i++) {
            ContentItem contentItem = (ContentItem) contentItems.get(i);
            Element li = new Element("li", RDF_NS);
            Element item = new Element("item", CONTENT_NS);

            if (contentItem.getContentAbout() != null) {
                Attribute about = new Attribute("about", contentItem.getContentAbout(), RDF_NS);
                item.setAttribute(about);
            }

            if (contentItem.getContentFormat() != null) {
                //System.out.println( "Format");
                Element format = new Element("format", CONTENT_NS);
                Attribute formatResource = new Attribute("resource", contentItem.getContentFormat(), RDF_NS);
                format.setAttribute(formatResource);

                item.addContent(format);
            }

            if (contentItem.getContentEncoding() != null) {
                //System.out.println( "Encoding");
                Element encoding = new Element("encoding", CONTENT_NS);
                Attribute encodingResource = new Attribute("resource", contentItem.getContentEncoding(),
                        RDF_NS);
                encoding.setAttribute(encodingResource);
                item.addContent(encoding);
            }

            if (contentItem.getContentValue() != null) {
                Element value = new Element("value", RDF_NS);

                if (contentItem.getContentValueParseType() != null) {
                    Attribute parseType = new Attribute("parseType", contentItem.getContentValueParseType(),
                            RDF_NS);
                    value.setAttribute(parseType);
                }

                if (contentItem.getContentValueNamespaces() != null) {
                    List namespaces = contentItem.getContentValueNamespaces();

                    for (int ni = 0; ni < namespaces.size(); ni++) {
                        value.addNamespaceDeclaration((Namespace) namespaces.get(ni));
                    }
                }

                List detached = new ArrayList();

                for (int c = 0; c < contentItem.getContentValueDOM().size(); c++) {
                    detached.add(
                            ((Content) ((Content) contentItem.getContentValueDOM().get(c)).clone()).detach());
                }

                value.setContent(detached);
                item.addContent(value);
            } // end value

            li.addContent(item);
            bag.addContent(li);
        } //end contentItems loop

        element.addContent(items);
    }
}

From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java

License:Open Source License

public void handleEnabledWorkItemEvent(WorkItemRecord enabledWorkItem) {
    try {/*from w ww  .  ja  v  a 2 s. c om*/
        if (!checkConnection(_sessionHandle)) {
            _sessionHandle = connect(engineLogonName, engineLogonPassword);
        }
        if (successful(_sessionHandle)) {
            WorkItemRecord child = checkOut(enabledWorkItem.getID(), _sessionHandle);
            if (child != null) {
                List children = getChildren(enabledWorkItem.getID(), _sessionHandle);
                for (int i = 0; i < children.size(); i++) {
                    WorkItemRecord itemRecord = (WorkItemRecord) children.get(i);
                    if (WorkItemRecord.statusFired.equals(itemRecord.getStatus())) {
                        checkOut(itemRecord.getID(), _sessionHandle);
                    }

                }
                List executingChildren = getChildren(enabledWorkItem.getID(), _sessionHandle);
                for (int i = 0; i < executingChildren.size(); i++) {
                    WorkItemRecord itemRecord = (WorkItemRecord) executingChildren.get(i);
                    Element element = itemRecord.getDataList();

                    String answer;

                    //Get the signed document
                    String Document = element.getChild(_Signature).getText();
                    Document = Document.replace(" ", "+");
                    System.out.println("Beginning of Checking XmlSignature:");

                    System.out.println(Document);
                    //Decode the BASE64 signature
                    Base64 deCoder = new Base64();

                    byte[] SignedDocument = deCoder.decode(Document.getBytes());
                    System.out.println("Beginning of Checking XmlSignature:");
                    if (checkSignature(SignedDocument))
                        answer = "true";
                    else
                        answer = "false";
                    System.out.println("end of Checking XmlSignature:");
                    System.out.println(answer);

                    //Set the output element
                    Element Outputelement = prepareReplyRootElement(itemRecord, _sessionHandle);
                    Element Child = new Element(_CheckSignature);
                    Child.setText(answer);
                    Outputelement.addContent(Child);

                    Element Child2 = new Element(_Document);
                    Child2.setContent(Doc.cloneContent());
                    Outputelement.addContent(Child2);

                    Element Child3 = new Element(_Alias);
                    Child3.setText(_Name);
                    Outputelement.addContent(Child3);

                    //Check In the work item and finish the task. 
                    this.checkInWorkItem(itemRecord.getID(), itemRecord.getDataList(), Outputelement,
                            _sessionHandle);

                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java

License:Open Source License

public String PrepareDocumentToBeSign(Element element) {

    try {//from   ww w.  jav a 2 s  .  c  o m
        //extract the Document to sign and transform it in a valid XML DOM 
        Element rootElement = new Element(element.getName());
        rootElement.setContent(element.cloneContent());
        //convert the Element in a JDOM Document
        Document xdoc = new Document(rootElement);
        //create a DOMOutputter to write the content of the JDOM document in a DOM document
        DOMOutputter outputter = new DOMOutputter();
        org.w3c.dom.Document Doctosign = outputter.output(xdoc);

        // Show the document before being sign 
        System.out.println("xml to Sign:");
        XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
        sortie.output(xdoc, System.out);

        //Transform the XML DOM in a String using the xml transformer
        DOMSource domSource = new DOMSource(Doctosign);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        String StringTobeSign = writer.toString();

        return StringTobeSign;

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

From source file:org.yawlfoundation.yawl.resourcing.ResourceManager.java

License:Open Source License

/**
 * updates the input datalist with the changed data in the output datalist
 *
 * @param in  - the JDOM Element containing the input params
 * @param out - the JDOM Element containing the output params
 * @return a JDOM Element with the data updated
 *///from w  w  w  . j  av  a  2 s .  c om
private Element updateOutputDataList(Element in, Element out) {

    // get a copy of the 'in' list
    Element result = in.clone();

    // for each child in 'out' list, get its value and copy to 'in' list
    for (Element e : out.getChildren()) {

        // if there's a matching 'in' data item, update its value
        Element resData = result.getChild(e.getName());
        if (resData != null) {
            if (resData.getContentSize() > 0)
                resData.setContent(e.cloneContent());
            else
                resData.setText(e.getText());
        } else {
            result.addContent(e.clone());
        }
    }

    return result;
}

From source file:org.yawlfoundation.yawl.worklet.WorkletService.java

License:Open Source License

/**
 * updates the input datalist with the changed data in the output datalist
 *
 * @param in  - the JDOM Element containing the input params
 * @param out - the JDOM Element containing the output params
 * @return a JDOM Element with the data updated
 *///from  ww  w .  jav a  2 s .c o  m
public Element updateDataList(Element in, Element out) {

    // get a copy of the 'in' list      
    Element result = in.clone();

    // for each child in 'out' list, get its value and copy to 'in' list
    for (Element e : out.getChildren()) {

        // if there's a matching 'in' data item, update its value
        Element resData = result.getChild(e.getName());
        if (resData != null) {
            if (resData.getContentSize() > 0)
                resData.setContent(e.cloneContent());
            else
                resData.setText(e.getText());
        } else {
            // if the item is not in the 'in' list, add it.
            result.getChildren().add(e.clone());
        }
    }

    return result;
}

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();//ww w .  j  av a  2 s .  com
    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 writeLocaleBundleMap(final String bundleName, final String keyName,
        final Map<String, String> localeMap) {
    ResourceBundle theBundle = null;
    for (final PwmLocaleBundle bundle : PwmLocaleBundle.values()) {
        if (bundle.getTheClass().getName().equals(bundleName)) {
            theBundle = ResourceBundle.getBundle(bundleName);
        }/*  w w w.ja  va  2  s.co  m*/
    }

    if (theBundle == null) {
        LOGGER.info("ignoring unknown locale bundle for bundle=" + bundleName + ", key=" + keyName);
        return;
    }

    if (theBundle.getString(keyName) == null) {
        LOGGER.info("ignoring unknown key for bundle=" + bundleName + ", key=" + keyName);
        return;
    }

    resetLocaleBundleMap(bundleName, keyName);
    if (localeMap == null || localeMap.isEmpty()) {
        LOGGER.info("cleared locale bundle map for bundle=" + bundleName + ", key=" + keyName);
        return;
    }

    preModifyActions();
    changeLog.updateChangeLog(bundleName, keyName, localeMap);
    try {
        domModifyLock.writeLock().lock();
        final Element localeBundleElement = new Element("localeBundle");
        localeBundleElement.setAttribute("bundle", bundleName);
        localeBundleElement.setAttribute("key", keyName);
        for (final String locale : localeMap.keySet()) {
            final Element valueElement = new Element("value");
            if (locale != null && locale.length() > 0) {
                valueElement.setAttribute("locale", locale);
            }
            valueElement.setContent(new CDATA(localeMap.get(locale)));
            localeBundleElement.addContent(valueElement);
        }
        localeBundleElement.setAttribute(XML_ATTRIBUTE_MODIFY_TIME, JavaHelper.toIsoDate(Instant.now()));
        document.getRootElement().addContent(localeBundleElement);
    } finally {
        domModifyLock.writeLock().unlock();
    }
}