Spartan 117
Spartan 117

Reputation: 619

How to access SOAP message elements?

So i am trying to replace the values of username and password in the XML file containing a SOAP message. Here are the elements:

 <o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
        <o:UsernameToken u:Id="uuid-68f84594-d592-470b-9bbc-b29f58b4756f-1">
            <o:Username></o:Username>
            <o:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"></o:Password>
        </o:UsernameToken>
    </o:Security>

Basically, i want to take the username and password values from my config file, and place them in the username and password fields within the XML file containing the soap message. This is my attempt, and it throws a NPE at the docElement.getElementsByTagName lines:

 public void updateUserDetails() {
    final Properties configProperties = new Properties();
    try {
        configProperties.load(new FileInputStream(PROPERTIES));
        final Document requestDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream(SOAP_REQUEST));
        final Element docElement = requestDoc.getDocumentElement();
        docElement.getElementsByTagName("Username").item(0).setTextContent(configProperties.getProperty("username"));
        docElement.getElementsByTagName("Password").item(0).setTextContent(configProperties.getProperty("password"));
    } catch(IOException | ParserConfigurationException | SAXException exception) {
        LOGGER.error("There was an error loading the properties file", exception);
    }
}

Any help will be appreciated!

Upvotes: 1

Views: 959

Answers (1)

aUserHimself
aUserHimself

Reputation: 1597

It seems to be related to a namespace problem. Try specifying the namespace for your tag:

String namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
final Document requestDoc = factory.newDocumentBuilder().parse(new FileInputStream(SOAP_REQUEST));
docElement.getElementsByTagNameNS(namespace, "Username").item(0).setTextContent(configProperties.getProperty("username"));
docElement.getElementsByTagNameNS(namespace, "Password").item(0).setTextContent(configProperties.getProperty("password"));

Also, don't forget in the end to write the result back to file:

TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
Transformer transformer = transformerFactory.newTransformer(); 
DOMSource domSource = new DOMSource(requestDoc); 
StreamResult streamResult = new StreamResult(new File(SOAP_REQUEST)); 
transformer.transform(domSource, streamResult);

Upvotes: 1

Related Questions