Example usage for javax.xml.soap SOAPMessage getMimeHeaders

List of usage examples for javax.xml.soap SOAPMessage getMimeHeaders

Introduction

In this page you can find the example usage for javax.xml.soap SOAPMessage getMimeHeaders.

Prototype

public abstract MimeHeaders getMimeHeaders();

Source Link

Document

Returns all the transport-specific MIME headers for this SOAPMessage object in a transport-independent fashion.

Usage

From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java

/**
 * Invokes an operation using SAAJ//from www .  j  ava2 s  .c o m
 *
 * @param operation The operation to invoke
 */
public static void main(String[] args) {
    try {
        /*OperationInfo operation = new OperationInfo();
        operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
        operation.setInputMessageName("HelloWorld_sayHello");
        operation.setInputMessageText("<urn:sayHello xmlns:urn='urn:jbosstest'><arg0>Markus</arg0></urn:sayHello>");
        operation.setNamespaceURI("urn:jbosstest");
        operation.setOutputMessageName("HelloWorld_sayHelloResponse");
        operation.setOutputMessageText("<sayHello><return>0</return></sayHello>");
        operation.setSoapActionURI("");
        operation.setStyle("document");
        operation.setTargetMethodName("sayHello");
        operation.setTargetObjectURI(null);
        operation.setTargetURL("http://localhost:8080/HelloWorld/HelloWorld");*/

        OperationInfo operation = new OperationInfo();
        operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
        operation.setInputMessageName("ConversionRateSoapIn");
        operation.setInputMessageText(
                "<ns5:ConversionRate xmlns:ns5='http://www.webserviceX.NET/'><ns5:FromCurrency>EUR</ns5:FromCurrency><ns5:ToCurrency>SKK</ns5:ToCurrency></ns5:ConversionRate>");
        operation.setNamespaceURI("http://www.webserviceX.NET/");
        operation.setOutputMessageName("ConversionRateSoapOut");
        operation.setOutputMessageText(
                "<ConversionRate><ConversionRateResult>0</ConversionRateResult></ConversionRate>");
        operation.setSoapActionURI("http://www.webserviceX.NET/ConversionRate");
        operation.setStyle("document");
        operation.setTargetMethodName("ConversionRate");
        operation.setTargetObjectURI(null);
        operation.setTargetURL("http://www.webservicex.net/CurrencyConvertor.asmx");

        // Determine if the operation style is RPC
        boolean isRPC = operation.getStyle().equalsIgnoreCase("rpc");

        // All connections are created by using a connection factory
        SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance();

        // Now we can create a SOAPConnection object using the connection factory
        SOAPConnection connection = conFactory.createConnection();

        // All SOAP messages are created by using a message factory
        MessageFactory msgFactory = MessageFactory.newInstance();

        // Now we can create the SOAP message object
        SOAPMessage msg = msgFactory.createMessage();

        // Get the SOAP part from the SOAP message object
        SOAPPart soapPart = msg.getSOAPPart();

        // The SOAP part object will automatically contain the SOAP envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        //envelope.addNamespaceDeclaration("", operation.getNamespaceURI());

        if (isRPC) {
            // Add namespace declarations to the envelope, usually only required for RPC/encoded
            envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI);
            envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI);
        }

        // Get the SOAP header from the envelope
        SOAPHeader header = envelope.getHeader();

        // The client does not yet support SOAP headers
        header.detachNode();

        // Get the SOAP body from the envelope and populate it
        SOAPBody body = envelope.getBody();

        // Create the default namespace for the SOAP body
        //body.addNamespaceDeclaration("", operation.getNamespaceURI());

        // Add the service information
        String targetObjectURI = operation.getTargetObjectURI();

        if (targetObjectURI == null) {
            // The target object URI should not be null
            targetObjectURI = "";
        }

        // Add the service information
        //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI);
        Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns2", operation.getNamespaceURI());
        SOAPElement svcElem = body.addChildElement(svcInfo);

        if (isRPC) {
            // Set the encoding style of the service element
            svcElem.setEncodingStyle(operation.getEncodingStyle());
        }

        // Add the message contents to the SOAP body
        Document doc = XMLSupport.readXML(operation.getInputMessageText());

        if (doc.hasRootElement()) {
            // Begin building content
            buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC);
        }

        //svcElem.addTextNode(operation.getInputMessageText());
        //svcElem.

        // Check for a SOAPAction
        String soapActionURI = operation.getSoapActionURI();

        if (soapActionURI != null && soapActionURI.length() > 0) {
            // Add the SOAPAction value as a MIME header
            MimeHeaders mimeHeaders = msg.getMimeHeaders();
            mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\"");
        }

        // Save changes to the message we just populated
        msg.saveChanges();

        // Get ready for the invocation
        URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL());

        // Show the URL endpoint message in the log
        ByteArrayOutputStream msgStream = new ByteArrayOutputStream();
        msg.writeTo(msgStream);

        log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL());
        log.debug("SOAP Request: " + msgStream.toString());

        // Make the call
        SOAPMessage response = connection.call(msg, endpoint);

        // Close the connection, we are done with it
        connection.close();

        // Get the content of the SOAP response
        Source responseContent = response.getSOAPPart().getContent();

        // Convert the SOAP response into a JDOM
        TransformerFactory tFact = TransformerFactory.newInstance();
        Transformer transformer = tFact.newTransformer();

        JDOMResult jdomResult = new JDOMResult();
        transformer.transform(responseContent, jdomResult);

        // Get the document created by the transform operation
        Document responseDoc = jdomResult.getDocument();

        // Send the response to the Log
        String strResponse = XMLSupport.outputString(responseDoc);
        log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse);

        // Set the response as the output message
        operation.setOutputMessageText(strResponse);

        // Return the response generated
        //return strResponse;
    }

    catch (Throwable ex) {
        log.error("Error invoking operation:");
        log.error(ex.getMessage());
    }

    //return "";
}

