Example usage for org.w3c.dom Node setNodeValue

List of usage examples for org.w3c.dom Node setNodeValue

Introduction

In this page you can find the example usage for org.w3c.dom Node setNodeValue.

Prototype

public void setNodeValue(String nodeValue) throws DOMException;

Source Link

Document

The value of this node, depending on its type; see the table above.

Usage

From source file:org.apache.ranger.utils.install.XmlConfigChanger.java

private void modProperty(String propName, String val, boolean createIfNotExists) {
    Node node = findProperty(propName);
    if (node != null) {
        NodeList cnl = node.getChildNodes();
        for (int j = 0; j < cnl.getLength(); j++) {
            String nodeName = cnl.item(j).getNodeName();
            if (nodeName.equals(VALUE_NODE_NAME)) {
                if (cnl.item(j).hasChildNodes()) {
                    cnl.item(j).getChildNodes().item(0).setNodeValue(val);
                } else {
                    Node propValueNode = cnl.item(j);
                    Node txtNode = doc.createTextNode(val);
                    propValueNode.appendChild(txtNode);
                    txtNode.setNodeValue(val);
                }//w ww  .j  a v  a2 s  . c o m
                return;
            }
        }
    }
    if (createIfNotExists) {
        addProperty(propName, val);
    }
}

From source file:org.apache.ranger.utils.install.XmlConfigChanger.java

private Element createNewElement(String propName, String val) {
    Element ret = null;/*w  w w  .  j a  v  a  2 s. c  o  m*/

    try {
        if (doc != null) {
            ret = doc.createElement(PROPERTY_NODE_NAME);
            Node propNameNode = doc.createElement(NAME_NODE_NAME);
            Node txtNode = doc.createTextNode(propName);
            propNameNode.appendChild(txtNode);
            propNameNode.setNodeValue(propName);
            ret.appendChild(propNameNode);

            Node propValueNode = doc.createElement(VALUE_NODE_NAME);
            txtNode = doc.createTextNode(val);
            propValueNode.appendChild(txtNode);
            propValueNode.setNodeValue(propName);
            ret.appendChild(propValueNode);
        }
    } catch (Throwable t) {
        throw new RuntimeException("createNewElement(" + propName + ") with value [" + val + "] failed.", t);
    }

    return ret;
}

From source file:org.apache.ws.security.message.UsernameTokenTest.java

/**
 * A test for WSS-66 - the nonce string is null
 * http://issues.apache.org/jira/browse/WSS-66
 * "Possible security hole when PasswordDigest is used by client."
 *//* w  w w  .  ja  v  a  2 s. c  om*/
@org.junit.Test
public void testNullNonce() throws Exception {
    WSSecUsernameToken builder = new WSSecUsernameToken();
    builder.setPasswordType(WSConstants.PASSWORD_DIGEST);
    builder.setUserInfo("wernerd", "BAD_PASSWORD");

    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document utDoc = builder.build(doc, secHeader);

    //
    // Manually find the Nonce node and set the content to null
    //
    org.w3c.dom.Element elem = builder.getUsernameTokenElement();
    org.w3c.dom.NodeList list = elem.getElementsByTagNameNS(WSConstants.WSSE_NS, "Nonce");
    org.w3c.dom.Node nonceNode = list.item(0);
    org.w3c.dom.Node childNode = nonceNode.getFirstChild();
    childNode.setNodeValue("");

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(utDoc);
        LOG.debug(outputString);
    }

    try {
        //
        // Verification should fail as the password is bad
        //
        verify(utDoc);
        fail("Expected failure due to a bad password");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == WSSecurityException.FAILED_AUTHENTICATION);
        // expected
    }
}

From source file:org.apache.ws.security.message.UsernameTokenTest.java

/**
 * A test for WSS-66 - the created string is null
 * http://issues.apache.org/jira/browse/WSS-66
 * "Possible security hole when PasswordDigest is used by client."
 *//*from www .  j a va2 s . c o m*/
@org.junit.Test
public void testNullCreated() throws Exception {
    WSSecUsernameToken builder = new WSSecUsernameToken();
    builder.setPasswordType(WSConstants.PASSWORD_DIGEST);
    builder.setUserInfo("wernerd", "BAD_PASSWORD");

    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document utDoc = builder.build(doc, secHeader);

    //
    // Manually find the Created node and set the content to null
    //
    org.w3c.dom.Element elem = builder.getUsernameTokenElement();
    org.w3c.dom.NodeList list = elem.getElementsByTagNameNS(WSConstants.WSU_NS, "Created");
    org.w3c.dom.Node nonceNode = list.item(0);
    org.w3c.dom.Node childNode = nonceNode.getFirstChild();
    childNode.setNodeValue("");

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(utDoc);
        LOG.debug(outputString);
    }

    try {
        //
        // Verification should fail as the password is bad
        //
        verify(utDoc);
        fail("Expected failure due to a bad password");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == WSSecurityException.FAILED_AUTHENTICATION);
        // expected
    }
}

From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java

