Example usage for javax.xml.soap SOAPHeader addHeaderElement

List of usage examples for javax.xml.soap SOAPHeader addHeaderElement

Introduction

In this page you can find the example usage for javax.xml.soap SOAPHeader addHeaderElement.

Prototype

public SOAPHeaderElement addHeaderElement(QName qname) throws SOAPException;

Source Link

Document

Creates a new SOAPHeaderElement object initialized with the specified qname and adds it to this SOAPHeader 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 w w.j  a v  a 2s.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();

}

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(/*w  ww  .ja va 2  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();

    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 w ww .  j  a v  a  2  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();

    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(/*from   w  w  w  .ja  va 2 s.com*/
                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:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java

private static final SOAPMessage getMessageToSign(final String pathBase) throws SOAPException, IOException {
    final SOAPMessage soapMessage;
    final SOAPPart soapPart;
    final SOAPEnvelope soapEnvelope;
    final SOAPHeader soapHeader;
    final SOAPHeaderElement secElement;
    final SOAPElement binaryTokenElement;

    soapMessage = SoapMessageUtils.getMessage(pathBase);
    soapPart = soapMessage.getSOAPPart();
    soapEnvelope = soapPart.getEnvelope();
    soapHeader = soapEnvelope.getHeader();

    secElement = soapHeader.addHeaderElement(soapEnvelope.createName("Security", "wsse",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"));
    binaryTokenElement = secElement.addChildElement(soapEnvelope.createName("BinarySecurityToken", "wsse",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"));
    binaryTokenElement.setAttribute("EncodingType",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
    binaryTokenElement.setAttribute("ValueType",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3");

    return soapMessage;
}

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;//from  ww w . j  a  v  a2s  .  c om
    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:it.cnr.icar.eric.common.SOAPMessenger.java

/** Send a SOAP request to the registry server. Main entry point for
 * this class. If credentials have been set on the registry connection,
 * they will be used to sign the request.
 *
 * @param requestString//from  ww  w  .  j  a  v a2  s.c  om
 *     String that will be placed in the body of the
 *     SOAP message to be sent to the server
 *
 * @param attachments
 *     HashMap consisting of entries each of which
 *     corresponds to an attachment where the entry key is the ContentId
 *     and the entry value is a javax.activation.DataHandler of the
 *     attachment. A parameter value of null means no attachments.
 *
 * @return
 *     RegistryResponseHolder that represents the response from the
 *     server
 */
@SuppressWarnings("unchecked")
public RegistryResponseHolder sendSoapRequest(String requestString, Map<?, ?> attachments)
        throws JAXRException {
    boolean logRequests = Boolean.valueOf(
            CommonProperties.getInstance().getProperty("eric.common.soapMessenger.logRequests", "false"))
            .booleanValue();

    if (logRequests) {
        PrintStream requestLogPS = null;
        try {
            requestLogPS = new PrintStream(
                    new FileOutputStream(java.io.File.createTempFile("SOAPMessenger_requestLog", ".xml")));
            requestLogPS.println(requestString);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (requestLogPS != null) {
                requestLogPS.close();
            }
        }
    }

    // =================================================================

    //        // Remove the XML Declaration, if any
    //        if (requestString.startsWith("<?xml")) {
    //            requestString = requestString.substring(requestString.indexOf("?>")+2).trim();
    //        }
    //
    //        StringBuffer soapText = new StringBuffer(
    //                "<soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">");
    //
    //      soapText.append("<soap-env:Header>\n");
    //      // tell server about our superior SOAP Fault capabilities
    //      soapText.append("<");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName);
    //      soapText.append(" xmlns='");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_Namespace);
    //      soapText.append("'>");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes);
    //      soapText.append("</");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName);
    //      soapText.append(">\n");
    //      soapText.append("</soap-env:Header>\n");

    //      soapText.append("<soap-env:Body>\n");
    //        soapText.append(requestString);
    //        soapText.append("</soap-env:Body>");
    //        soapText.append("</soap-env:Envelope>");

    MessageFactory messageFactory;
    SOAPMessage message = null;
    SOAPPart sp = null;
    SOAPEnvelope se = null;
    SOAPBody sb = null;
    SOAPHeader sh = null;

    if (log.isTraceEnabled()) {
        log.trace("requestString=\"" + requestString + "\"");
    }
    try {

        messageFactory = MessageFactory.newInstance();
        message = messageFactory.createMessage();

        sp = message.getSOAPPart();
        se = sp.getEnvelope();
        sb = se.getBody();
        sh = se.getHeader();

        /*
         * <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
         *       <soap-env:Header>
         *          <capabilities xmlns="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</capabilities>
         *
         * change with explicit namespace
         *          <ns1:capabilities xmlns:ns1="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</ns1:capabilities>
                
         */
        SOAPHeaderElement capabilityElement = sh
                .addHeaderElement(se.createName(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName, "ns1",
                        BindingUtility.SOAP_CAPABILITY_HEADER_Namespace));
        //           capabilityElement.addAttribute(
        //                 se.createName("xmlns"), 
        //                 BindingUtility.SOAP_CAPABILITY_HEADER_Namespace);
        capabilityElement.setTextContent(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes);

        /*
         * body
         */

        // Remove the XML Declaration, if any
        if (requestString.startsWith("<?xml")) {
            requestString = requestString.substring(requestString.indexOf("?>") + 2).trim();
        }

        // Generate DOM Document from request xml string
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        InputStream stream = new ByteArrayInputStream(requestString.getBytes("UTF-8"));

        // Inject request into body
        sb.addDocument(builderFactory.newDocumentBuilder().parse(stream));

        // Is it never the case that there attachments but no credentials
        if ((attachments != null) && !attachments.isEmpty()) {
            addAttachments(message, attachments);
        }

        if (credentialInfo == null) {
            throw new JAXRException(resourceBundle.getString("message.credentialInfo"));
        }

        WSS4JSecurityUtilSAML.signSOAPEnvelopeOnClientSAML(se, credentialInfo);

        SOAPMessage response = send(message);

        // Check to see if the session has expired
        // by checking for an error response code
        // TODO: what error code to we look for?
        if (isSessionExpired(response)) {
            credentialInfo.sessionId = null;
            // sign the SOAPMessage this time
            // TODO: session - add method to do the signing
            // signSOAPMessage(msg);
            // send signed message
            // SOAPMessage response = send(msg);
        }

        // Process the main SOAPPart of the response
        //check for soapfault and throw RegistryException
        SOAPFault fault = response.getSOAPBody().getFault();
        if (fault != null) {
            throw createRegistryException(fault);
        }

        Reader reader = processResponseBody(response, "Response");

        RegistryResponseType ebResponse = null;

        try {
            Object obj = BindingUtility.getInstance().getJAXBContext().createUnmarshaller()
                    .unmarshal(new InputSource(reader));

            if (obj instanceof JAXBElement<?>)
                // if Element: take ComplexType from Element
                obj = ((JAXBElement<RegistryResponseType>) obj).getValue();

            ebResponse = (RegistryResponseType) obj;
        } catch (Exception x) {
            log.error(CommonResourceBundle.getInstance().getString("message.FailedToUnmarshalServerResponse"),
                    x);
            throw new JAXRException(resourceBundle.getString("message.invalidServerResponse"));
        }

        // Process the attachments of the response if any
        HashMap<String, Object> responseAttachments = processResponseAttachments(response);

        return new RegistryResponseHolder(ebResponse, responseAttachments);

    } catch (SAXException e) {
        throw new JAXRException(e);

    } catch (ParserConfigurationException e) {
        throw new JAXRException(e);

    } catch (UnsupportedEncodingException x) {
        throw new JAXRException(x);

    } catch (MessagingException x) {
        throw new JAXRException(x);

    } catch (FileNotFoundException x) {
        throw new JAXRException(x);

    } catch (IOException e) {
        throw new JAXRException(e);

    } catch (SOAPException x) {
        x.printStackTrace();
        throw new JAXRException(resourceBundle.getString("message.cannotConnect"), x);

    } catch (TransformerConfigurationException x) {
        throw new JAXRException(x);

    } catch (TransformerException x) {
        throw new JAXRException(x);
    }
}

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();// w ww .  j a  v a 2s  .co  m
    }

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