Example usage for javax.xml.soap SOAPMessage getSOAPPart

List of usage examples for javax.xml.soap SOAPMessage getSOAPPart

Introduction

In this page you can find the example usage for javax.xml.soap SOAPMessage getSOAPPart.

Prototype

public abstract SOAPPart getSOAPPart();

Source Link

Document

Gets the SOAP part of this SOAPMessage object.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

    SOAPHeader soapHeader = soapEnvelope.getHeader();
    SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature",
            "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

    SOAPBody soapBody = soapEnvelope.getBody();
    soapBody.addAttribute(/*from w ww.  jav  a2  s  . c  om*/
            soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"),
            "Body");
    Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
    SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

    Source source = soapPart.getContent();

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

    SOAPHeader soapHeader = soapEnvelope.getHeader();
    SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature",
            "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

    SOAPBody soapBody = soapEnvelope.getBody();
    soapBody.addAttribute(/*  ww w .ja v  a 2  s .co  m*/
            soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"),
            "Body");
    Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
    SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

    Source source = soapPart.getContent();

    Node root = null;
    if (source instanceof DOMSource) {
        root = ((DOMSource) source).getNode();
    } else if (source instanceof SAXSource) {
        InputSource inSource = ((SAXSource) source).getInputSource();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = null;

        db = dbf.newDocumentBuilder();

        Document doc = db.parse(inSource);
        root = (Node) doc.getDocumentElement();
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

    SOAPHeader soapHeader = soapEnvelope.getHeader();
    SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature",
            "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

    SOAPBody soapBody = soapEnvelope.getBody();
    soapBody.addAttribute(/*from   www . ja v a  2  s .c  o  m*/
            soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"),
            "Body");
    Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
    SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

    Source source = soapPart.getContent();

    Node root = null;
    if (source instanceof DOMSource) {
        root = ((DOMSource) source).getNode();
    } else if (source instanceof SAXSource) {
        InputSource inSource = ((SAXSource) source).getInputSource();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = null;

        db = dbf.newDocumentBuilder();

        Document doc = db.parse(inSource);
        root = (Node) doc.getDocumentElement();
    }

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(new DOMSource(root), new StreamResult(System.out));
}

From source file:Signing.java

public static void main(String[] args) throws Exception {
        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        SOAPHeader soapHeader = soapEnvelope.getHeader();
        SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature",
                "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

        SOAPBody soapBody = soapEnvelope.getBody();
        soapBody.addAttribute(//  ww w  . j  a  v a 2s .c om
                soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"),
                "Body");
        Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
        SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

        Source source = soapPart.getContent();
        Node root = null;
        if (source instanceof DOMSource) {
            root = ((DOMSource) source).getNode();
        } else if (source instanceof SAXSource) {
            InputSource inSource = ((SAXSource) source).getInputSource();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = null;

            db = dbf.newDocumentBuilder();

            Document doc = db.parse(inSource);
            root = (Node) doc.getDocumentElement();
        }

        dumpDocument(root);

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(1024, new SecureRandom());
        KeyPair keypair = kpg.generateKeyPair();

        XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance();
        Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null));
        SignedInfo signedInfo = sigFactory.newSignedInfo(
                sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null),
                sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));
        KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
        KeyValue kv = kif.newKeyValue(keypair.getPublic());
        KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));

        XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo);

        System.out.println("Signing the message...");
        PrivateKey privateKey = keypair.getPrivate();
        Element envelope = getFirstChildElement(root);
        Element header = getFirstChildElement(envelope);
        DOMSignContext sigContext = new DOMSignContext(privateKey, header);
        sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
        sigContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        sig.sign(sigContext);

        dumpDocument(root);

        System.out.println("Validate the signature...");
        Element sigElement = getFirstChildElement(header);
        DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement);
        valContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        boolean valid = sig.validate(valContext);

        System.out.println("Signature valid? " + valid);
    }

From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java

/**
 * Invokes an operation using SAAJ/*from   w  w w .  ja v  a2 s  .c o m*/
 *
 * @param operation The operation to invoke
 */
