Example usage for javax.xml.soap MessageFactory createMessage

List of usage examples for javax.xml.soap MessageFactory createMessage

Introduction

In this page you can find the example usage for javax.xml.soap MessageFactory createMessage.

Prototype

public abstract SOAPMessage createMessage() throws SOAPException;

Source Link

Document

Creates a new SOAPMessage object with the default SOAPPart , SOAPEnvelope , SOAPBody , and SOAPHeader objects.

Usage

From source file:io.hummer.util.ws.WebServiceClient.java

private SOAPMessage createSOAPMessage(Element request, List<Element> headers, String protocol)
        throws Exception {
    MessageFactory mf = MessageFactory.newInstance(protocol);
    SOAPMessage message = mf.createMessage();
    SOAPBody body = message.getSOAPBody();

    // check if we have a complete soap:Envelope as request..
    String ns = request.getNamespaceURI();
    if (request.getTagName().contains("Envelope")) {
        if (ns.equals("http://schemas.xmlsoap.org/soap/envelope/"))
            message = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createMessage(
                    new MimeHeaders(), new ByteArrayInputStream(xmlUtil.toString(request).getBytes()));
        if (ns.equals("http://www.w3.org/2003/05/soap-envelope"))
            message = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(
                    new MimeHeaders(), new ByteArrayInputStream(xmlUtil.toString(request).getBytes()));

    } else {//from  w ww .  ja  v  a  2 s  . c  o  m
        xmlUtil.appendChild(body, request);
    }
    for (Element h : headers) {
        xmlUtil.appendChild(message.getSOAPHeader(), h);
    }
    for (Element h : eprParamsAndProps) {
        xmlUtil.appendChild(message.getSOAPHeader(), h);
    }
    xmlUtil.appendChild(message.getSOAPHeader(), xmlUtil.toElement(
            "<wsa:To xmlns:wsa=\"" + EndpointReference.NS_WS_ADDRESSING + "\">" + endpointURL + "</wsa:To>"));
    message.saveChanges();
    return message;
}

From source file:net.sf.jasperreports.olap.xmla.JRXmlaQueryExecuter.java

protected SOAPMessage createQueryMessage() {
    String queryStr = getQueryString();

    if (log.isDebugEnabled()) {
        log.debug("MDX query: " + queryStr);
    }//from www . ja v a 2s  .c  o  m

    try {
        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage message = mf.createMessage();

        MimeHeaders mh = message.getMimeHeaders();
        mh.setHeader("SOAPAction", "\"urn:schemas-microsoft-com:xml-analysis:Execute\"");

        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody body = envelope.getBody();
        Name nEx = envelope.createName("Execute", "", XMLA_URI);

        SOAPElement eEx = body.addChildElement(nEx);

        // add the parameters

        // COMMAND parameter
        // <Command>
        // <Statement>queryStr</Statement>
        // </Command>
        Name nCom = envelope.createName("Command", "", XMLA_URI);
        SOAPElement eCommand = eEx.addChildElement(nCom);
        Name nSta = envelope.createName("Statement", "", XMLA_URI);
        SOAPElement eStatement = eCommand.addChildElement(nSta);
        eStatement.addTextNode(queryStr);

        // <Properties>
        // <PropertyList>
        // <DataSourceInfo>dataSource</DataSourceInfo>
        // <Catalog>catalog</Catalog>
        // <Format>Multidimensional</Format>
        // <AxisFormat>TupleFormat</AxisFormat>
        // </PropertyList>
        // </Properties>
        Map<String, String> paraList = new HashMap<String, String>();
        String datasource = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_DATASOURCE);
        paraList.put("DataSourceInfo", datasource);
        String catalog = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_CATALOG);
        paraList.put("Catalog", catalog);
        paraList.put("Format", "Multidimensional");
        paraList.put("AxisFormat", "TupleFormat");
        addParameterList(envelope, eEx, "Properties", "PropertyList", paraList);
        message.saveChanges();

        if (log.isDebugEnabled()) {
            log.debug("XML/A query message: \n" + prettyPrintSOAP(message.getSOAPPart().getEnvelope()));
        }

        return message;
    } catch (SOAPException e) {
        throw new JRRuntimeException(e);
    }
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

