Example usage for javax.xml.soap MessageFactory newInstance

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

Introduction

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

Prototype

public static MessageFactory newInstance() throws SOAPException 

Source Link

Document

Creates a new MessageFactory object that is an instance of the default implementation (SOAP 1.1).

Usage

From source file:org.jbpm.bpel.integration.soap.SoapUtilTest.java

public void testCopy_soapDom_qualifiedNoPrefix() throws Exception {
    String xml = "<ReverseAndConcatNames xmlns='http://my.namespace'>" + " <firstName>Martin</firstName>"
            + " <secondName>Steinle</secondName>" + "</ReverseAndConcatNames>";
    Element source = XmlUtil.parseText(xml);

    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPEnvelope envelope = soapMessage.getSOAPPart().getEnvelope();
    SOAPElement target = envelope.getBody().addBodyElement(envelope.createName("detail"));

    // perform the copy
    SoapUtil.copy(target, source);/*from ww w . j a va  2s  .c  o m*/

    assertEquals("http://my.namespace", target.getNamespaceURI(SoapUtil.DEFAULT_NAMESPACE_PREFIX));
    // qualified elements
    SOAPElement firstName = SoapUtil.getElement(target, "http://my.namespace", "firstName");
    assertEquals("Martin", firstName.getValue());
    SOAPElement secondName = SoapUtil.getElement(target, "http://my.namespace", "secondName");
    assertEquals("Steinle", secondName.getValue());
}

From source file:org.jbpm.bpel.integration.soap.SoapUtilTest.java

public void testCopy_soapDom_noOverride() throws Exception {
    String xml = "<part xmlns:produce='urn:example:produce'>"
            + " <lunch produce:lettuce='0.1lb' fish:fillet='0.25lb'"
            + "  xmlns:fish='urn:example:fish' xmlns='urn:example:meal'/>" + "</part>";
    Element source = XmlUtil.parseText(xml);

    /*/*from w w w  . j a  v  a2s  .c  o  m*/
     * here, notice the 'urn:example:meal' namespace (the default namespace in the source) is mapped
     * to prefix 'fish' which the source maps to namespace 'urn:example:fish'
     */
    // <soap:Envelope xmlns:soap='${SOAPConstants.URI_NS_SOAP_ENVELOPE}'>
    // <soap:Body>"
    // <fish:Operation xmlns:fish='urn:example:meal'>
    // <part />
    // </fish:Operation>
    // </soap:Body>"
    // </soap:Envelope>
    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPElement operation = soapMessage.getSOAPBody().addChildElement("Operation", "fish", "urn:example:meal");
    SOAPElement part = SoapUtil.addChildElement(operation, "part");

    // perform the copy
    SoapUtil.copy(part, source);

    soapMessage = writeAndRead(soapMessage);
    // retrieve relevant elements
    operation = SoapUtil.getElement(soapMessage.getSOAPBody(), "urn:example:meal", "Operation");
    part = SoapUtil.getElement(operation, "part");
    SOAPElement lunch = SoapUtil.getElement(part, "urn:example:meal", "lunch");

    // prefixed declaration
    assertEquals("urn:example:fish", lunch.getNamespaceURI("fish"));
    // parent prefixed declaration
    assertEquals("urn:example:produce", lunch.getNamespaceURI("produce"));
    // default declaration (reassigned)
    assertEquals("urn:example:meal", lunch.getNamespaceURI(SoapUtil.DEFAULT_NAMESPACE_PREFIX));
}

From source file:org.libreplan.importers.TimSoapClient.java

/**
 * Creates SOAP message to be send to the SOAP server
 *
 * @return the created SOAP message/*  w w  w . ja  v a2 s  . c o  m*/
 * @throws SOAPException
 *             if unable to create soap message
 */
private static SOAPMessage createMessage() throws SOAPException {
    MessageFactory messageFactory = MessageFactory.newInstance();

    return messageFactory.createMessage();
}

From source file:org.mule.modules.paypal.util.PayPalAPIHelper.java

