Example usage for javax.xml.soap SOAPHeaderElement addTextNode

List of usage examples for javax.xml.soap SOAPHeaderElement addTextNode

Introduction

In this page you can find the example usage for javax.xml.soap SOAPHeaderElement addTextNode.

Prototype

public SOAPElement addTextNode(String text) throws SOAPException;

Source Link

Document

Creates a new Text object initialized with the given String and adds it to this SOAPElement object.

Usage

From source file:com.amazon.advertising.api.common.HmacSecurityHandler.java

public void invoke(MessageContext mc) throws AxisFault {
    String actionUri = mc.getSOAPActionURI();
    String tokens[] = actionUri.split("/");
    String action = tokens[tokens.length - 1];

    String timestamp = getTimestamp();
    String signature;//ww w. j  a v a2s.co  m
    try {
        signature = this.calculateSignature(action, timestamp);
    } catch (Exception e) {
        throw AxisFault.makeFault(e);
    }

    try {
        SOAPMessageContext smc = (SOAPMessageContext) mc;
        SOAPMessage message = smc.getMessage();
        SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
        SOAPHeader header = envelope.getHeader();
        header.addNamespaceDeclaration(AWS_SECURITY_NS_PREFIX, AWS_SECURITY_NS);

        Name akidName = envelope.createName("AWSAccessKeyId", AWS_SECURITY_NS_PREFIX, AWS_SECURITY_NS);
        Name tsName = envelope.createName("Timestamp", AWS_SECURITY_NS_PREFIX, AWS_SECURITY_NS);
        Name sigName = envelope.createName("Signature", AWS_SECURITY_NS_PREFIX, AWS_SECURITY_NS);

        SOAPHeaderElement akidElement = header.addHeaderElement(akidName);
        SOAPHeaderElement tsElement = header.addHeaderElement(tsName);
        SOAPHeaderElement sigElement = header.addHeaderElement(sigName);

        akidElement.addTextNode(awsAccessKeyId);
        tsElement.addTextNode(timestamp);
        sigElement.addTextNode(signature);
    } catch (SOAPException e) {
        throw AxisFault.makeFault(e);
    }
}

From source file:be.agiv.security.handler.WSAddressingHandler.java

private void handleOutboundMessage(SOAPMessageContext context) throws SOAPException {
    LOG.debug("adding WS-Addressing headers");
    SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
    SOAPHeader header = envelope.getHeader();
    if (null == header) {
        header = envelope.addHeader();//from ww w  . j a  v a2s.c  om
    }

    String wsuPrefix = null;
    String wsAddrPrefix = null;
    Iterator namespacePrefixesIter = envelope.getNamespacePrefixes();
    while (namespacePrefixesIter.hasNext()) {
        String namespacePrefix = (String) namespacePrefixesIter.next();
        String namespace = envelope.getNamespaceURI(namespacePrefix);
        if (WSConstants.WS_ADDR_NAMESPACE.equals(namespace)) {
            wsAddrPrefix = namespacePrefix;
        } else if (WSConstants.WS_SECURITY_UTILITY_NAMESPACE.equals(namespace)) {
            wsuPrefix = namespacePrefix;
        }
    }
    if (null == wsAddrPrefix) {
        wsAddrPrefix = getUniquePrefix("a", envelope);
        envelope.addNamespaceDeclaration(wsAddrPrefix, WSConstants.WS_ADDR_NAMESPACE);
    }
    if (null == wsuPrefix) {
        /*
         * Using "wsu" is very important for the IP-STS X509 credential.
         * Apparently the STS refuses when the namespace prefix of the
         * wsu:Id on the WS-Addressing To element is different from the
         * wsu:Id prefix on the WS-Security timestamp.
         */
        wsuPrefix = "wsu";
        envelope.addNamespaceDeclaration(wsuPrefix, WSConstants.WS_SECURITY_UTILITY_NAMESPACE);
    }

    SOAPFactory factory = SOAPFactory.newInstance();

    SOAPHeaderElement actionHeaderElement = header
            .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "Action", wsAddrPrefix));
    actionHeaderElement.setMustUnderstand(true);
    actionHeaderElement.addTextNode(this.action);

    SOAPHeaderElement messageIdElement = header
            .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "MessageID", wsAddrPrefix));
    String messageId = "urn:uuid:" + UUID.randomUUID().toString();
    context.put(MESSAGE_ID_CONTEXT_ATTRIBUTE, messageId);
    messageIdElement.addTextNode(messageId);

    SOAPHeaderElement replyToElement = header
            .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "ReplyTo", wsAddrPrefix));
    SOAPElement addressElement = factory.createElement("Address", wsAddrPrefix, WSConstants.WS_ADDR_NAMESPACE);
    addressElement.addTextNode("http://www.w3.org/2005/08/addressing/anonymous");
    replyToElement.addChildElement(addressElement);

    SOAPHeaderElement toElement = header
            .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "To", wsAddrPrefix));
    toElement.setMustUnderstand(true);

    toElement.addTextNode(this.to);

    String toIdentifier = "to-id-" + UUID.randomUUID().toString();
    toElement.addAttribute(new QName(WSConstants.WS_SECURITY_UTILITY_NAMESPACE, "Id", wsuPrefix), toIdentifier);
    try {
        toElement.setIdAttributeNS(WSConstants.WS_SECURITY_UTILITY_NAMESPACE, "Id", true);
    } catch (UnsupportedOperationException e) {
        // Axis2 has missing implementation of setIdAttributeNS
        LOG.error("error setting Id attribute: " + e.getMessage());
    }
    context.put(TO_ID_CONTEXT_ATTRIBUTE, toIdentifier);
}