private Document createSOAPFaultDocument(String faultString) throws SOAPException {
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart sp = message.getSOAPPart();
    SOAPEnvelope se = sp.getEnvelope();
    se.setPrefix(SOAP_PREFIX);/*from w w w . j  ava 2  s . c  om*/
    se.getHeader().detachNode();
    se.addHeader();
    se.getBody().detachNode();
    SOAPBody body = se.addBody();
    SOAPFault fault = body.addFault();
    Name faultCode = se.createName("Client", null, SOAPConstants.URI_NS_SOAP_ENVELOPE);
    fault.setFaultCode(faultCode);
    fault.setFaultString(faultString);
    return se.getOwnerDocument();
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

public Object buildOutputData(Context context, Object convertigoResponse) throws Exception {
    Engine.logBeans.debug("[WebServiceTranslator] Encoding the SOAP response...");

    SOAPMessage responseMessage = null;
    String sResponseMessage = "";
    String encodingCharSet = "UTF-8";
    if (context.requestedObject != null)
        encodingCharSet = context.requestedObject.getEncodingCharSet();

    if (convertigoResponse instanceof Document) {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is a XML document.");
        Document document = Engine.theApp.schemaManager.makeResponse((Document) convertigoResponse);

        //MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
        MessageFactory messageFactory = MessageFactory.newInstance();
        responseMessage = messageFactory.createMessage();

        responseMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, encodingCharSet);

        SOAPPart sp = responseMessage.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        SOAPBody sb = se.getBody();

        sb.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");

        //se.addNamespaceDeclaration(prefix, targetNameSpace);
        se.addNamespaceDeclaration("soapenc", "http://schemas.xmlsoap.org/soap/encoding/");
        se.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        se.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");

        // Remove header as it not used. Seems that empty headers causes the WS client of Flex 4 to fail 
        se.getHeader().detachNode();/* w  ww  . j a va 2 s . c  o m*/

        addSoapElement(context, se, sb, document.getDocumentElement());

        sResponseMessage = SOAPUtils.toString(responseMessage, encodingCharSet);

        // Correct missing "xmlns" (Bug AXA POC client .NET)
        //sResponseMessage = sResponseMessage.replaceAll("<soapenv:Envelope", "<soapenv:Envelope xmlns=\""+targetNameSpace+"\"");
    } else {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is not a XML document.");
        sResponseMessage = convertigoResponse.toString();
    }

    if (Engine.logBeans.isDebugEnabled()) {
        Engine.logBeans.debug("[WebServiceTranslator] SOAP response:\n" + sResponseMessage);
    }

    return responseMessage == null ? sResponseMessage.getBytes(encodingCharSet) : responseMessage;
}

From source file:com.jaspersoft.ireport.designer.data.fieldsproviders.olap.OLAPQueryExecuter.java

protected SOAPMessage createQueryMessage(JRXMLADataSourceConnection xmlaConnection) {
    String queryStr = getQueryString();

    if (log.isDebugEnabled()) {
        log.debug("MDX query: " + queryStr);
    }/*www .  j  av  a 2  s.  co  m*/

    try {
        // Force the use of Axis as message factory...

        MessageFactory mf = MessageFactory.newInstance();

        SOAPMessage message = mf.createMessage();

        MimeHeaders mh = message.getMimeHeaders();
        mh.setHeader("SOAPAction", "\"urn:schemas-microsoft-com:xml-analysis:Execute\"");
        //mh.setHeader("Content-Type", "text/xml; charset=utf-8");

        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody body = envelope.getBody();
        Name nEx = envelope.createName("Execute", "", XMLA_URI);

        SOAPElement eEx = body.addChildElement(nEx);

        // add the parameters

        // COMMAND parameter
        // <Command>
        // <Statement>queryStr</Statement>
        // </Command>
        Name nCom = envelope.createName("Command", "", XMLA_URI);
        SOAPElement eCommand = eEx.addChildElement(nCom);
        Name nSta = envelope.createName("Statement", "", XMLA_URI);
        SOAPElement eStatement = eCommand.addChildElement(nSta);
        eStatement.addTextNode(queryStr);

        // <Properties>
        // <PropertyList>
        // <DataSourceInfo>dataSource</DataSourceInfo>
        // <Catalog>catalog</Catalog>
        // <Format>Multidimensional</Format>
        // <AxisFormat>TupleFormat</AxisFormat>
        // </PropertyList>
        // </Properties>
        Map paraList = new HashMap();
        String datasource = xmlaConnection.getDatasource();
        paraList.put("DataSourceInfo", datasource);
        String catalog = xmlaConnection.getCatalog();
        paraList.put("Catalog", catalog);
        paraList.put("Format", "Multidimensional");
        paraList.put("AxisFormat", "TupleFormat");
        addParameterList(envelope, eEx, "Properties", "PropertyList", paraList);
        message.saveChanges();

        if (log.isDebugEnabled()) {
            log.debug("XML/A query message: " + message.toString());
        }

        return message;
    } catch (SOAPException e) {
        log.error(e);
        throw new JRRuntimeException(e);
    }
}

From source file:org.springframework.ws.transport.http.HttpComponentsMessageSenderIntegrationTest.java