private static SOAPMessage createGetPalDetailsSOAPRequest(@NotNull String username, @NotNull String password,
        @NotNull String appId, String signature) throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();

    envelope.addNamespaceDeclaration(PREFIX_1, SOAP_HEADER_CREDENTIAL_NAMESPACE_1);
    envelope.addNamespaceDeclaration(PREFIX_2, SOAP_HEADER_CREDENTIAL_NAMESPACE_2);

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

    SOAPElement soapReqElement = soapHeader.addChildElement(rootStringValue, PREFIX_1);
    SOAPElement soapCredElement = soapReqElement.addChildElement(subRootStringValue, PREFIX_2);
    soapCredElement.addChildElement(appIdStringValue, PREFIX_2).addTextNode(appId);
    soapCredElement.addChildElement(usernameStringValue, PREFIX_2).addTextNode(username);
    soapCredElement.addChildElement(passwordStringValue, PREFIX_2).addTextNode(password);
    soapCredElement.addChildElement("Signature", PREFIX_2).addTextNode(signature);

    // SOAP Body/*  w ww . j  a  v  a 2s. c o  m*/
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("GetPalDetailsReq", PREFIX_1);
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("GetPalDetailsRequest", PREFIX_1);
    soapBodyElem1.addChildElement("Version", PREFIX_2).addTextNode("51");
    soapMessage.saveChanges();

    return soapMessage;
}

From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java

/**
 * Fetches the values for the given item configurations from the FritzBox. Calls
 * the FritzBox SOAP services delivering the values for the item configurations.
 * The resulting map contains the values of all item configurations returned by
 * the invoked services. This can be more items than were given as parameter.
 *
 * @param request/*from  w w w. jav  a2 s .c  om*/
 *            string from config including the command and optional parameters
 * @return Parsed values for all item configurations returned by the invoked
 *         services.
 */
public Map<ItemConfiguration, String> getTr064Values(Collection<ItemConfiguration> itemConfigurations) {
    Map<ItemConfiguration, String> values = new HashMap<>();

    for (ItemConfiguration itemConfiguration : itemConfigurations) {

        String itemCommand = itemConfiguration.getItemCommand();

        if (values.containsKey(itemCommand)) {
            // item value already read by earlier MultiItemMap
            continue;
        }

        // search for proper item Mapping
        ItemMap itemMap = determineItemMappingByItemCommand(itemCommand);

        if (itemMap == null) {
            logger.warn("No item mapping found for {}. Function not implemented by your FritzBox (?)",
                    itemConfiguration);
            continue;
        }

        // determine which url etc. to connect to for accessing required value
        Tr064Service tr064service = determineServiceByItemMapping(itemMap);

        // construct soap Body which is added to soap msg later
        SOAPBodyElement bodyData = null; // holds data to be sent to fbox
        try {
            MessageFactory mf = MessageFactory.newInstance();
            SOAPMessage msg = mf.createMessage(); // empty message
            SOAPBody body = msg.getSOAPBody(); // std. SAOP body
            QName bodyName = new QName(tr064service.getServiceType(), itemMap.getReadServiceCommand(), "u"); // header
                                                                                                             // for
                                                                                                             // body
                                                                                                             // element
            bodyData = body.addBodyElement(bodyName);
            // only if input parameter is present
            if (itemMap instanceof ParametrizedItemMap) {
                for (InputArgument inputArgument : ((ParametrizedItemMap) itemMap)
                        .getConfigInputArguments(itemConfiguration)) {
                    String dataInName = inputArgument.getName();
                    String dataInValue = inputArgument.getValue();
                    QName dataNode = new QName(dataInName);
                    SOAPElement beDataNode = bodyData.addChildElement(dataNode);
                    // if input is mac address, replace "-" with ":" as fbox wants
                    if (itemConfiguration.getItemCommand().equals("maconline")) {
                        dataInValue = dataInValue.replaceAll("-", ":");
                    }
                    beDataNode.addTextNode(dataInValue); // add data which should be requested from fbox for this
                                                         // service
                }

            }
            logger.trace("Raw SOAP Request to be sent to FritzBox: {}", soapToString(msg));

        } catch (Exception e) {
            logger.warn("Error constructing request SOAP msg for getting parameter. {}", e.getMessage());
            logger.debug("Request was: {}", itemConfiguration);
        }

        if (bodyData == null) {
            logger.warn("Could not determine data to be sent to FritzBox!");
            return null;
        }

        SOAPMessage smTr064Request = constructTr064Msg(bodyData); // construct entire msg with body element
        String soapActionHeader = tr064service.getServiceType() + "#" + itemMap.getReadServiceCommand(); // needed
                                                                                                         // to be
                                                                                                         // sent
                                                                                                         // with
                                                                                                         // request
                                                                                                         // (not
                                                                                                         // in body
                                                                                                         // ->
                                                                                                         // header)
        SOAPMessage response = readSoapResponse(soapActionHeader, smTr064Request,
                _url + tr064service.getControlUrl());
        logger.trace("Raw SOAP Response from FritzBox: {}", soapToString(response));
        if (response == null) {
            logger.warn("Error retrieving SOAP response from FritzBox");
            continue;
        }

        values.putAll(
                itemMap.getSoapValueParser().parseValuesFromSoapMessage(response, itemMap, itemConfiguration));
    }

    return values;
}