From source file:com.nortal.jroad.util.SOAPUtil.java

/**
 * Adds a custom MIME header to a {@link SOAPMessage}.
 *
 * @param message The {@link SOAPMessage} to add the header to.
 * @param name The name of the header./*w ww . j a va 2  s .co m*/
 * @param value The value (content) of the header.
 */
public static void addMimeHeader(SOAPMessage message, String name, String value) {
    message.getMimeHeaders().setHeader(name, value);
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.WsStream.java

/**
 * Performs JAX-WS service call using SOAP API.
 *
 * @param url/*from w  w  w.j  a v  a2 s .c o  m*/
 *            JAX-WS service URL
 * @param soapRequestData
 *            JAX-WS service request data: headers and body XML string
 * @return service response string
 * @throws Exception
 *             if exception occurs while performing JAX-WS service call
 */
protected static String callWebService(String url, String soapRequestData) throws Exception {
    if (StringUtils.isEmpty(url)) {
        LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME,
                "WsStream.cant.execute.request"), url);
        return null;
    }

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "WsStream.invoking.request"),
            url, soapRequestData);

    Map<String, String> headers = new HashMap<>();
    // separate SOAP message header values from request body XML
    BufferedReader br = new BufferedReader(new StringReader(soapRequestData));
    StringBuilder sb = new StringBuilder();
    try {
        String line;
        while ((line = br.readLine()) != null) {
            if (line.trim().startsWith("<")) { // NON-NLS
                sb.append(line).append(Utils.NEW_LINE);
            } else {
                int bi = line.indexOf(':'); // NON-NLS
                if (bi >= 0) {
                    String hKey = line.substring(0, bi).trim();
                    String hValue = line.substring(bi + 1).trim();
                    headers.put(hKey, hValue);
                } else {
                    sb.append(line).append(Utils.NEW_LINE);
                }
            }
        }
    } finally {
        Utils.close(br);
    }

    soapRequestData = sb.toString();

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "WsStream.invoking.request"),
            url, soapRequestData);

    // Create Request body XML document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(soapRequestData)));

    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Create SOAP message and set request XML as body
    SOAPMessage soapRequest = MessageFactory.newInstance().createMessage();

    // SOAPPart part = soapRequest.getSOAPPart();
    // SOAPEnvelope envelope = part.getEnvelope();
    // envelope.addNamespaceDeclaration();

    if (!headers.isEmpty()) {
        MimeHeaders mimeHeaders = soapRequest.getMimeHeaders();

        for (Map.Entry<String, String> e : headers.entrySet()) {
            mimeHeaders.addHeader(e.getKey(), e.getValue());
        }
    }

    SOAPBody body = soapRequest.getSOAPBody();
    body.addDocument(doc);
    soapRequest.saveChanges();

    // Send SOAP Message to SOAP Server
    SOAPMessage soapResponse = soapConnection.call(soapRequest, url);

    ByteArrayOutputStream soapResponseBaos = new ByteArrayOutputStream();
    soapResponse.writeTo(soapResponseBaos);
    String soapResponseXml = soapResponseBaos.toString();

    return soapResponseXml;
}

From source file:org.soapfromhttp.service.CallSOAP.java