@Test
public void testContextClose() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    int port = FreePortScanner.getFreePort();
    Server jettyServer = new Server(port);
    Context jettyContext = new Context(jettyServer, "/");
    jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/");
    jettyServer.start();/* w  w  w .  ja  va  2 s. c  o  m*/
    WebServiceConnection connection = null;
    try {

        StaticApplicationContext appContext = new StaticApplicationContext();
        appContext.registerSingleton("messageSender", HttpComponentsMessageSender.class);
        appContext.refresh();

        HttpComponentsMessageSender messageSender = appContext.getBean("messageSender",
                HttpComponentsMessageSender.class);
        connection = messageSender.createConnection(new URI("http://localhost:" + port));

        connection.send(new SaajSoapMessage(messageFactory.createMessage()));
        connection.receive(new SaajSoapMessageFactory(messageFactory));

        appContext.close();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ex) {
                // ignore
            }
        }
        if (jettyServer.isRunning()) {
            jettyServer.stop();
        }
    }

}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

public Object __buildOutputData(Context context, Object convertigoResponse) throws Exception {
    Engine.logBeans.debug("[WebServiceTranslator] Encoding the SOAP response...");

    SOAPMessage responseMessage = null;
    String sResponseMessage = "";
    String encodingCharSet = "UTF-8";
    if (context.requestedObject != null)
        encodingCharSet = context.requestedObject.getEncodingCharSet();

    if (convertigoResponse instanceof Document) {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is a XML document.");
        Document document = (Document) convertigoResponse;

        //MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
        MessageFactory messageFactory = MessageFactory.newInstance();
        responseMessage = messageFactory.createMessage();

        responseMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, encodingCharSet);

        SOAPPart sp = responseMessage.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        SOAPBody sb = se.getBody();

        sb.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");

        String targetNamespace = context.project.getTargetNamespace();
        String prefix = getPrefix(context.projectName, targetNamespace);

        //se.addNamespaceDeclaration(prefix, targetNameSpace);
        se.addNamespaceDeclaration("soapenc", "http://schemas.xmlsoap.org/soap/encoding/");
        se.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        se.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");

        // Remove header as it not used. Seems that empty headers causes the WS client of Flex 4 to fail 
        se.getHeader().detachNode();/*from  ww  w .  j a  va2  s  . com*/

        // Add the method response element
        SOAPElement soapMethodResponseElement = null;
        String soapElementName = context.sequenceName != null ? context.sequenceName
                : context.connectorName + "__" + context.transactionName;
        soapElementName += "Response";

        soapMethodResponseElement = sb.addChildElement(se.createName(soapElementName, prefix, targetNamespace));

        if (XsdForm.qualified == context.project.getSchemaElementForm()) {
            soapMethodResponseElement.addAttribute(se.createName("xmlns"), targetNamespace);
        }

        // Add a 'response' root child element or not
        SOAPElement soapResponseElement;
        if (context.sequenceName != null) {
            Sequence sequence = (Sequence) context.requestedObject;
            if (sequence.isIncludeResponseElement()) {
                soapResponseElement = soapMethodResponseElement.addChildElement("response");
            } else {
                soapResponseElement = soapMethodResponseElement;
            }
        } else {
            soapResponseElement = soapMethodResponseElement.addChildElement("response");
        }

        if (soapResponseElement.getLocalName().equals("response")) {
            if (document.getDocumentElement().hasAttributes()) {
                addAttributes(responseMessage, se, context, document.getDocumentElement().getAttributes(),
                        soapResponseElement);
            }
        }

        NodeList childNodes = document.getDocumentElement().getChildNodes();
        int len = childNodes.getLength();
        org.w3c.dom.Node node;
        for (int i = 0; i < len; i++) {
            node = childNodes.item(i);
            if (node instanceof Element) {
                addElement(responseMessage, se, context, (Element) node, soapResponseElement);
            }
        }

        sResponseMessage = SOAPUtils.toString(responseMessage, encodingCharSet);

        // Correct missing "xmlns" (Bug AXA POC client .NET)
        //sResponseMessage = sResponseMessage.replaceAll("<soapenv:Envelope", "<soapenv:Envelope xmlns=\""+targetNameSpace+"\"");
    } else {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is not a XML document.");
        sResponseMessage = convertigoResponse.toString();
    }

    if (Engine.logBeans.isDebugEnabled()) {
        Engine.logBeans.debug("[WebServiceTranslator] SOAP response:\n" + sResponseMessage);
    }

    return responseMessage == null ? sResponseMessage.getBytes(encodingCharSet) : responseMessage;
}

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//www.  j  av 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:com.streamreduce.util.JiraClient.java

