Example usage for org.w3c.dom Attr setValue

List of usage examples for org.w3c.dom Attr setValue

Introduction

In this page you can find the example usage for org.w3c.dom Attr setValue.

Prototype

public void setValue(String value) throws DOMException;

Source Link

Document

On retrieval, the value of the attribute is returned as a string.

Usage

From source file:cc.siara.csv_ml.ParsedObject.java

/**
 * Sets data attribute. In case of W3C Document, sets value of W3C
 * Attribute. In case of JSON, sets new JSONString
 * /*from  ww  w. j a  v a2  s .  co  m*/
 * @param col_name
 *            Name of attribute
 * @param value
 *            Value of attribute
 */
public void setAttribute(String col_name, String value) {
    if (target == TARGET_W3C_DOC) {
        if (cur_element.getNodeType() == Node.ELEMENT_NODE) {
            int cIdx = col_name.indexOf(':');
            if (cIdx == -1)
                ((Element) cur_element).setAttribute(col_name, value);
            else {
                String ns = col_name.substring(0, cIdx);
                if (ns.equals("xmlns")) {
                    nsMap.put(col_name.substring(cIdx + 1), value);
                } else {
                    String nsURI = nsMap.get(ns);
                    if (nsURI == null) {
                        pendingAttributes.put(col_name, value);
                    } else {
                        Attr attr = doc.createAttributeNS(nsURI, col_name.substring(cIdx + 1));
                        attr.setPrefix(ns);
                        attr.setValue(value);
                        ((Element) cur_element).setAttributeNodeNS(attr);
                    }
                }
            }
        }
    } else
        cur_jo.put(col_name, value);
}

From source file:clus.ext.hierarchical.WHTDStatistic.java

@Override
public Element getPredictElement(Document doc) {
    Element stats = doc.createElement("WHTDStat");
    NumberFormat fr = ClusFormat.SIX_AFTER_DOT;
    Attr examples = doc.createAttribute("examples");
    examples.setValue(fr.format(m_SumWeight));
    stats.setAttributeNode(examples);/*from   w  w w.  j  a  v a 2  s . com*/
    if (m_Threshold >= 0.0) {
        String pred = computePrintTuple().toStringHuman(getHier());
        Element predictions = doc.createElement("Predictions");
        stats.appendChild(predictions);
        String[] predictionS = pred.split(",");
        for (String prediction : predictionS) {
            Element attr = doc.createElement("Prediction");
            predictions.appendChild(attr);
            attr.setTextContent(prediction);
        }
    } else {
        for (int i = 0; i < m_NbAttrs; i++) {
            Element attr = doc.createElement("Target");
            Attr name = doc.createAttribute("name");
            name.setValue(m_Attrs[i].getName());
            attr.setAttributeNode(name);
            if (m_SumWeight == 0.0) {
                attr.setTextContent("?");
            } else {
                attr.setTextContent(fr.format(getMean(i)));
            }
            stats.appendChild(attr);
        }
    }
    return stats;
}

From source file:com.marklogic.dom.AttributeNodeMapImpl.java

protected Node item(int index, Document ownerDoc) throws ParserConfigurationException {
    int numAttr = getNumAttr();
    ExpandedTree tree = element.tree;//from   w w  w. j  a v  a 2s.  c o  m
    if (index < numAttr) {
        if (LOG.isTraceEnabled()) {
            LOG.trace(this.getClass().getSimpleName() + ".item(" + element.node + ", " + index + ")");
        }
        return tree.node(tree.elemNodeAttrNodeRepID[tree.nodeRepID[element.node]] + index);
    } else {
        int nsIdx = index - numAttr;
        // if nsDecl is initialized, return it
        if (nsDecl != null)
            return nsDecl[nsIdx];

        // create owner doc
        if (ownerDoc == null) {
            ownerDoc = getClonedOwnerDoc();
        }

        nsDecl = new Attr[element.getNumNSDecl()];
        // ordinal of the element node
        long minimal = tree.nodeOrdinal[element.node];
        int count = 0;
        for (int ns = element.getNSNodeID(minimal, minimal); ns >= 0
                && count < element.getNumNSDecl(); ns = element.nextNSNodeID(ns, minimal)) {
            String uri = tree.atomString(tree.nsNodeUriAtom[ns]);
            String prefix = tree.atomString(tree.nsNodePrefixAtom[ns]);
            Attr attr = null;
            String name = null;
            try {
                if (prefix != null && "".equals(prefix) == false) {
                    name = "xmlns:" + prefix;
                } else {
                    name = "xmlns";
                }
                attr = ownerDoc.createAttributeNS("http://www.w3.org/2000/xmlns/", name);
                attr.setValue(uri);
            } catch (DOMException e) {
                throw new RuntimeException(e);
            }
            nsDecl[count] = attr;
            count++;
        }

        if (nsDecl != null && nsIdx < count) {
            return nsDecl[nsIdx];
        }
        return null;
    }
}