/**
 * Contruction dynamique de la requte SOAP
 *
 * @param pBody/*from  ww  w.ja va 2 s  .c  o m*/
 * @param method
 * @return SOAPMessage
 * @throws SOAPException
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private SOAPMessage createSOAPRequest(final String pBody, final String method)
        throws SOAPException, IOException, SAXException, ParserConfigurationException {

    // Prcise la version du protocole SOAP  utiliser (ncessaire pour les appels de WS Externe)
    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);

    SOAPMessage soapMessage = messageFactory.createMessage();

    MimeHeaders headers = soapMessage.getMimeHeaders();

    // Prcise la mthode du WSDL  interroger
    headers.addHeader("SOAPAction", method);
    // Encodage UTF-8
    headers.addHeader("Content-Type", "text/xml;charset=UTF-8");

    final SOAPBody soapBody = soapMessage.getSOAPBody();

    // convert String into InputStream - traitement des caracres escaps > < ... (contraintes de l'affichage IHM)
    //InputStream is = new ByteArrayInputStream(HtmlUtils.htmlUnescape(pBody).getBytes());
    InputStream is = new ByteArrayInputStream(pBody.getBytes());
    DocumentBuilder builder = null;

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

    // Important  laisser sinon KO
    builderFactory.setNamespaceAware(true);
    try {
        builder = builderFactory.newDocumentBuilder();

        Document document = builder.parse(is);

        soapBody.addDocument(document);
    } catch (ParserConfigurationException e) {
        MyLogger.log(CallSOAP.class.getName(), Level.ERROR, e.toString());
    } finally {
        is.close();
        if (builder != null) {
            builder.reset();
        }
    }
    soapMessage.saveChanges();

    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.  j a  v  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:edu.unc.lib.dl.services.TripleStoreManagerMulgaraImpl.java

private String sendTQL(String query) {
    log.info(query);//from   w  ww . j a  va 2  s .co  m
    String result = null;
    try {
        // First create the connection
        SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnFactory.createConnection();

        // 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();
        SOAPMessage 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.jdom.Document jdomDoc = builder.build(reply.getSOAPBody().getOwnerDocument());
                log.info(new XMLOutputter().outputString(jdomDoc));
            }
        } else {
            NodeList nl = reply.getSOAPPart().getEnvelope().getBody().getElementsByTagNameNS("*",
                    "executeQueryToStringReturn");
            if (nl.getLength() > 0) {
                result = nl.item(0).getTextContent();
            }
            log.debug(result);
        }
    } catch (SOAPException e) {
        throw new Error("Cannot query triple store at " + this.getItqlEndpointURL(), e);
    }
    return result;
}

From source file:com.wandrell.example.swss.test.util.test.integration.endpoint.AbstractITEndpoint.java

/**
 * Calls the web service being tested and returns the response.
 *
 * @param request/* ww w .j  a va2s.c  o  m*/
 *            request to the web service
 * @return the web service response
 * @throws SOAPException
 *             never, this is a required declaration
 */
protected final SOAPMessage callWebService(final SOAPMessage request) throws SOAPException {
    final SOAPConnectionFactory soapConnectionFactory; // Connection factory
    final MimeHeaders headers; // Message headers

    soapConnectionFactory = SOAPConnectionFactory.newInstance();

    // Sets the SOAP action
    headers = request.getMimeHeaders();
    headers.addHeader("SOAPAction", soapAction);
    request.saveChanges();

    return soapConnectionFactory.createConnection().call(request, wsURL);
}

From source file:ee.sk.hwcrypto.demo.controller.SigningController.java

private SOAPMessage SOAPQuery(String req) {
    try {//from   www  .j a  v  a  2 s .  c  om
        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:it.cnr.icar.eric.common.SOAPMessenger.java

private void cacheSessionId(SOAPMessage message) {
    MimeHeaders mimeHeaders = message.getMimeHeaders();
    String[] header = mimeHeaders.getHeader("Set-Cookie");
    if (header != null) {
        for (int i = 0; i < header.length; i++) {
            if (header[i].startsWith("JSESSIONID")) {
                // parse JSESSIONID attribute
                String[] attributes = header[i].split(";");
                // JSESSIONID will be first attribute
                credentialInfo.sessionId = attributes[0];
                break;
            }/* ww w .  j  av a2 s .  c o  m*/
        }
    }
}

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test/*w ww.  j a  va  2s.  c o  m*/
public final void testRemoveAllAttachments() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    for (int i = 0; i < 5; i++) {
        AttachmentPart att = message.createAttachmentPart("test" + i, "text/plain");
        message.addAttachmentPart(att);
    }
    assertEquals(5, message.countAttachments());
    message.removeAllAttachments();
    assertEquals(0, message.countAttachments());
    if (message.saveRequired()) {
        message.saveChanges();
    }
    String[] contentType = message.getMimeHeaders().getHeader("Content-Type");
    assertNotNull(contentType);
    assertEquals(1, contentType.length);
    assertEquals(messageSet.getVersion().getContentType(), new MimeType(contentType[0]).getBaseType());
}