public SOAPMessage invokeSoap(JiraStudioApp app, String soapBody) throws SOAPException {
    String cacheKey = (app + "-SOAP-" + soapBody.hashCode());
    Object objectFromCache = requestCache.getIfPresent(cacheKey);

    if (objectFromCache != null) {
        debugLog(LOGGER, "  (From cache)");
        return (SOAPMessage) objectFromCache;
    }//from  ww w. j ava  2s  .c om

    // Wrap the SOAP body content in an envelope/body container
    StringBuilder sb = new StringBuilder();
    String soapBaseURL = getBaseUrl();
    String soapNamespaceURL;

    sb.append("<soapenv:Envelope ").append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ")
            .append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ")
            .append("xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" ");

    switch (app) {
    case CONFLUENCE:
        soapNamespaceURL = "http://soap.rpc.confluence.atlassian.com";
        soapBaseURL += "/wiki/rpc/soap-axis/confluenceservice-v1";
        break;
    case JIRA:
        soapNamespaceURL = "http://soap.rpc.jira.atlassian.com";
        soapBaseURL += "/rpc/soap/jirasoapservice-v2";
        break;
    default:
        throw new SOAPException("Unknown Jira Studio application: " + app);
    }

    sb.append("xmlns:soap=\"" + soapNamespaceURL + "\">\n");
    sb.append("<soapenv:Body>\n");
    sb.append(soapBody);
    sb.append("</soapenv:Body></soapenv:Envelope>");

    String rawResponse;
    List<Header> requestHeaders = new ArrayList<>();

    requestHeaders.add(new BasicHeader("SOAPAction", ""));

    try {
        rawResponse = HTTPUtils.openUrl(soapBaseURL, "POST", sb.toString(), MediaType.TEXT_XML, null, null,
                requestHeaders, null);
    } catch (Exception e) {
        LOGGER.error(String.format("Unable to make SOAP call to %s: %s", soapBaseURL, e.getMessage()), e);
        throw new SOAPException(e);
    }

    Source response = new StreamSource(new StringReader(rawResponse));
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPMessage message = msgFactory.createMessage();
    SOAPPart env = message.getSOAPPart();
    env.setContent(response);

    if (message.getSOAPBody().hasFault()) {
        SOAPFault fault = message.getSOAPBody().getFault();
        LOGGER.error("soap fault in jira soap response: " + fault.getFaultString());
    }

    requestCache.put(cacheKey, message);

    return message;
}

From source file:edu.unc.lib.dl.util.TripleStoreQueryServiceMulgaraImpl.java

private String sendTQL(String query) {
    log.debug(query);/* w w w .  j a v  a 2  s  . c om*/
    String result = null;
    SOAPMessage reply = null;
    SOAPConnection connection = null;
    try {
        // Next, create the actual message
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage message = messageFactory.createMessage();
        message.getMimeHeaders().setHeader("SOAPAction", "itqlbean:executeQueryToString");
        SOAPBody soapBody = message.getSOAPPart().getEnvelope().getBody();
        soapBody.addNamespaceDeclaration("xsd", JDOMNamespaceUtil.XSD_NS.getURI());
        soapBody.addNamespaceDeclaration("xsi", JDOMNamespaceUtil.XSI_NS.getURI());
        soapBody.addNamespaceDeclaration("itqlbean", this.getItqlEndpointURL());
        SOAPElement eqts = soapBody.addChildElement("executeQueryToString", "itqlbean");
        SOAPElement queryStr = eqts.addChildElement("queryString", "itqlbean");
        queryStr.setAttributeNS(JDOMNamespaceUtil.XSI_NS.getURI(), "xsi:type", "xsd:string");
        CDATASection queryCDATA = message.getSOAPPart().createCDATASection(query);
        queryStr.appendChild(queryCDATA);
        message.saveChanges();

        // First create the connection
        SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
        connection = soapConnFactory.createConnection();
        reply = connection.call(message, this.getItqlEndpointURL());

        if (reply.getSOAPBody().hasFault()) {
            reportSOAPFault(reply);
            if (log.isDebugEnabled()) {
                // log the full soap body response
                DOMBuilder builder = new DOMBuilder();
                org.jdom2.Document jdomDoc = builder.build(reply.getSOAPBody().getOwnerDocument());
                log.debug(new XMLOutputter().outputString(jdomDoc));
            }
        } else {
            NodeList nl = reply.getSOAPPart().getEnvelope().getBody().getElementsByTagNameNS("*",
                    "executeQueryToStringReturn");
            if (nl.getLength() > 0) {
                result = nl.item(0).getFirstChild().getNodeValue();
            }
            log.debug(result);
        }
    } catch (SOAPException e) {
        log.error("Failed to prepare or send iTQL via SOAP", e);
        throw new RuntimeException("Cannot query triple store at " + this.getItqlEndpointURL(), e);
    } finally {
        try {
            connection.close();
        } catch (SOAPException e) {
            log.error("Failed to close SOAP connection", e);
            throw new RuntimeException(
                    "Failed to close SOAP connection for triple store at " + this.getItqlEndpointURL(), e);
        }
    }
    return result;
}