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:org.wso2.carbon.identity.provisioning.connector.UserUpdation.java

private static SOAPMessage createUserObject(String userId, String serviceId, String loginId, String login,
        String firstName, String name, String mail, String phone, String status, String role,
        String extraFields) throws SOAPException, IdentityProvisioningException {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    String serverURI = InweboConnectorConstants.INWEBO_URI;
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("con", serverURI);
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("loginUpdate", "con");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("userid", "con");
    soapBodyElem1.addTextNode(userId);/*from  w  ww  .  j a  v  a2 s  . com*/
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("serviceid", "con");
    soapBodyElem2.addTextNode(serviceId);
    SOAPElement soapBodyElem3 = soapBodyElem.addChildElement("loginid", "con");
    soapBodyElem3.addTextNode(loginId);
    SOAPElement soapBodyElem4 = soapBodyElem.addChildElement("login", "con");
    soapBodyElem4.addTextNode(login);
    SOAPElement soapBodyElem5 = soapBodyElem.addChildElement("firstname", "con");
    soapBodyElem5.addTextNode(firstName);
    SOAPElement soapBodyElem6 = soapBodyElem.addChildElement("name", "con");
    soapBodyElem6.addTextNode(name);
    SOAPElement soapBodyElem7 = soapBodyElem.addChildElement("mail", "con");
    soapBodyElem7.addTextNode(mail);
    SOAPElement soapBodyElem8 = soapBodyElem.addChildElement("phone", "con");
    soapBodyElem8.addTextNode(phone);
    SOAPElement soapBodyElem9 = soapBodyElem.addChildElement("status", "con");
    soapBodyElem9.addTextNode(status);
    SOAPElement soapBodyElem10 = soapBodyElem.addChildElement("role", "con");
    soapBodyElem10.addTextNode(role);
    SOAPElement soapBodyElem11 = soapBodyElem.addChildElement("extrafields", "con");
    soapBodyElem11.addTextNode(extraFields);
    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI + "/services/ConsoleAdmin");
    soapMessage.saveChanges();
    return soapMessage;
}

From source file:org.wso2.carbon.identity.sso.saml.util.SAMLSOAPUtils.java

/**
 *
 * Decode the request received by the samlecp servlet.
 * Validate the SOAP message/*  w  ww  .j  a  v  a 2 s . c  o  m*/
 * Check whether the SOAP body contains a valid SAML request
 * @param soapMessage
 * @return
 * @throws IdentitySAML2ECPException
 */
public static String decodeSOAPMessage(SOAPMessage soapMessage)
        throws IdentitySAML2ECPException, TransformerException {
    SOAPBody body;
    String samlRequest = null;
    String strElement;
    if (soapMessage != null) {
        try {
            body = soapMessage.getSOAPPart().getEnvelope().getBody();
        } catch (SOAPException e) {
            String err = "Invalid SOAP Request";
            throw new IdentitySAML2ECPException(err, e);
        }
        int elementSize = 0;
        Iterator<?> elements = body.getChildElements();
        while (elements.hasNext()) {
            SOAPElement element = (SOAPElement) elements.next();
            strElement = convertSOAPElementToString(element);
            samlRequest = Base64.getEncoder().encodeToString(strElement.getBytes());
            elementSize += 1;
        }
        if (elementSize == 0) {
            String err = "SOAP message body cannot be Null";
            throw new IdentitySAML2ECPException(err);
        } else if (elementSize > 1) {
            String err = "SOAP Message body should Only contain a valid SAML Request";
            throw new IdentitySAML2ECPException(err);
        }
    } else {
        String err = "Empty SOAP Request";
        throw new IdentitySAML2ECPException(err);
    }
    return samlRequest;
}

From source file:org.wso2.carbon.identity.sso.saml.util.SAMLSOAPUtils.java

/**
 *
 * Creates a SOAP Fault message including the fault code and fault string.
 * @param faultString detailed error message
 * @param faultcode/*from  ww w  .j ava  2  s  . c o  m*/
 * @return
 */
