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:be.agiv.security.handler.WSSecurityHandler.java

private void handleInboundMessage(SOAPMessageContext context) throws WSSecurityException {
    LOG.debug("checking WS-Security header");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(soapPart, null, null, null);
    if (null == results) {
        throw new SecurityException("no WS-Security results");
    }//from  w w w.  j  ava  2  s .  c  om

    WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.TS);
    if (null == actionResult) {
        throw new SecurityException("no WS-Security timestamp result");
    }

    Timestamp receivedTimestamp = (Timestamp) actionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);
    if (null == receivedTimestamp) {
        throw new SecurityException("no WS-Security timestamp");
    }

    LOG.debug("WS-Security timestamp created: " + receivedTimestamp.getCreated());
    LOG.debug("WS-Security timestamp expires: " + receivedTimestamp.getExpires());
}

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

private void handleOutboundMessage(SOAPMessageContext context) throws WSSecurityException,
        ConversationException, SOAPException, IOException, XMLSignatureException, XMLSecurityException {
    LOG.debug("adding WS-Security header");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    SOAPHeader soapHeader = soapMessage.getSOAPHeader();
    if (null == soapHeader) {
        /*/*from   ww  w .j  a  v  a  2s .c o m*/
         * Work-around for Axis2.
         */
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
        soapHeader = soapEnvelope.addHeader();
    }

    WSSecHeader wsSecHeader = new WSSecHeader();
    Element securityElement = wsSecHeader.insertSecurityHeader(soapPart);

    addToken(context, securityElement);

    addUsernamePassword(context, soapPart, wsSecHeader);

    WSSecTimestamp wsSecTimeStamp = new WSSecTimestamp();
    wsSecTimeStamp.build(soapPart, wsSecHeader);

    addProofOfPossessionSignature(context, soapMessage, soapPart, wsSecHeader, wsSecTimeStamp);

    addCertificateSignature(context, soapPart, wsSecHeader, wsSecTimeStamp);

    /*
     * Really needs to be at the end for Axis2 to work. Axiom bug?
     */
    appendSecurityHeader(soapHeader, securityElement);
}

From source file:com.fortify.bugtracker.tgt.archer.connection.ArcherAuthenticatingRestConnection.java

public Long addValueToValuesList(Long valueListId, String value) {
    LOG.info("[Archer] Adding value '" + value + "' to value list id " + valueListId);
    // Adding items to value lists is not supported via REST API, so we need to revert to SOAP API
    // TODO Simplify this method?
    // TODO Make this method more fail-safe (like checking for the correct response element)?
    Long result = null;/*from ww w.  ja v a 2 s . c om*/
    try {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage message = messageFactory.createMessage();
        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody body = envelope.getBody();
        SOAPElement bodyElement = body.addChildElement(
                envelope.createName("CreateValuesListValue", "", "http://archer-tech.com/webservices/"));
        bodyElement.addChildElement("sessionToken").addTextNode(tokenProviderRest.getToken());
        bodyElement.addChildElement("valuesListId").addTextNode(valueListId + "");
        bodyElement.addChildElement("valuesListValueName").addTextNode(value);
        message.saveChanges();

        SOAPMessage response = executeRequest(HttpMethod.POST,
                getBaseResource().path("/ws/field.asmx").request()
                        .header("SOAPAction", "\"http://archer-tech.com/webservices/CreateValuesListValue\"")
                        .accept("text/xml"),
                Entity.entity(message, "text/xml"), SOAPMessage.class);
        @SuppressWarnings("unchecked")
        Iterator<Object> it = response.getSOAPBody().getChildElements();
        while (it.hasNext()) {
            Object o = it.next();
            if (o instanceof SOAPElement) {
                result = new Long(((SOAPElement) o).getTextContent());
            }
        }
        System.out.println(response);
    } catch (SOAPException e) {
        throw new RuntimeException("Error executing SOAP request", e);
    }
    return result;
}

From source file:backend.Weather.java

private void getSOAPResponse(SOAPMessage soapResponse) throws Exception {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    Source sourceContent = soapResponse.getSOAPPart().getContent();
    System.out.print("\nResponse SOAP Message = ");
    StreamResult result = new StreamResult(System.out);
    transformer.transform(sourceContent, result);
}