public static void main(String[] args) {
    try {
        /*OperationInfo operation = new OperationInfo();
        operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
        operation.setInputMessageName("HelloWorld_sayHello");
        operation.setInputMessageText("<urn:sayHello xmlns:urn='urn:jbosstest'><arg0>Markus</arg0></urn:sayHello>");
        operation.setNamespaceURI("urn:jbosstest");
        operation.setOutputMessageName("HelloWorld_sayHelloResponse");
        operation.setOutputMessageText("<sayHello><return>0</return></sayHello>");
        operation.setSoapActionURI("");
        operation.setStyle("document");
        operation.setTargetMethodName("sayHello");
        operation.setTargetObjectURI(null);
        operation.setTargetURL("http://localhost:8080/HelloWorld/HelloWorld");*/

        OperationInfo operation = new OperationInfo();
        operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
        operation.setInputMessageName("ConversionRateSoapIn");
        operation.setInputMessageText(
                "<ns5:ConversionRate xmlns:ns5='http://www.webserviceX.NET/'><ns5:FromCurrency>EUR</ns5:FromCurrency><ns5:ToCurrency>SKK</ns5:ToCurrency></ns5:ConversionRate>");
        operation.setNamespaceURI("http://www.webserviceX.NET/");
        operation.setOutputMessageName("ConversionRateSoapOut");
        operation.setOutputMessageText(
                "<ConversionRate><ConversionRateResult>0</ConversionRateResult></ConversionRate>");
        operation.setSoapActionURI("http://www.webserviceX.NET/ConversionRate");
        operation.setStyle("document");
        operation.setTargetMethodName("ConversionRate");
        operation.setTargetObjectURI(null);
        operation.setTargetURL("http://www.webservicex.net/CurrencyConvertor.asmx");

        // Determine if the operation style is RPC
        boolean isRPC = operation.getStyle().equalsIgnoreCase("rpc");

        // All connections are created by using a connection factory
        SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance();

        // Now we can create a SOAPConnection object using the connection factory
        SOAPConnection connection = conFactory.createConnection();

        // All SOAP messages are created by using a message factory
        MessageFactory msgFactory = MessageFactory.newInstance();

        // Now we can create the SOAP message object
        SOAPMessage msg = msgFactory.createMessage();

        // Get the SOAP part from the SOAP message object
        SOAPPart soapPart = msg.getSOAPPart();

        // The SOAP part object will automatically contain the SOAP envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        //envelope.addNamespaceDeclaration("", operation.getNamespaceURI());

        if (isRPC) {
            // Add namespace declarations to the envelope, usually only required for RPC/encoded
            envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI);
            envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI);
        }

        // Get the SOAP header from the envelope
        SOAPHeader header = envelope.getHeader();

        // The client does not yet support SOAP headers
        header.detachNode();

        // Get the SOAP body from the envelope and populate it
        SOAPBody body = envelope.getBody();

        // Create the default namespace for the SOAP body
        //body.addNamespaceDeclaration("", operation.getNamespaceURI());

        // Add the service information
        String targetObjectURI = operation.getTargetObjectURI();

        if (targetObjectURI == null) {
            // The target object URI should not be null
            targetObjectURI = "";
        }

        // Add the service information
        //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI);
        Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns2", operation.getNamespaceURI());
        SOAPElement svcElem = body.addChildElement(svcInfo);

        if (isRPC) {
            // Set the encoding style of the service element
            svcElem.setEncodingStyle(operation.getEncodingStyle());
        }

        // Add the message contents to the SOAP body
        Document doc = XMLSupport.readXML(operation.getInputMessageText());

        if (doc.hasRootElement()) {
            // Begin building content
            buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC);
        }

        //svcElem.addTextNode(operation.getInputMessageText());
        //svcElem.

        // Check for a SOAPAction
        String soapActionURI = operation.getSoapActionURI();

        if (soapActionURI != null && soapActionURI.length() > 0) {
            // Add the SOAPAction value as a MIME header
            MimeHeaders mimeHeaders = msg.getMimeHeaders();
            mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\"");
        }

        // Save changes to the message we just populated
        msg.saveChanges();

        // Get ready for the invocation
        URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL());

        // Show the URL endpoint message in the log
        ByteArrayOutputStream msgStream = new ByteArrayOutputStream();
        msg.writeTo(msgStream);

        log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL());
        log.debug("SOAP Request: " + msgStream.toString());

        // Make the call
        SOAPMessage response = connection.call(msg, endpoint);

        // Close the connection, we are done with it
        connection.close();

        // Get the content of the SOAP response
        Source responseContent = response.getSOAPPart().getContent();

        // Convert the SOAP response into a JDOM
        TransformerFactory tFact = TransformerFactory.newInstance();
        Transformer transformer = tFact.newTransformer();

        JDOMResult jdomResult = new JDOMResult();
        transformer.transform(responseContent, jdomResult);

        // Get the document created by the transform operation
        Document responseDoc = jdomResult.getDocument();

        // Send the response to the Log
        String strResponse = XMLSupport.outputString(responseDoc);
        log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse);

        // Set the response as the output message
        operation.setOutputMessageText(strResponse);

        // Return the response generated
        //return strResponse;
    }

    catch (Throwable ex) {
        log.error("Error invoking operation:");
        log.error(ex.getMessage());
    }

    //return "";
}