From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java

/**
 * Sets a parameter in fbox. Called from event bus.
 *
 * @param request// ww w.j  av  a2 s.c o m
 *            config string from itemconfig
 * @param cmd
 *            command to set
 */
public void setTr064Value(ItemConfiguration request, Command cmd) {
    String itemCommand = request.getItemCommand();

    // search for proper item Mapping
    ItemMap itemMapForCommand = determineItemMappingByItemCommand(itemCommand);

    if (!(itemMapForCommand instanceof WritableItemMap)) {
        logger.warn("Item command {} does not support setting values", itemCommand);
        return;
    }
    WritableItemMap itemMap = (WritableItemMap) itemMapForCommand;

    Tr064Service tr064service = determineServiceByItemMapping(itemMap);

    // determine which url etc. to connect to for accessing required value
    // construct soap Body which is added to soap msg later
    SOAPBodyElement bodyData = null; // holds data to be sent to fbox
    try {
        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage msg = mf.createMessage(); // empty message
        SOAPBody body = msg.getSOAPBody(); // std. SAOP body
        QName bodyName = new QName(tr064service.getServiceType(), itemMap.getWriteServiceCommand(), "u"); // header
                                                                                                          // for
                                                                                                          // body
                                                                                                          // element
        bodyData = body.addBodyElement(bodyName);

        List<InputArgument> writeInputArguments = new ArrayList<>();
        writeInputArguments.add(itemMap.getWriteInputArgument(cmd));
        if (itemMap instanceof ParametrizedItemMap) {
            writeInputArguments.addAll(((ParametrizedItemMap) itemMap).getConfigInputArguments(request));
        }

        for (InputArgument inputArgument : writeInputArguments) {
            QName dataNode = new QName(inputArgument.getName());
            SOAPElement beDataNode = bodyData.addChildElement(dataNode);
            beDataNode.addTextNode(inputArgument.getValue());
        }

        logger.debug("SOAP Msg to send to FritzBox for setting data: {}", soapToString(msg));

    } catch (Exception e) {
        logger.error("Error constructing request SOAP msg for setting parameter. {}", e.getMessage());
        logger.debug("Request was: {}. Command was: {}.", request, cmd.toString());
    }

    if (bodyData == null) {
        logger.error("Could not determine data to be sent to FritzBox!");
        return;
    }

    SOAPMessage smTr064Request = constructTr064Msg(bodyData); // construct entire msg with body element
    String soapActionHeader = tr064service.getServiceType() + "#" + itemMap.getWriteServiceCommand(); // needed to
                                                                                                      // be sent
                                                                                                      // with
                                                                                                      // request
                                                                                                      // (not in
                                                                                                      // body ->
                                                                                                      // header)
    SOAPMessage response = readSoapResponse(soapActionHeader, smTr064Request,
            _url + tr064service.getControlUrl());
    if (response == null) {
        logger.error("Error retrieving SOAP response from FritzBox");
        return;
    }
    logger.debug("SOAP response from FritzBox: {}", soapToString(response));

    // Check if error received
    try {
        if (response.getSOAPBody().getFault() != null) {
            logger.error("Error received from FritzBox while trying to set parameter");
            logger.debug("Soap Response was: {}", soapToString(response));
        }
    } catch (SOAPException e) {
        logger.error("Could not parse soap response from FritzBox while setting parameter. {}", e.getMessage());
        logger.debug("Soap Response was: {}", soapToString(response));
    }

}

From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java

/**
 *
 * @param soapActionHeader//from ww  w  . ja v  a2  s  .c o  m
 *            String in HTTP Header. specific for each TR064 service
 * @param request
 *            the SOAPMEssage Object to send to fbox as request
 * @param serviceUrl
 *            URL to sent the SOAP Message to (service specific)
 * @return
 */
