Example usage for javax.xml.soap SOAPPart getEnvelope

List of usage examples for javax.xml.soap SOAPPart getEnvelope

Introduction

In this page you can find the example usage for javax.xml.soap SOAPPart getEnvelope.

Prototype

public abstract SOAPEnvelope getEnvelope() throws SOAPException;

Source Link

Document

Gets the SOAPEnvelope object associated with this SOAPPart object.

Usage

From source file:backend.Weather.java

private SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    String serverURI = "http://ws.cdyne.com/";
    SOAPEnvelope envelope = soapPart.getEnvelope();

    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("GetCityWeatherByZIP");
    QName attributeName = new QName("xmlns");
    soapBodyElem.addAttribute(attributeName, "http://ws.cdyne.com/WeatherWS/");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("ZIP");
    soapBodyElem1.addTextNode("02215");
    soapMessage.saveChanges();//w  ww.j  a v a 2  s.com
    return soapMessage;

}

From source file:com.cisco.dvbu.ps.common.adapters.connect.SoapHttpConnector.java

private Document send(SoapHttpConnectorCallback cb, String requestXml) throws AdapterException {
    log.debug("Entered send: " + cb.getName());

    // set up the factories and create a SOAP factory
    SOAPConnection soapConnection;
    Document doc = null;//from  w  w w  . jav  a  2s  .c  om
    URL endpoint = null;
    try {
        soapConnection = SOAPConnectionFactory.newInstance().createConnection();
        MessageFactory messageFactory = MessageFactory.newInstance();

        // Create a message from the message factory.
        SOAPMessage soapMessage = messageFactory.createMessage();

        // Set the SOAP Action here
        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", cb.getAction());

        // set credentials
        //         String authorization = new sun.misc.BASE64Encoder().encode((shConfig.getUser() + "@" + shConfig.getDomain() + ":" + shConfig.getPassword()).getBytes());
        String authorization = new String(org.apache.commons.codec.binary.Base64.encodeBase64(
                (shConfig.getUser() + "@" + shConfig.getDomain() + ":" + shConfig.getPassword()).getBytes()));
        headers.addHeader("Authorization", "Basic " + authorization);
        log.debug("Authentication: " + authorization);

        // create a SOAP part have populate the envelope
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.setEncodingStyle(SOAPConstants.URI_NS_SOAP_ENCODING);

        SOAPHeader head = envelope.getHeader();
        if (head == null)
            head = envelope.addHeader();

        // create a SOAP body
        SOAPBody body = envelope.getBody();

        log.debug("Request XSL Style Sheet:\n"
                + XMLUtils.getPrettyXml(XMLUtils.getDocumentFromString(cb.getRequestBodyXsl())));

        // convert request string to document and then transform
        body.addDocument(XmlUtils.xslTransform(XmlUtils.stringToDocument(requestXml), cb.getRequestBodyXsl()));

        // build the request structure
        soapMessage.saveChanges();
        log.debug("Soap request successfully built: ");
        log.debug("  Body:\n"
                + XMLUtils.getPrettyXml(XMLUtils.getDocumentFromString(XmlUtils.nodeToString(body))));

        if (shConfig.useProxy()) {
            System.setProperty("http.proxySet", "true");
            System.setProperty("http.proxyHost", shConfig.getProxyHost());
            System.setProperty("http.proxyPort", "" + shConfig.getProxyPort());
            if (shConfig.useProxyCredentials()) {
                System.setProperty("http.proxyUser", shConfig.getProxyUser());
                System.setProperty("http.proxyPassword", shConfig.getProxyPassword());
            }
        }

        endpoint = new URL(shConfig.getEndpoint(cb.getEndpoint()));

        // now make that call over the SOAP connection
        SOAPMessage reply = null;
        AdapterException ae = null;

        for (int i = 1; (i <= shConfig.getRetryAttempts() && reply == null); i++) {
            log.debug("Attempt " + i + ": sending request to endpoint: " + endpoint);
            try {
                reply = soapConnection.call(soapMessage, endpoint);
                log.debug("Attempt " + i + ": received response: " + reply);
            } catch (Exception e) {
                ae = new AdapterException(502, String.format(AdapterConstants.ADAPTER_EM_CONNECTION, endpoint),
                        e);
                Thread.sleep(100);
            }
        }

        // close down the connection
        soapConnection.close();

        if (reply == null)
            throw ae;

        SOAPFault fault = reply.getSOAPBody().getFault();
        if (fault == null) {
            doc = reply.getSOAPBody().extractContentAsDocument();
        } else {
            // Extracts the entire Soap Fault message coming back from CIS
            String faultString = XmlUtils.nodeToString(fault);
            throw new AdapterException(503, faultString, null);
        }
    } catch (AdapterException e) {
        throw e;
    } catch (Exception e) {
        throw new AdapterException(504,
                String.format(AdapterConstants.ADAPTER_EM_CONNECTION, shConfig.getEndpoint(cb.getEndpoint())),
                e);
    } finally {
        if (shConfig.useProxy()) {
            System.setProperty("http.proxySet", "false");
        }
    }
    log.debug("Exiting send: " + cb.getName());

    return doc;
}