From source file:Interface.MainJFrame.java

private void btnXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXMLActionPerformed
    // TODO add your handling code here:
    try {//from   w  w  w. j  av  a2 s. c  o  m

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Employees");
        doc.appendChild(rootElement);

        // staff elements
        String empTitle = txtEmployeeType.getText().trim();
        empTitle = empTitle.replace(" ", "");
        Element staff = doc.createElement(empTitle);
        rootElement.appendChild(staff);

        // set attribute to staff element
        Attr attr = doc.createAttribute("ID");
        attr.setValue(txtEmployeeID.getText().trim());
        staff.setAttributeNode(attr);

        // shorten way
        // staff.setAttribute("id", "1");

        // FullName elements
        Element FulllName = doc.createElement("FulllName");
        FulllName.appendChild(doc.createTextNode(txtFullName.getText().trim()));
        staff.appendChild(FulllName);

        // Phone elements
        Element Phone = doc.createElement("PhoneNumber");
        Phone.appendChild(doc.createTextNode(txtPhoneNumber.getText().trim()));
        staff.appendChild(Phone);

        // Address elements
        Element Address = doc.createElement("Address");
        Address.appendChild(doc.createTextNode(txtAddress.getText().trim()));
        staff.appendChild(Address);

        // Title elements
        Element Title = doc.createElement("Tile");
        Title.appendChild(doc.createTextNode(txtEmployeeType.getText().trim()));
        staff.appendChild(Title);

        // PayCategory elements
        Element PayCategory = doc.createElement("PayCategory");
        PayCategory.appendChild(doc.createTextNode(txtPayCategory.getText().trim()));
        staff.appendChild(PayCategory);

        // Salary elements
        Element Salary = doc.createElement("Salary");
        Salary.appendChild(doc.createTextNode(txtSalary.getText().trim()));
        staff.appendChild(Salary);

        // Hours elements

        String hours = txtHours.getText().trim();
        if (txtHours.getText().equalsIgnoreCase("") || hours == null) {
            hours = "null";
        }
        Element Hours = doc.createElement("Hours");
        Hours.appendChild(doc.createTextNode(hours));
        staff.appendChild(Hours);

        // Bonus elements
        Element Bonus = doc.createElement("Bonus");
        Bonus.appendChild(doc.createTextNode(txtBonuses.getText().trim()));
        staff.appendChild(Bonus);

        // Total elements
        Element Total = doc.createElement("Total");
        Total.appendChild(doc.createTextNode(txtTotal.getText().trim()));
        staff.appendChild(Total);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("XMLOutput"));

        // Output to console for testing
        // StreamResult result = new StreamResult(System.out);

        transformer.transform(source, result);

    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        tfe.printStackTrace();
    }

}

From source file:org.gvnix.dynamic.configuration.roo.addon.config.XmlDynamicConfiguration.java

/**
 * Update the root element property values with dynamic properties.
 * // w ww . j ava  2  s  . c om
 * @param root Parent element
 * @param dynProps Dynamic property list
 */