private SOAPMessage readSoapResponse(String soapActionHeader, SOAPMessage request, String serviceUrl) {
    SOAPMessage response = null;

    // Soap Body to post
    HttpPost postSoap = new HttpPost(serviceUrl); // url is service specific
    postSoap.addHeader("SOAPAction", soapActionHeader); // add the Header specific for this request
    HttpEntity entBody = null;
    HttpResponse resp = null; // stores raw response from fbox
    boolean exceptionOccurred = false;
    try {
        entBody = new StringEntity(soapToString(request), ContentType.create("text/xml", "UTF-8")); // add body
        postSoap.setEntity(entBody);
        synchronized (_httpClient) {
            resp = _httpClient.execute(postSoap, _httpClientContext);
        }

        // Fetch content data
        StatusLine slResponse = resp.getStatusLine();
        HttpEntity heResponse = resp.getEntity();

        // Check for (auth-) error
        if (slResponse.getStatusCode() == 401) {
            logger.warn(
                    "Could not read response from FritzBox. Unauthorized! Check user and password in config. "
                            + "Verify configured user for tr064 requests. Reason from Fritzbox was: {}",
                    slResponse.getReasonPhrase());

            postSoap.releaseConnection();
            resetHttpClient();
            return null;
        }

        // Parse response into SOAP Message
        response = MessageFactory.newInstance().createMessage(null, heResponse.getContent());

    } catch (UnsupportedEncodingException e) {
        logger.error("Encoding not supported: {}", e.getMessage().toString());
        exceptionOccurred = true;
    } catch (ClientProtocolException e) {
        logger.error("Client Protocol not supported: {}", e.getMessage().toString());
        exceptionOccurred = true;
    } catch (IOException e) {
        logger.error("Cannot send/receive: {}", e.getMessage().toString());
        exceptionOccurred = true;
    } catch (UnsupportedOperationException e) {
        logger.error("Operation unsupported: {}", e.getMessage().toString());
        response = null;
        exceptionOccurred = true;
    } catch (SOAPException e) {
        logger.error("SOAP Error: {}", e.getMessage().toString());
        exceptionOccurred = true;
    } finally {
        // Make sure connection is released. If error occurred make sure to print in log
        if (exceptionOccurred) {
            logger.warn("Releasing connection to FritzBox because of error.");
            resetHttpClient();
        } else {
            logger.debug("Releasing connection");
        }
        postSoap.releaseConnection();
    }

    return response;

}

From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java

/**
 * Sets all required namespaces and prepares the SOAP message to send.
 * Creates skeleton + body data./* w w  w .j a v  a  2  s  . co m*/
 *
 * @param bodyData
 *            is attached to skeleton to form entire SOAP message
 * @return ready to send SOAP message
 */
private SOAPMessage constructTr064Msg(SOAPBodyElement bodyData) {
    SOAPMessage soapMsg = null;

    try {
        MessageFactory msgFac;
        msgFac = MessageFactory.newInstance();
        soapMsg = msgFac.createMessage();
        soapMsg.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
        soapMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
        SOAPPart part = soapMsg.getSOAPPart();

        // valid for entire SOAP msg
        String namespace = "s";

        // create suitable fbox envelope
        SOAPEnvelope envelope = part.getEnvelope();
        envelope.setPrefix(namespace);
        envelope.removeNamespaceDeclaration("SOAP-ENV"); // delete standard namespace which was already set
        envelope.addNamespaceDeclaration(namespace, "http://schemas.xmlsoap.org/soap/envelope/");
        Name nEncoding = envelope.createName("encodingStyle", namespace,
                "http://schemas.xmlsoap.org/soap/encoding/");
        envelope.addAttribute(nEncoding, "http://schemas.xmlsoap.org/soap/encoding/");

        // create empty header
        SOAPHeader header = envelope.getHeader();
        header.setPrefix(namespace);

        // create body with command based on parameter
        SOAPBody body = envelope.getBody();
        body.setPrefix(namespace);
        body.addChildElement(bodyData); // bodyData already prepared. Needs only be added

    } catch (Exception e) {
        logger.error("Error creating SOAP message for fbox request with data {}", bodyData);
        e.printStackTrace();
    }

    return soapMsg;
}

From source file:org.openhie.test.xds.util.SoapMessageSender.java