From source file:com.inbravo.scribe.rest.service.crm.ms.auth.SOAPExecutor.java

/**
 * Constructs XPath query over the SOAP message
 * /*from   w w  w .j a  v a 2 s .  c  o m*/
 * @param query XPath query
 * @param response SOAP message
 * @return XPath query
 * @throws SOAPException in case of SOAP issue
 * @throws JaxenException XPath problem
 */
public final XPath createXPath(final String query, final SOAPMessage response)
        throws SOAPException, JaxenException {

    /* Uses DOM to XPath mapping */
    final XPath xpath = new DOMXPath(query);

    /* Define a namespaces used in response */
    final SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
    final SOAPPart sp = response.getSOAPPart();
    final SOAPEnvelope env = sp.getEnvelope();
    final SOAPBody bdy = env.getBody();

    /* Add namespaces from SOAP envelope */
    addNamespaces(nsContext, env);

    /* Add namespaces of top body element */
    final Iterator<?> bodyElements = bdy.getChildElements();
    while (bodyElements.hasNext()) {
        SOAPElement element = (SOAPElement) bodyElements.next();
        addNamespaces(nsContext, element);
    }
    xpath.setNamespaceContext(nsContext);
    return xpath;
}

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  w w w. ja v  a 2 s .co  m*/
    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:com.googlecode.ddom.saaj.SOAPPartTest.java

@Validated
@Test//from w w w .j a v a 2  s .  co  m
public void testCreateEnvelopeWithCreateElementNS() throws Exception {
    SOAPPart soapPart = factory.createMessage().getSOAPPart();
    Element element = soapPart.createElementNS(SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE, "SOAP-ENV:Envelope");
    assertTrue(element instanceof SOAPEnvelope);
    soapPart.appendChild(element);
    SOAPEnvelope envelope = soapPart.getEnvelope();
    assertNotNull(envelope);
}

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 www  .  ja v a 2s  . c  o  m*/
    // 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 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();//from w w  w . j a  v a  2  s.  c o  m
    return reqMsg;
}

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());/*from www.j  a v a 2  s.  c  o  m*/
    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:ee.sk.hwcrypto.demo.controller.SigningController.java

private SOAPMessage SOAPQuery(String req) {
    try {/*from www .  j ava 2  s.c  o  m*/
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        String url = "http://www.sk.ee/DigiDocService/DigiDocService_2_3.wsdl";

        MessageFactory messageFactory = MessageFactory.newInstance();
        InputStream is = new ByteArrayInputStream(req.getBytes());
        SOAPMessage soapMessage = messageFactory.createMessage(null, is);
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI = "https://www.openxades.org:8443/DigiDocService/";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("", url);
        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", "");
        soapMessage.saveChanges();

        SOAPMessage soapResponse = soapConnection.call(soapMessage, serverURI);

        return soapResponse;
    } catch (Exception e) {
        log.error("SOAP Exception " + e);
    }
    return null;
}

From source file:org.cleverbus.core.reqres.RequestResponseTest.java

/**
 * Test saving synchronous request/response where response is failed SOAP fault exception.
 *///  ww  w .  jav  a2  s .  c om
@Test
public void testSavingRequestWithSOAPFaultResponse() throws Exception {

    final String soapFault = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<SOAP-ENV:Fault xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            + "     <faultcode>SOAP-ENV:Server</faultcode>"
            + "     <faultstring>There is one error</faultstring>" + "</SOAP-ENV:Fault>";

    // prepare target route
    prepareTargetRoute(TARGET_URI, new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getOut().setBody(soapFault);

            // create SOAP Fault message
            SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
            SOAPPart soapPart = soapMessage.getSOAPPart();
            SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
            SOAPBody soapBody = soapEnvelope.getBody();

            // Set fault code and fault string
            SOAPFault fault = soapBody.addFault();
            fault.setFaultCode(new QName("http://schemas.xmlsoap.org/soap/envelope/", "Server"));
            fault.setFaultString("There is one error");
            SoapMessage message = new SaajSoapMessage(soapMessage);
            throw new SoapFaultClientException(message);
        }
    });

    // action
    mock.expectedMessageCount(0);

    try {
        producer.sendBody(REQUEST);
        fail("Target route was thrown exception.");
    } catch (CamelExecutionException ex) {
        assertRequestResponse(REQUEST, null,
                "org.springframework.ws.soap.client.SoapFaultClientException: There is one error", soapFault);
    }
}