public static String createSOAPFault(String faultString, String faultcode)
        throws TransformerException, SOAPException {
    SOAPMessage soapMsg;
    MessageFactory factory = MessageFactory.newInstance();
    soapMsg = factory.createMessage();
    SOAPPart part = soapMsg.getSOAPPart();
    SOAPEnvelope envelope = part.getEnvelope();
    SOAPBody body = envelope.getBody();
    SOAPFault fault = body.addFault();
    fault.setFaultString(faultString);
    fault.setFaultCode(new QName(SAMLECPConstants.SOAPNamespaceURI.SOAP_NAMESPACE_URI, faultcode));
    return convertSOAPMsgToString(soapMsg).replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
}

From source file:org.wso2.carbon.identity.sso.saml.util.SAMLSOAPUtils.java

/**
 *
 * @param samlRes SAML Response//from  w w w . j  ava 2  s . co m
 * @param acUrl Assertion Consumer URL
 * @return
 */
public static String createSOAPMessage(String samlRes, String acUrl)
        throws TransformerException, SOAPException {
    SOAPMessage soapMsg;
    MessageFactory factory = MessageFactory.newInstance();
    soapMsg = factory.createMessage();
    SOAPPart part = soapMsg.getSOAPPart();
    SOAPEnvelope envelope = part.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPHeaderElement soapHeaderElement = header.addHeaderElement(
            envelope.createName(SAMLECPConstants.SOAPECPHeaderElements.SOAP_ECP_HEADER_LOCAL_NAME,
                    SAMLECPConstants.SOAPECPHeaderElements.SOAP_ECP_HEADER_PREFIX,
                    SAMLECPConstants.SOAPECPHeaderElements.SOAP_ECP_HEADER_URI));
    soapHeaderElement.setMustUnderstand(true);
    soapHeaderElement.setActor(SAMLECPConstants.SOAPHeaderElements.SOAP_HEADER_ELEMENT_ACTOR);
    soapHeaderElement.addAttribute(new QName(SAMLECPConstants.SOAPHeaderElements.SOAP_HEADER_ELEMENT_ACS_URL),
            acUrl);
    SOAPBody body = envelope.getBody();
    String rawxml = "<![CDATA[" + samlRes + "]]>";
    body.addTextNode(rawxml);
    return convertSOAPMsgToString(soapMsg).replace("<![CDATA[", "").replace("]]>", "");
}

From source file:org.wso2.carbon.identity.sso.saml.util.SAMLSOAPUtils.java

/**
 *Converts a  SOAP Message to String./*  w w w  .  j  a  v  a 2s  .  c  o m*/
 * @param soapMessage
 * @return
 */
public static String convertSOAPMsgToString(SOAPMessage soapMessage) throws TransformerException {
    String strElement;
    final StringWriter stringWriter = new StringWriter();
    TransformerFactory.newInstance().newTransformer().transform(new DOMSource(soapMessage.getSOAPPart()),
            new StreamResult(stringWriter));
    strElement = stringWriter.toString();
    return strElement;
}

From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.wstep.util.MessageHandler.java

/**
 * This method adds Timestamp for SOAP header, and adds Content-length for HTTP header for
 * avoiding HTTP chunking./*  ww  w . j  a v  a2  s.  c om*/
 *
 * @param context
 */