From source file:Main.java

public static Document documentFromSoapBody(SOAPMessage soapMessage)
        throws ParserConfigurationException, SOAPException {
    SOAPEnvelope env = soapMessage.getSOAPPart().getEnvelope();
    SOAPBodyElement body = (SOAPBodyElement) soapMessage.getSOAPBody().getChildNodes().item(0);
    return documentFromSoapBody(body, getNamespaceDeclarations(env, body));
}

From source file:Main.java

public static Document documentFromSoapBody(SOAPMessage soapMessage, QName bodyName)
        throws ParserConfigurationException, SOAPException {
    SOAPEnvelope env = soapMessage.getSOAPPart().getEnvelope();
    SOAPBodyElement body = (SOAPBodyElement) soapMessage.getSOAPBody().getChildElements(bodyName).next();
    return documentFromSoapBody(body, getNamespaceDeclarations(env, body));
}

From source file:com.hiperium.commons.client.soap.AthenticationDispatcherTest.java

/**
 * /*from  ww  w  .  j a  v  a2 s  . com*/
 * @return
 */
public static SOAPMessage createEndSessionSOAPMessage() {
    SOAPMessage soapMessage = null;
    try {
        soapMessage = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        // Add message body parameters
        SOAPBody soapBody = soapEnvelope.getBody();
        soapBody.addChildElement("endSession", "ns2", "https://sei.general.soap.web.hiperium.com/");

        // Check the input
        System.out.println("REQUEST:");
        soapMessage.writeTo(System.out);
        System.out.println();

    } catch (SOAPException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return soapMessage;
}

From source file:com.hiperium.commons.client.soap.AthenticationDispatcherTest.java

/**
 * /*from  w  w  w  . j ava 2s .  c o  m*/
 * @return
 */
public static SOAPMessage createAuthSOAPMessage(UserCredentialDTO dto) {
    SOAPMessage soapMessage = null;
    try {
        soapMessage = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        // Add message body parameters
        SOAPBody soapBody = soapEnvelope.getBody();
        SOAPElement method = soapBody.addChildElement("userAuthentication", "ns2",
                "https://sei.authentication.soap.web.hiperium.com/");
        SOAPElement argument = method.addChildElement("arg0");
        argument.addChildElement("email").addTextNode(dto.getEmail());
        argument.addChildElement("password").addTextNode(dto.getPassword());

        // Check the input
        System.out.println("REQUEST:");
        soapMessage.writeTo(System.out);
        System.out.println();

    } catch (SOAPException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return soapMessage;
}

From source file:com.hiperium.commons.client.soap.AthenticationDispatcherTest.java

/**
 * //from w  w w  .  j  av a 2s. c o  m
 * @return
 */
public static SOAPMessage createSelectHomeSOAPMessage(HomeSelectionDTO dto) {
    SOAPMessage soapMessage = null;
    try {
        soapMessage = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        // Add message body parameters
        SOAPBody soapBody = soapEnvelope.getBody();
        SOAPElement method = soapBody.addChildElement("selectHome", "ns2",
                "https://sei.authentication.soap.web.hiperium.com/");
        SOAPElement argument = method.addChildElement("arg0");
        argument.addChildElement("homeId").addTextNode(dto.getHomeId().toString());
        argument.addChildElement("profileId").addTextNode(dto.getProfileId().toString());

        // Check the input
        System.out.println("REQUEST:");
        soapMessage.writeTo(System.out);
        System.out.println();

    } catch (SOAPException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return soapMessage;
}