@Override
protected Element getStructure(Document doc, LayoutStructure ls) {
    Element structure = null;//from www. j  a  v  a2 s  . co m

    String type = ls.getType();

    if (ls.isChannel()) {
        final IPortletDefinition channelDef = this.portletDefinitionRegistry
                .getPortletDefinition(String.valueOf(ls.getChanId()));
        if (channelDef != null && channelApproved(channelDef.getApprovalDate())) {
            structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(), channelDef,
                    ls.getLocale());
        } else {
            structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(),
                    MissingPortletDefinition.INSTANCE, null);
        }
    } else {
        // create folder objects including dlm new types in cp namespace
        if (type != null && type.startsWith(Constants.NS)) {
            structure = doc.createElementNS(Constants.NS_URI, type);
        } else {
            structure = doc.createElement("folder");
        }
        structure.setAttribute("name", ls.getName());
        structure.setAttribute("type", (type != null ? type : "regular"));
    }

    structure.setAttribute("hidden", (ls.isHidden() ? "true" : "false"));
    structure.setAttribute("immutable", (ls.isImmutable() ? "true" : "false"));
    structure.setAttribute("unremovable", (ls.isUnremovable() ? "true" : "false"));
    if (localeAware) {
        structure.setAttribute("locale", ls.getLocale()); // for i18n by Shoji
    }

    /*
     * Parameters from up_layout_param are loaded slightly differently for
     * folders and channels. For folders all parameters are added as attributes
     * of the Element. For channels only those parameters with names starting
     * with the dlm namespace Constants.NS are added as attributes to the Element.
     * Others are added as child parameter Elements.
     */
    if (ls.getParameters() != null) {
        for (final Iterator itr = ls.getParameters().iterator(); itr.hasNext();) {
            final StructureParameter sp = (StructureParameter) itr.next();
            String pName = sp.getName();

            if (!ls.isChannel()) { // Folder
                if (pName.startsWith(Constants.NS)) {
                    structure.setAttributeNS(Constants.NS_URI, pName, sp.getValue());
                } else {
                    structure.setAttribute(pName, sp.getValue());
                }
            } else // Channel
            {
                // if dealing with a dlm namespace param add as attribute
                if (pName.startsWith(Constants.NS)) {
                    structure.setAttributeNS(Constants.NS_URI, pName, sp.getValue());
                    itr.remove();
                } else {
                    /*
                     * do traditional override processing. some explanation is in
                     * order. The structure element was created by the
                     * ChannelDefinition and only contains parameter children if the
                     * definition had defined parameters. These are checked for each
                     * layout loaded parameter as found in LayoutStructure.parameters.
                     * If a name match is found then we need to see if overriding is
                     * allowed and if so we set the value on the child parameter
                     * element. At that point we are done with that version loaded
                     * from the layout so we remove it from the in-memory set of
                     * parameters that are being merged-in. Then, after all such have
                     * been checked against those added by the channel definition we
                     * add in any remaining as adhoc, unregulated parameters.
                     */
                    final NodeList nodeListParameters = structure.getElementsByTagName("parameter");
                    for (int j = 0; j < nodeListParameters.getLength(); j++) {
                        final Element parmElement = (Element) nodeListParameters.item(j);
                        final NamedNodeMap nm = parmElement.getAttributes();

                        final String nodeName = nm.getNamedItem("name").getNodeValue();
                        if (nodeName.equals(pName)) {
                            final Node override = nm.getNamedItem("override");
                            if (override != null && override.getNodeValue().equals("yes")) {
                                final Node valueNode = nm.getNamedItem("value");
                                valueNode.setNodeValue(sp.getValue());
                            }
                            itr.remove();
                            break; // found the corresponding one so skip the rest
                        }
                    }
                }
            }
        }
        // For channels, add any remaining parameter elements loaded with the
        // layout as adhoc, unregulated, parameter children that can be overridden.
        if (ls.isChannel()) {
            for (final Iterator itr = ls.getParameters().iterator(); itr.hasNext();) {
                final StructureParameter sp = (StructureParameter) itr.next();
                final Element parameter = doc.createElement("parameter");
                parameter.setAttribute("name", sp.getName());
                parameter.setAttribute("value", sp.getValue());
                parameter.setAttribute("override", "yes");
                structure.appendChild(parameter);
            }
        }
    }
    // finish setting up elements based on loaded params
    final String origin = structure.getAttribute(Constants.ATT_ORIGIN);
    final String prefix = ls.isChannel() ? channelPrefix : folderPrefix;

    // if not null we are dealing with a node incorporated from another
    // layout and this node contains changes made by the user so handle
    // id swapping.
    if (!origin.equals("")) {
        structure.setAttributeNS(Constants.NS_URI, Constants.ATT_PLF_ID, prefix + ls.getStructId());
        structure.setAttribute("ID", origin);
    } else if (!ls.isChannel())
    // regular folder owned by this user, need to check if this is a
    // directive or ui element. If the latter then use traditional id
    // structure
    {
        if (type != null && type.startsWith(Constants.NS)) {
            structure.setAttribute("ID", Constants.DIRECTIVE_PREFIX + ls.getStructId());
        } else {
            structure.setAttribute("ID", folderPrefix + ls.getStructId());
        }
    } else {
        logger.debug("Adding identifier {}{}", folderPrefix, ls.getStructId());
        structure.setAttribute("ID", channelPrefix + ls.getStructId());
    }
    structure.setIdAttribute(Constants.ATT_ID, true);
    return structure;
}