From source file:org.springframework.integration.sqs.AWSSecurityHandler.java

/**
 * {@inheritDoc}//www  .  j  av  a 2s.com
 */
public boolean handleMessage(final SOAPMessageContext context) {
    logMessage(context);
    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (!outboundProperty) {
        return true;
    }

    /*
     * Example SOAP header from
     * http://docs.amazonwebservices.com/AWSSimpleQueueService
     * /2008-01-01/SQSDeveloperGuide
     * /MakingRequests_MakingSOAPRequestsArticle.html
     * 
     * <soapenv:Header
     * xmlns:aws="http://security.amazonaws.com/doc/2007-01-01/">
     * <aws:AWSAccessKeyId>1D9FVRAYCP1VJS767E02EXAMPLE</aws:AWSAccessKeyId>
     * <aws:Timestamp>2008-02-10T23:59:59Z</aws:Timestamp>
     * <aws:Signature>SZf1CHmQ/nrZbsrC13hCZS061ywsEXAMPLE</aws:Signature>
     * </soapenv:Header>
     */

    SOAPMessage aSOAPMessage = context.getMessage();
    try {
        SOAPEnvelope aEnvelope = aSOAPMessage.getSOAPPart().getEnvelope();
        SOAPHeader aHeader = aEnvelope.addHeader();
        String aTimestampStr = this.getTimestamp();
        // ADD AWS SECURITY HEADER ----------------------------------------
        aHeader.addNamespaceDeclaration(NAMESPACE_AWS_PREFIX, NAMESPACE_AWS);

        // ADD ACCESS KEY -------------------------------------------------
        Name aKeyName = aEnvelope.createName("AWSAccessKeyId", NAMESPACE_AWS_PREFIX, NAMESPACE_AWS);
        SOAPHeaderElement aKey = aHeader.addHeaderElement(aKeyName);
        aKey.addTextNode(s_key);

        // ADD TIMESTAMP --------------------------------------------------
        Name aTimestampName = aEnvelope.createName("Timestamp", NAMESPACE_AWS_PREFIX, NAMESPACE_AWS);
        SOAPHeaderElement aTimestamp = aHeader.addHeaderElement(aTimestampName);
        aTimestamp.addTextNode(aTimestampStr);

        // ADD SIGNATURE --------------------------------------------------
        Name aSignatureName = aEnvelope.createName("Signature", NAMESPACE_AWS_PREFIX, NAMESPACE_AWS);
        SOAPHeaderElement aSignature = aHeader.addHeaderElement(aSignatureName);

        SOAPBody aBody = aEnvelope.getBody();
        Iterator<?> aChildren = aBody.getChildElements();
        SOAPBodyElement aAction = (SOAPBodyElement) aChildren.next();
        if (aChildren.hasNext()) {
            throw new IllegalStateException(
                    "Unexpected number of actions in soap request. Cannot calculate signature.");
        }
        aSignature.addTextNode(this.calculateSignature(aAction.getLocalName(), aTimestampStr));
        aSOAPMessage.saveChanges();
        logMessage("Final out message: ", aSOAPMessage);
    } catch (Exception e) {
        throw new IllegalStateException("Failed to add aws headers!", e);
    }
    return true;
}

From source file:org.wso2.carbon.device.mgt.mobile.windows.api.services.enrollment.util.MessageHandler.java

/**
 * This method adds Timestamp for SOAP header, and adds Content-length for HTTP header for
 * avoiding HTTP chunking.//from   w w  w  .ja v  a  2s .  c o  m
 *
 * @param context - Context of the SOAP Message
 */