protected void setProperties(Element root, DynPropertyList dynProps) {

    // Iterate all dynamic properties to update
    for (DynProperty dynProp : dynProps) {

        // Remove possible namespaces
        String xpath = removeNamespaces(dynProp.getKey());

        // If attr prefix present, there is an attribute else an element
        int index;
        if ((index = xpath.indexOf(XPATH_ARRAY_PREFIX + XPATH_ATTRIBUTE_PREFIX)) != -1) {

            // Set the new attribute value through container element
            Element elem = XmlUtils.findFirstElement(xpath.substring(0, index), root);
            if (elem == null) {

                logger.log(Level.WARNING, "Element " + xpath + " to set attribute value not exists on file");
            } else {

                String name = xpath.substring(index + 2, xpath.length() - 1);
                Attr attr = elem.getAttributeNode(name);
                if (attr == null) {

                    logger.log(Level.WARNING,
                            "Element attribute " + xpath + " to set value not exists on file");
                } else {

                    attr.setValue(dynProp.getValue());
                }
            }
        } else {

            // Set the new element content
            Element elem = XmlUtils.findFirstElement(xpath, root);

            if (elem == null) {

                logger.log(Level.WARNING, "Element " + xpath + " to set text content not exists on file");
            } else {

                elem.setTextContent(dynProp.getValue());
            }
        }
    }
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static void setNamespaceDeclaration(Element element, String prefix, String namespaceUri) {
    Document doc = element.getOwnerDocument();
    NamedNodeMap attributes = element.getAttributes();
    Attr attr;
    if (prefix == null || prefix.isEmpty()) {
        // default namespace
        attr = doc.createAttributeNS(W3C_XML_SCHEMA_XMLNS_URI, W3C_XML_SCHEMA_XMLNS_PREFIX);
    } else {/*from w  ww.  j  a  va  2s .  c  o  m*/
        attr = doc.createAttributeNS(W3C_XML_SCHEMA_XMLNS_URI, W3C_XML_SCHEMA_XMLNS_PREFIX + ":" + prefix);
    }
    checkValidXmlChars(namespaceUri);
    attr.setValue(namespaceUri);
    attributes.setNamedItem(attr);
}

From source file:org.guanxi.idp.service.shibboleth.AttributeAuthority.java

private AttributeStatementDocument addAttributesFromFarm(UserAttributesDocument guanxiAttrFarmOutput,
        String nameQualifier, String spProviderId) {
    AttributeStatementDocument attrStatementDoc = AttributeStatementDocument.Factory.newInstance();
    AttributeStatementType attrStatement = attrStatementDoc.addNewAttributeStatement();

    boolean hasAttrs = false;
    for (int c = 0; c < guanxiAttrFarmOutput.getUserAttributes().getAttributeArray().length; c++) {
        hasAttrs = true;/*from   ww  w .j ava 2s.co m*/

        AttributorAttribute attributorAttr = guanxiAttrFarmOutput.getUserAttributes().getAttributeArray(c);

        // Has the attribute already been processed? i.e. does it have multiple values?
        AttributeType attribute = null;
        AttributeType[] existingAttrs = attrStatement.getAttributeArray();
        if (existingAttrs != null) {
            for (int cc = 0; cc < existingAttrs.length; cc++) {
                if (existingAttrs[cc].getAttributeName().equals(attributorAttr.getName())) {
                    attribute = existingAttrs[cc];
                }
            }
        }

        // New attribute, not yet processed
        if (attribute == null) {
            attribute = attrStatement.addNewAttribute();
            attribute.setAttributeName(attributorAttr.getName());
            attribute.setAttributeNamespace(Shibboleth.NS_ATTRIBUTES);
        }

        XmlObject attrValue = attribute.addNewAttributeValue();

        // Deal with scoped eduPerson attributes
        if ((attribute.getAttributeName().equals(EduPerson.EDUPERSON_SCOPED_AFFILIATION))
                || (attribute.getAttributeName().equals(EduPerson.EDUPERSON_TARGETED_ID))) {
            // Check if the scope is present...
            if (!attributorAttr.getValue().contains(EduPerson.EDUPERSON_SCOPED_DELIMITER)) {
                // ...if not, add the error scope
                logger.error(attribute.getAttributeName() + " has no scope, adding "
                        + EduPerson.EDUPERSON_NO_SCOPE_DEFINED);
                attributorAttr.setValue(attributorAttr.getValue() + EduPerson.EDUPERSON_SCOPED_DELIMITER
                        + EduPerson.EDUPERSON_NO_SCOPE_DEFINED);
            }
            String[] parts = attributorAttr.getValue().split(EduPerson.EDUPERSON_SCOPED_DELIMITER);
            Attr scopeAttribute = attrValue.getDomNode().getOwnerDocument()
                    .createAttribute(EduPerson.EDUPERSON_SCOPE_ATTRIBUTE);
            scopeAttribute.setValue(parts[1]);
            attrValue.getDomNode().getAttributes().setNamedItem(scopeAttribute);
            Text valueNode = attrValue.getDomNode().getOwnerDocument().createTextNode(parts[0]);
            attrValue.getDomNode().appendChild(valueNode);
        } else {
            Text valueNode = attrValue.getDomNode().getOwnerDocument()
                    .createTextNode(attributorAttr.getValue());
            attrValue.getDomNode().appendChild(valueNode);
        }

        // Release the newer eduPersonTargetedID format to specific SPs
        // internet2-mace-dir-saml-attributes-200804a : 2.3.2.1.1 Recommended Name and Syntax
        if (attribute.getAttributeName().equals(EduPerson.EDUPERSON_TARGETED_ID)) {
            if (getsNewEPTID(spProviderId)) {
                NameIDDocument nameIDDoc = NameIDDocument.Factory.newInstance();
                NameIDType nameID = nameIDDoc.addNewNameID();
                nameID.setFormat(SAML.SAML2_ATTRIBUTE_FORMAT_NAMEID_PERSISTENT);
                nameID.setNameQualifier(nameQualifier);
                nameID.setSPNameQualifier(spProviderId);
                if (attributorAttr.getValue().contains("@")) {
                    attributorAttr.setValue(attributorAttr.getValue().split("@")[0]);
                }
                nameID.setStringValue(attributorAttr.getValue());

                AttributeType saml2Attribute = attrStatement.addNewAttribute();
                saml2Attribute.setAttributeName(
                        EduPersonOID.ATTRIBUTE_NAME_PREFIX + EduPersonOID.OID_EDUPERSON_TARGETED_ID);
                saml2Attribute.setAttributeNamespace(Shibboleth.NS_ATTRIBUTES);

                XmlObject saml2AttrValue = saml2Attribute.addNewAttributeValue();
                saml2AttrValue.getDomNode().appendChild(
                        saml2AttrValue.getDomNode().getOwnerDocument().importNode(nameID.getDomNode(), true));

                // Don't release the legacy format of eduPersonTargetedID
                int count = 0;
                AttributeType[] existingAttributes = attrStatement.getAttributeArray();
                for (AttributeType existingAttribute : existingAttributes) {
                    if (existingAttribute.getAttributeName().equals(EduPerson.EDUPERSON_TARGETED_ID)) {
                        attrStatement.removeAttribute(count);
                    }
                    count++;
                }
            }
        }
    }

    if (hasAttrs)
        return attrStatementDoc;
    else
        return null;
}

From source file:com.icesoft.faces.context.DOMResponseWriter.java

public void writeAttribute(String name, Object value, String componentPropertyName) throws IOException {
    //name.trim() because cardemo had a leading space in an attribute name
    //which made the DOM processor choke
    Attr attribute = document.createAttribute(name.trim());
    attribute.setValue(String.valueOf(value));
    appendToCursor(attribute);/*from  w  w  w .  j  a v  a  2  s  .c o  m*/
}

From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java

/**
 * ?SAML????./*from  ww w.j  a v a  2s  .  com*/
 * @return SAML
 */
public String toSamlString() {

    /*
     * Creation of SAML2.0 Document
     * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
     */

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {
        builder = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // ????????????
        throw new RuntimeException(e);
    }
    Document doc = builder.newDocument();
    Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion");
    doc.appendChild(assertion);
    assertion.setAttribute("ID", this.id);
    assertion.setAttribute("Version", "2.0");

    // Dummy Date
    DateTime dateTime = new DateTime(this.issuedAt);

    assertion.setAttribute("IssueInstant", dateTime.toString());

    // Issuer
    Element issuer = doc.createElement("Issuer");
    issuer.setTextContent(this.issuer);
    assertion.appendChild(issuer);

    // Subject
    Element subject = doc.createElement("Subject");
    Element nameId = doc.createElement("NameID");
    nameId.setTextContent(this.subject);
    Element subjectConfirmation = doc.createElement("SubjectConfirmation");
    subject.appendChild(nameId);
    subject.appendChild(subjectConfirmation);
    assertion.appendChild(subject);

    // Conditions
    Element conditions = doc.createElement("Conditions");
    Element audienceRestriction = doc.createElement("AudienceRestriction");
    for (String aud : new String[] { this.target, this.schema }) {
        Element audience = doc.createElement("Audience");
        audience.setTextContent(aud);
        audienceRestriction.appendChild(audience);
    }
    conditions.appendChild(audienceRestriction);
    assertion.appendChild(conditions);

    // AuthnStatement
    Element authnStmt = doc.createElement("AuthnStatement");
    authnStmt.setAttribute("AuthnInstant", dateTime.toString());
    Element authnCtxt = doc.createElement("AuthnContext");
    Element authnCtxtCr = doc.createElement("AuthnContextClassRef");
    authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
    authnCtxt.appendChild(authnCtxtCr);
    authnStmt.appendChild(authnCtxt);
    assertion.appendChild(authnStmt);

    // AttributeStatement
    Element attrStmt = doc.createElement("AttributeStatement");
    Element attribute = doc.createElement("Attribute");
    for (Role role : this.roleList) {
        Element attrValue = doc.createElement("AttributeValue");
        Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
        attr.setPrefix("xsi");
        attr.setValue("string");
        attrValue.setAttributeNodeNS(attr);
        attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer));
        attribute.appendChild(attrValue);
    }
    attrStmt.appendChild(attribute);
    assertion.appendChild(attrStmt);

    // Normalization 
    doc.normalizeDocument();

    // Dsig??
    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement());

    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);

    // Marshal, generate, and sign the enveloped signature.
    try {
        signature.sign(dsc);
        // ?
        return DcCoreUtils.nodeToString(doc.getDocumentElement());
    } catch (MarshalException e1) {
        // DOM???????
        throw new RuntimeException(e1);
    } catch (XMLSignatureException e1) {
        // ??????????
        throw new RuntimeException(e1);
    }

    /*
     * ------------------------------------------------------------
     * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10
     * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization
     * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and
     * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The
     * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST
     * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648]
     * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/
     * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be
     * line wrapped and pad characters ("=") SHOULD NOT be included.
     */
}