private SOAPMessage getSoapMessageFromString() throws SOAPException, IOException {
    MessageFactory factory = MessageFactory.newInstance();

    //MimeHeaders header=new MimeHeaders();
    //header.addHeader("Content-Type","application/xop+xml; application/soap+xml" + "action=urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-b" + "boundary=MIMEBoundaryurn_uuid_E3F7CE4554928DA89B1231365678616;"+ "Content-Transfer-Encoding=binary" + "Content-ID=\"<0.urn:uuid:E3F7CE4554928DA89B1231365678617@apache.org>\"");
    //header.addHeader("action", "urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-b");

    SOAPMessage message = MessageFactory.newInstance().createMessage();
    SOAPPart soapPart = message.getSOAPPart();

    MimeHeaders header = message.getMimeHeaders();
    //header.addHeader("Content-Type","application/xop+xml; application/soap+xml" + "action=urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-b" + "boundary=MIMEBoundaryurn_uuid_E3F7CE4554928DA89B1231365678616;"+ "Content-Transfer-Encoding=binary" + "Content-ID=\"<0.urn:uuid:E3F7CE4554928DA89B1231365678617@apache.org>\"");
    //header.addHeader("Content-Type", "multipart/related;start=<rootpart*17f1ec84-85ec-4f1f-9b29-423a6a2e354f@example.jaxws.sun.com>;type=application/xop+xml;boundary=uuid:17f1ec84-85ec-4f1f-9b29-423a6a2e354f\";start-info=\"application/soap+xml\";action=\"urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-b");
    header.setHeader("Content-Type", "application/soap+xml;charset=UTF-8");

    SOAPHeader soap = message.getSOAPHeader();
    soapPart.setContent(new StreamSource(new FileInputStream(
            "/Users/snkasthu/SourceCode/cds/openhie-integration-tests/src/test/resources/xds/OHIE-XDS-01-10.xml")));

    System.out.print("Request SOAP Message :");
    message.writeTo(System.out);/*ww  w .  ja va2 s.c  om*/
    System.out.println();

    return message;
}

From source file:org.overlord.rtgov.tests.platforms.jbossas.activityserver.JBossASActivityServerServiceTest.java

@Test
@OperateOnDeployment("orders-app")
public void testQueryActivityServer() {

    try {/*from ww  w. j  a  v a 2s .c om*/
        SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
        SOAPConnection con = factory.createConnection();

        java.net.URL url = new java.net.URL(ORDER_SERVICE_URL);

        String mesg = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "   <soap:Body>"
                + "       <orders:submitOrder xmlns:orders=\"urn:switchyard-quickstart-demo:orders:1.0\">"
                + "            <order>" + "                <orderId>1</orderId>"
                + "                <itemId>BUTTER</itemId>" + "                <quantity>100</quantity>"
                + "                <customer>Fred</customer>" + "            </order>"
                + "        </orders:submitOrder>" + "    </soap:Body>" + "</soap:Envelope>";

        long startTime = System.currentTimeMillis();

        java.io.InputStream is = new java.io.ByteArrayInputStream(mesg.getBytes());

        SOAPMessage request = MessageFactory.newInstance().createMessage(null, is);

        is.close();

        SOAPMessage response = con.call(request, url);

        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();

        response.writeTo(baos);

        baos.close();

        // Wait for events to propagate
        Thread.sleep(4000);

        java.util.List<ActivityType> acts = getActivityEvents(startTime, System.currentTimeMillis());

        if (acts == null) {
            fail("Activity event list is null");
        }

        System.out.println("LIST SIZE=" + acts.size());

        System.out.println("LIST=" + acts);

        if (acts.size() != 12) {
            fail("Expecting 12 activity events: " + acts.size());
        }

        // RTGOV-256 Check that first activity type has header value extracted as a property
        ActivityType at = acts.get(0);

        if (!at.getProperties().containsKey("contentType")) {
            fail("Property 'contentType' not found");
        }

        if (!at.getProperties().get("contentType")
                .equals("{urn:switchyard-quickstart-demo:orders:1.0}submitOrder")) {
            fail("Incorrect content type, expecting '{urn:switchyard-quickstart-demo:orders:1.0}submitOrder' but got: "
                    + at.getProperties().get("contentType"));
        }

        if (!at.getProperties().containsKey("gateway")) {
            fail("Property 'gateway' not found");
        }

        if (!at.getProperties().get("gateway").equals("soap")) {
            fail("Incorrect gateway, expecting 'soap' but got: " + at.getProperties().get("gateway"));
        }

    } catch (Exception e) {
        e.printStackTrace();
        fail("Failed to invoke service: " + e);
    }
}