@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().entity("SOAP message content cannot be read.").build();
        }
        try {
            if ((header == null) && (envelope != null)) {
                header = envelope.addHeader();
            }
        } catch (SOAPException e) {
            Response.serverError().entity("SOAP header cannot be added.").build();
        }

        SOAPFactory soapFactory = null;
        try {
            soapFactory = SOAPFactory.newInstance();
        } catch (SOAPException e) {
            Response.serverError().entity("Cannot get an instance of SOAP factory.").build();
        }

        QName qNamesSecurity = new QName(PluginConstants.WS_SECURITY_TARGET_NAMESPACE,
                PluginConstants.CertificateEnrolment.SECURITY);
        SOAPHeaderElement Security = null;
        Name attributeName = null;
        try {
            if (header != null) {
                Security = header.addHeaderElement(qNamesSecurity);
            }
            if (soapFactory != null) {
                attributeName = soapFactory.createName(PluginConstants.CertificateEnrolment.TIMESTAMP_ID,
                        PluginConstants.CertificateEnrolment.TIMESTAMP_U,
                        PluginConstants.CertificateEnrolment.WSS_SECURITY_UTILITY);
            }
        } catch (SOAPException e) {
            Response.serverError().entity("Security header cannot be added.").build();
        }

        QName qNameTimestamp = new QName(PluginConstants.CertificateEnrolment.WSS_SECURITY_UTILITY,
                PluginConstants.CertificateEnrolment.TIMESTAMP);
        SOAPHeaderElement timestamp = null;
        try {
            if (header != null) {
                timestamp = header.addHeaderElement(qNameTimestamp);
                timestamp.addAttribute(attributeName, PluginConstants.CertificateEnrolment.TIMESTAMP_0);
            }
        } catch (SOAPException e) {
            Response.serverError().entity("Exception while adding timestamp header.").build();
        }
        DateTime dateTime = new DateTime();
        DateTime expiredDateTime = dateTime.plusMinutes(VALIDITY_TIME);
        String createdISOTime = dateTime.toString(ISODateTimeFormat.dateTime());
        String expiredISOTime = expiredDateTime.toString(ISODateTimeFormat.dateTime());
        createdISOTime = createdISOTime.substring(TIMESTAMP_BEGIN_INDEX,
                createdISOTime.length() - TIMESTAMP_END_INDEX);
        createdISOTime = createdISOTime + TIME_ZONE;
        expiredISOTime = expiredISOTime.substring(TIMESTAMP_BEGIN_INDEX,
                expiredISOTime.length() - TIMESTAMP_END_INDEX);
        expiredISOTime = expiredISOTime + TIME_ZONE;
        QName qNameCreated = new QName(PluginConstants.CertificateEnrolment.WSS_SECURITY_UTILITY,
                PluginConstants.CertificateEnrolment.CREATED);
        SOAPHeaderElement SOAPHeaderCreated = null;

        try {
            if (header != null) {
                SOAPHeaderCreated = header.addHeaderElement(qNameCreated);
                SOAPHeaderCreated.addTextNode(createdISOTime);
            }
        } catch (SOAPException e) {
            Response.serverError().entity("Exception while creating SOAP header.").build();
        }
        QName qNameExpires = new QName(PluginConstants.CertificateEnrolment.WSS_SECURITY_UTILITY,
                PluginConstants.CertificateEnrolment.EXPIRES);
        SOAPHeaderElement SOAPHeaderExpires = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String messageString = null;
        try {
            if (header != null) {
                SOAPHeaderExpires = header.addHeaderElement(qNameExpires);
                SOAPHeaderExpires.addTextNode(expiredISOTime);
            }
            if ((timestamp != null) && (Security != null)) {
                timestamp.addChildElement(SOAPHeaderCreated);
                timestamp.addChildElement(SOAPHeaderExpires);
                Security.addChildElement(timestamp);
            }
            message.saveChanges();
            message.writeTo(outputStream);
            messageString = new String(outputStream.toByteArray(), PluginConstants.CertificateEnrolment.UTF_8);
        } catch (SOAPException e) {
            Response.serverError().entity("Exception while creating timestamp SOAP header.").build();
        } catch (IOException e) {
            Response.serverError().entity("Exception while writing message to output stream.").build();
        }

        Map<String, List<String>> headers = (Map<String, List<String>>) context
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        headers = new HashMap<String, List<String>>();
        if (messageString != null) {
            headers.put(PluginConstants.CONTENT_LENGTH, Arrays.asList(String.valueOf(messageString.length())));
        }
        context.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
    }
    return true;
}

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.//from   ww  w  .j  av  a 2s  . c o  m
 *
 * @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;
}