From source file:edu.duke.cabig.c3pr.webservice.integration.StudyImportExportWebServiceTest.java

private SOAPMessage prepareRequestEnvelope(String xmlFile, String wrapperElement)
        throws SOAPException, DOMException, IOException, SAXException, ParserConfigurationException {
    MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
    SOAPMessage reqMsg = mf.createMessage();
    SOAPPart part = reqMsg.getSOAPPart();
    SOAPEnvelope env = part.getEnvelope();
    SOAPBody body = env.getBody();

    SOAPElement operation = body.addChildElement(wrapperElement, "stud", SERVICE_NS);
    operation.appendChild(env.getOwnerDocument().importNode(getSOAPBodyFromXML(xmlFile), true));
    reqMsg.saveChanges();/*  w w w.ja v  a2  s . c o m*/
    return reqMsg;
}

From source file:edu.duke.cabig.c3pr.webservice.integration.StudyImportExportWebServiceTest.java

private void verifySuccessulImportResponse(SOAPMessage respMsg) throws SOAPException {
    SOAPPart part = respMsg.getSOAPPart();
    SOAPEnvelope env = part.getEnvelope();
    SOAPBody body = env.getBody();
    NodeList nodes = body.getElementsByTagNameNS(SERVICE_NS, "ImportStudyResponse");
    assertEquals(1, nodes.getLength());//from  w w  w.j a v a2s .  com
    // element should be empty
    Element responseEl = (Element) nodes.item(0);
    assertEquals(0, responseEl.getChildNodes().getLength());
}

From source file:edu.duke.cabig.c3pr.webservice.integration.StudyImportExportWebServiceTest.java

private void doStudyExportCheck()
        throws DOMException, SOAPException, IOException, SAXException, ParserConfigurationException {
    String xmlFile = "StudyIdentifier";

    Dispatch<SOAPMessage> dispatch = getDispatch();
    SOAPMessage reqMsg = prepareExportRequestEnvelope(xmlFile);
    SOAPMessage respMsg = dispatch.invoke(reqMsg);

    SOAPPart part = respMsg.getSOAPPart();
    SOAPEnvelope env = part.getEnvelope();
    SOAPBody body = env.getBody();
    NodeList nodes = body.getElementsByTagNameNS(SERVICE_NS, "ExportStudyResponse");
    assertEquals(1, nodes.getLength());/*  ww w  .  j a  v a2  s . c  om*/
    Element responseEl = (Element) nodes.item(0);
    assertEquals(1, responseEl.getChildNodes().getLength());

    Element exportedStudy = (Element) responseEl.getChildNodes().item(0);
    // this study element must match the one used to create the study in the first place
    Element originalStudy = (Element) getSOAPBodyFromXML("Study");
    assertTrue(XMLUtils.isDeepEqual(exportedStudy, originalStudy));

}

From source file:com.mirth.connect.connectors.ws.WebServiceMessageDispatcher.java