From source file:org.automagic.deps.doctor.editor.PomWriterImpl.java

private void clearDummyComment(Node node) {
    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node item = childNodes.item(i);
        if (Node.COMMENT_NODE == item.getNodeType()) {
            node.removeChild(item);//from   w w  w .j  a  v  a 2s.c  o m
            break;
        }
        if (Node.TEXT_NODE == item.getNodeType()) {
            item.setNodeValue(EMPTY);
        }
    }
}

From source file:org.broadleafcommerce.common.extensibility.context.merge.handlers.NodeValueMerge.java

@Override
public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) {
    if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) {
        return null;
    }/*w ww.jav a  2  s .  c om*/
    Node node1 = nodeList1.get(0);
    Node node2 = nodeList2.get(0);
    Set<String> finalItems = getMergedNodeValues(node1, node2);
    StringBuilder sb = new StringBuilder();
    Iterator<String> itr = finalItems.iterator();
    while (itr.hasNext()) {
        sb.append(itr.next());
        if (itr.hasNext()) {
            sb.append(getDelimiter());
        }
    }
    node1.setNodeValue(sb.toString());
    node2.setNodeValue(sb.toString());

    Node[] response = new Node[nodeList2.size()];
    for (int j = 0; j < response.length; j++) {
        response[j] = nodeList2.get(j);
    }
    return response;
}

From source file:org.carewebframework.shell.layout.UILayout.java

/**
 * Sets the specified attribute value for the specified element.
 * //from   w w w. ja  va2s  .c  o  m
 * @param name Attribute name.
 * @param value Attribute value.
 * @param element Element to receive the attribute.
 */
private void setAttributeValue(String name, String value, Node element) {
    Node node = element.getAttributes().getNamedItem(name);

    if (node == null) {
        node = document.createAttribute(name);
        element.getAttributes().setNamedItem(node);
    }

    node.setNodeValue(value);
}

From source file:org.deegree.tools.metadata.InspireValidator.java

/**
 * reads a number of random records from a CSW and validates them against INSPIRE metadata validator
 * /*ww  w .  j  a  v a2 s . c  o  m*/
 * @param mr
 *            number of records to be tested
 */
public void runRandomQuery(String mr) {
    int maxQueries = 50;
    if (mr != null) {
        maxQueries = Integer.parseInt(mr);
        LOG.logInfo(Messages.get("m1", mr));
    } else {
        LOG.logInfo(Messages.get("m2", mr));
    }
    try {
        int max = getNumberOfAvailableRecords();
        if (maxQueries > max) {
            maxQueries = max;
            LOG.logInfo(Messages.get("m3", max));
        }
        // create base GetRecords request without constraint but with startPosition and maxRecords = 1
        String s = Messages.get("getRecordsWithoutFilter");
        XMLFragment request = new XMLFragment(new StringReader(s), XMLFragment.DEFAULT_URL);
        Random random = new Random();
        outputWriter = new PrintWriter(new File(outputFile));
        for (int i = 0; i < maxQueries; i++) {
            // set index of record to read
            Node node = XMLTools.getNode(request.getRootElement(), Messages.get("xPathStartPosition"), nsc);
            node.setNodeValue(Integer.toString(random.nextInt(max) + 1));

            HttpMethod m = HttpUtils.performHttpPost(cswAddress, request, 60000, null, null, null);
            XMLFragment xml = new XMLFragment();
            xml.load(m.getResponseBodyAsStream(), cswAddress);
            List<org.w3c.dom.Element> list = XMLTools.getElements(xml.getRootElement(),
                    Messages.get("xPathMetadata"), nsc);
            System.out.println(Messages.get("m4", i + 1, maxQueries));
            outputWriter.println("---------------------------------------------------------------------");
            String id = XMLTools.getNodeAsString(list.get(0), Messages.get("xPathIdentifier"), nsc, "none");
            outputWriter.println(Messages.get("m5", id));
            validateINSPIRE(list.get(0));
        }
        System.out.println();
    } catch (Exception e) {
        LOG.logError(e);
    } finally {
        if (outputWriter != null) {
            outputWriter.flush();
            outputWriter.close();
        }
    }
    System.out.println(Messages.get("m6", new File(outputFile).getAbsolutePath()));
}

From source file:org.dita.dost.module.AbstractModuleTest.java

private void normalizeSpace(final Node node) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        for (final Node n : getChildren(node)) {
            normalizeSpace(n);//  w ww .ja va  2 s  . co  m
        }
        break;
    case Node.TEXT_NODE:
        final String v = node.getNodeValue().replaceAll("\\s+", " ").trim();
        if (v.isEmpty()) {
            node.getParentNode().removeChild(node);
        } else {
            node.setNodeValue(v);
        }
        break;
    }
}