From source file:gov.nih.nci.caadapter.ws.AddNewScenario.java

/**
* Update the reference in .map to the .scs and .h3s files.
*
* @param  mapplingFileName  mapping file name
*//*from  w  w w. ja va  2  s  .  c om*/
public void updateMapping(String mapplingBakFileName) throws Exception {
    Document xmlDOM = readFile(mapplingBakFileName);

    NodeList components = xmlDOM.getElementsByTagName("component");
    for (int i = 0; i < components.getLength(); i++) {
        Element component = (Element) components.item(i);
        //update location of SCS, H3S
        Attr locationAttr = component.getAttributeNode("location");
        Attr kindAttr = component.getAttributeNode("kind");
        if (locationAttr != null) {
            String cmpKind = "";
            if (kindAttr != null)
                cmpKind = kindAttr.getValue();
            if (cmpKind != null && cmpKind.equalsIgnoreCase("v2"))
                continue;
            String localName = extractOriginalFileName(locationAttr.getValue());
            locationAttr.setValue(localName);
        }
        //update VOM reference
        Attr groupAttr = component.getAttributeNode("group");
        if (groupAttr != null && groupAttr.getValue() != null
                && groupAttr.getValue().equalsIgnoreCase("vocabulary")) {
            NodeList chldComps = component.getElementsByTagName("data");
            for (int j = 0; j < chldComps.getLength(); j++) {
                Element chldElement = (Element) chldComps.item(j);
                Attr valueAttr = chldElement.getAttributeNode("value");
                if (valueAttr != null) {
                    String localFileName = extractOriginalFileName(valueAttr.getValue());
                    valueAttr.setValue(localFileName);
                }
            }
        }
    }
    System.out.println("AddNewScenario.updateMapping()..mapbakfile:" + mapplingBakFileName);

    outputXML(xmlDOM, mapplingBakFileName.substring(0, mapplingBakFileName.lastIndexOf(".bak")));
}