@Override
public boolean handleMessage(SOAPMessageContext context) {

    Boolean outBoundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    if (outBoundProperty) {

        SOAPMessage message = context.getMessage();
        SOAPHeader header = null;
        SOAPEnvelope envelope = null;

        try {
            header = message.getSOAPHeader();
            envelope = message.getSOAPPart().getEnvelope();
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        if (header == null) {
            try {
                header = envelope.addHeader();
            } catch (SOAPException e) {
                Response.serverError().build();
            }
        }
        SOAPFactory soapFactory = null;

        try {
            soapFactory = SOAPFactory.newInstance();
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        QName qNamesSecurity = new QName(Constants.CertificateEnrollment.WS_SECURITY_TARGET_NAMESPACE,
                Constants.CertificateEnrollment.SECURITY);

        SOAPHeaderElement Security = null;

        try {
            Security = header.addHeaderElement(qNamesSecurity);
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        Name attributeName = null;
        try {
            attributeName = soapFactory.createName(Constants.CertificateEnrollment.TIMESTAMP_ID,
                    Constants.CertificateEnrollment.TIMESTAMP_U,
                    Constants.CertificateEnrollment.WSS_SECURITY_UTILITY);
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        QName qNameTimestamp = new QName(Constants.CertificateEnrollment.WSS_SECURITY_UTILITY,
                Constants.CertificateEnrollment.TIMESTAMP);
        SOAPHeaderElement timestamp = null;

        try {
            timestamp = header.addHeaderElement(qNameTimestamp);
            timestamp.addAttribute(attributeName, Constants.CertificateEnrollment.TIMESTAMP_0);
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        DateTime dateTime = new DateTime();
        DateTime expiredDateTime = dateTime.plusMinutes(5);
        String createdISOTime = dateTime.toString(ISODateTimeFormat.dateTime());
        String expiredISOTime = expiredDateTime.toString(ISODateTimeFormat.dateTime());
        createdISOTime = createdISOTime.substring(0, createdISOTime.length() - 6);
        createdISOTime = createdISOTime + "Z";
        expiredISOTime = expiredISOTime.substring(0, expiredISOTime.length() - 6);
        expiredISOTime = expiredISOTime + "Z";

        QName qNameCreated = new QName(Constants.CertificateEnrollment.WSS_SECURITY_UTILITY,
                Constants.CertificateEnrollment.CREATED);
        SOAPHeaderElement SOAPHeaderCreated = null;

        try {
            SOAPHeaderCreated = header.addHeaderElement(qNameCreated);
            SOAPHeaderCreated.addTextNode(createdISOTime);
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        QName qNameExpires = new QName(Constants.CertificateEnrollment.WSS_SECURITY_UTILITY,
                Constants.CertificateEnrollment.EXPIRES);
        SOAPHeaderElement SOAPHeaderExpires = null;

        try {
            SOAPHeaderExpires = header.addHeaderElement(qNameExpires);
            SOAPHeaderExpires.addTextNode(expiredISOTime);
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        try {
            timestamp.addChildElement(SOAPHeaderCreated);
            timestamp.addChildElement(SOAPHeaderExpires);
            Security.addChildElement(timestamp);
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        try {
            message.saveChanges();
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            message.writeTo(outputStream);
        } catch (IOException e) {
            Response.serverError().build();
        } catch (SOAPException e) {
            Response.serverError().build();
        }

        String messageString = null;
        try {
            messageString = new String(outputStream.toByteArray(), Constants.CertificateEnrollment.UTF_8);
        } catch (UnsupportedEncodingException e) {
            Response.serverError().build();
        }

        Map<String, List<String>> headers = (Map<String, List<String>>) context
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        headers = new HashMap<String, List<String>>();
        headers.put(Constants.CertificateEnrollment.CONTENT_LENGTH,
                Arrays.asList(String.valueOf(messageString.length())));
        context.put(MessageContext.HTTP_REQUEST_HEADERS, headers);

    }
    return true;
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

private static VerifyResult verifyMessage(final SOAPMessage message) throws Exception {
    final long startMs = System.currentTimeMillis();
    try {//w w w.  ja  v a 2 s. c o  m
        final SOAPPart doc = message.getSOAPPart();
        final SOAPEnvelope envelope = doc.getEnvelope();
        final SOAPHeader soapHeader = message.getSOAPHeader();
        final Element recipient = findSecurityToken(soapHeader, ACTOR_RECIPIENT);
        final X509Certificate recipientCert;
        if (recipient != null) {
            final ValidateResult recipientResult = validate(recipient);
            if (recipientResult.error != null) {
                return new VerifyResult(" : " + recipientResult.error, null,
                        recipientResult.cert);
            }
            recipientCert = recipientResult.cert;
        } else {
            recipientCert = null;
        }
        final Element smev = findSecurityToken(soapHeader, ACTOR_SMEV);
        if (smev == null) {
            return new VerifyResult(" : ??", null, recipientCert);
        }
        final ValidateResult smevResult = validate(smev);
        return new VerifyResult(smevResult.error, smevResult.cert, recipientCert);
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("VERIFY: " + (System.currentTimeMillis() - startMs) + "ms");
        }
    }
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

public void sign(final SOAPMessage message) {
    try {//w w  w. j  a v  a 2  s .c o m
        loadCertificate();

        final long startMs = System.currentTimeMillis();

        final SOAPPart doc = message.getSOAPPart();
        final QName wsuId = doc.getEnvelope().createQName("Id", "wsu");
        final SOAPHeader header = message.getSOAPHeader();
        final QName actor = header.createQName("actor", header.getPrefix());

        final SOAPElement security = header.addChildElement("Security", "wsse", WSSE);
        security.addAttribute(actor, ACTOR_SMEV);
        SOAPElement binarySecurityToken = security.addChildElement("BinarySecurityToken", "wsse");
        binarySecurityToken.setAttribute("EncodingType", WSS_BASE64_BINARY);
        binarySecurityToken.setAttribute("ValueType", WSS_X509V3);
        binarySecurityToken.setValue(DatatypeConverter.printBase64Binary(cert.getEncoded()));
        binarySecurityToken.addAttribute(wsuId, "CertId");

        XMLSignature signature = new XMLSignature(doc, "", XMLSignature.ALGO_ID_SIGNATURE_GOST_GOST3410_3411,
                Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        {
            Element element = signature.getElement();
            Element keyInfo = doc.createElementNS(Constants.SignatureSpecNS, "KeyInfo");
            Element securityTokenReference = doc.createElementNS(WSSE, "SecurityTokenReference");
            Element reference = doc.createElementNS(WSSE, "Reference");
            reference.setAttribute("URI", "#CertId");
            reference.setAttribute("ValueType", WSS_X509V3);
            securityTokenReference.appendChild(reference);
            keyInfo.appendChild(securityTokenReference);
            element.appendChild(keyInfo);
            security.appendChild(element);
        }
        Transforms transforms = new Transforms(doc);
        transforms.addTransform(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        signature.addDocument("#body", transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_GOST3411);
        signature.sign(privateKey);
        if (log.isDebugEnabled()) {
            log.debug("SIGN: " + (System.currentTimeMillis() - startMs) + "ms");
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:test.functional.TestJAXMSamples.java

public void testJWSFault() throws Exception {
    try {//from w w w.j a v  a  2 s  .  c om
        SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection con = scFactory.createConnection();

        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage message = factory.createMessage();

        SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
        SOAPBody body = envelope.getBody();

        Name bodyName = envelope.createName("echo");
        SOAPBodyElement bodyElement = body.addBodyElement(bodyName);

        Name name = envelope.createName("arg0");
        SOAPElement symbol = bodyElement.addChildElement(name);
        symbol.addTextNode("Hello");

        URLEndpoint endpoint = new URLEndpoint("http://localhost:8080/jws/FaultTest.jws");
        SOAPMessage response = con.call(message, endpoint);
        SOAPBody respBody = response.getSOAPPart().getEnvelope().getBody();
        assertTrue(respBody.hasFault());
    } catch (javax.xml.soap.SOAPException e) {
        Throwable t = e.getCause();
        if (t != null) {
            t.printStackTrace();
            if (t instanceof AxisFault) {
                AxisFault af = (AxisFault) t;
                if ((af.detail instanceof SocketException)
                        || (af.getFaultCode().getLocalPart().equals("HTTP"))) {
                    System.out.println("Connect failure caused testJWSFault to be skipped.");
                    return;
                }
            }
            throw new Exception("Fault returned from test: " + t);
        } else {
            e.printStackTrace();
            throw new Exception("Exception returned from test: " + e);
        }
    } catch (Throwable t) {
        t.printStackTrace();
        throw new Exception("Fault returned from test: " + t);
    }
}

From source file:test.integ.be.agiv.security.Axis2Test.java

@Test
public void testWSSecurityHandler() throws Exception {
    // setup/*  ww  w  .j ava 2 s. c  o  m*/
    WSSecurityHandler testedInstance = new WSSecurityHandler();

    SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class);

    EasyMock.expect(mockContext.get("javax.xml.ws.handler.message.outbound")).andStubReturn(Boolean.TRUE);
    EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.token")).andStubReturn(null);
    String testUsername = "username-" + UUID.randomUUID().toString();
    EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.username"))
            .andStubReturn(testUsername);
    EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.password"))
            .andStubReturn("password");
    EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.key")).andStubReturn(null);
    EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.certificate"))
            .andStubReturn(null);

    SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createMessage(null,
            new ByteArrayInputStream(
                    "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\"><Body>test</Body></Envelope>"
                            .getBytes()));

    LOG.debug("SOAP message: " + toString(soapMessage.getSOAPPart()));
    EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage);

    // prepare
    EasyMock.replay(mockContext);

    // operate
    testedInstance.handleMessage(mockContext);

    // verify
    EasyMock.verify(mockContext);
    LOG.debug("SOAP message after handleMessage: " + toString(soapMessage.getSOAPPart()));
}