private void processMessage(MessageObject mo) throws Exception {
    /*/*  w ww  .  j a  va 2 s  .c  om*/
     * Initialize the dispatch object if it hasn't been initialized yet, or
     * create a new one if the connector properties have changed due to
     * variables.
     */
    createDispatch(mo);

    SOAPBinding soapBinding = (SOAPBinding) dispatch.getBinding();

    if (connector.isDispatcherUseAuthentication()) {
        dispatch.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, currentUsername);
        dispatch.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, currentPassword);
        logger.debug("Using authentication: username=" + currentUsername + ", password length="
                + currentPassword.length());
    }

    // See: http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528
    String soapAction = replacer.replaceValues(connector.getDispatcherSoapAction(), mo);

    if (StringUtils.isNotEmpty(soapAction)) {
        dispatch.getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY, soapAction);
    }

    // build the message
    logger.debug("Creating SOAP envelope.");
    String content = replacer.replaceValues(connector.getDispatcherEnvelope(), mo);
    Source source = new StreamSource(new StringReader(content));
    SOAPMessage message = soapBinding.getMessageFactory().createMessage();
    message.getSOAPPart().setContent(source);

    if (connector.isDispatcherUseMtom()) {
        soapBinding.setMTOMEnabled(true);

        List<String> attachmentIds = connector.getDispatcherAttachmentNames();
        List<String> attachmentContents = connector.getDispatcherAttachmentContents();
        List<String> attachmentTypes = connector.getDispatcherAttachmentTypes();

        for (int i = 0; i < attachmentIds.size(); i++) {
            String attachmentContentId = replacer.replaceValues(attachmentIds.get(i), mo);
            String attachmentContentType = replacer.replaceValues(attachmentTypes.get(i), mo);
            String attachmentContent = replacer.replaceValues(attachmentContents.get(i), mo);

            AttachmentPart attachment = message.createAttachmentPart();
            attachment.setBase64Content(new ByteArrayInputStream(attachmentContent.getBytes("UTF-8")),
                    attachmentContentType);
            attachment.setContentId(attachmentContentId);
            message.addAttachmentPart(attachment);
        }
    }

    message.saveChanges();

    // make the call
    String response = null;
    if (connector.isDispatcherOneWay()) {
        logger.debug("Invoking one way service...");
        dispatch.invokeOneWay(message);
        response = "Invoked one way operation successfully.";
    } else {
        logger.debug("Invoking web service...");
        SOAPMessage result = dispatch.invoke(message);
        response = sourceToXmlString(result.getSOAPPart().getContent());
    }
    logger.debug("Finished invoking web service, got result.");

    // process the result
    messageObjectController.setSuccess(mo, response, null);

    // send to reply channel
    if (connector.getDispatcherReplyChannelId() != null
            && !connector.getDispatcherReplyChannelId().equals("sink")) {
        new VMRouter().routeMessageByChannelId(connector.getDispatcherReplyChannelId(), response, true);
    }
}

From source file:hornet.framework.webservice.SOAPLoggingHandler.java

/**
 * log le message SOAP/* ww w  . ja v a 2 s  .co m*/
 *
 * @param smc
 *            SOAPMessageContext
 */
private void logSOAP(final SOAPMessageContext smc) {

    final Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (outboundProperty.booleanValue()) {
        LOGGER.debug("\nMessage SOAP envoye:");
    } else {
        LOGGER.debug("\nMessage SOAP recu:");
    }
    final SOAPMessage message = smc.getMessage();
    try {
        // Create transformer
        final TransformerFactory tff = TransformerFactory.newInstance();
        final Transformer tranf = tff.newTransformer();

        // Get reply content
        final Source src = message.getSOAPPart().getContent();

        // Set output transformation
        final ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
        final StreamResult result = new StreamResult(streamOut);
        tranf.transform(src, result);

        LOGGER.debug(streamOut.toString(CharEncoding.UTF_8));
    } catch (final TransformerConfigurationException e) {
        LOGGER.error(ERROR_MSG, e);
    } catch (final SOAPException e) {
        LOGGER.error(ERROR_MSG, e);
    } catch (final TransformerException e) {
        LOGGER.error(ERROR_MSG, e);
    } catch (final UnsupportedEncodingException e) {
        LOGGER.error(ERROR_MSG, e);
    }

}

From source file:com.konakart.bl.modules.ordertotal.thomson.HeaderLoggingHandler.java

/**
 * Outputs the soap msg to the logger//from   w w w . ja  v  a 2s.  com
 * 
 * @param context
 */
public void logSoapMsg(SOAPMessageContext context) {
    if (!log.isDebugEnabled()) {
        return;
    }

    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    String msgType = null;
    if (outboundProperty.booleanValue()) {
        msgType = "Request:";
    } else {
        msgType = "Response:";
    }

    SOAPMessage message = context.getMessage();
    try {
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer tf = tff.newTransformer();

        // Set formatting

        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        Source sc = message.getSOAPPart().getContent();

        ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(streamOut);
        tf.transform(sc, result);

        if (log.isDebugEnabled()) {
            log.debug(msgType + "\n" + streamOut.toString()
                    + "\n------------------------------------------------------------------------");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}