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:org.apache.ws.scout.transport.SaajTransport.java

private SOAPMessage createSOAPMessage(Element elem) throws Exception {
    String prefix = "";
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPFactory factory = SOAPFactory.newInstance();

    SOAPMessage message = msgFactory.createMessage();
    message.getSOAPHeader().detachNode();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPBody soapBody = soapPart.getEnvelope().getBody();
    //Create the outer body element
    Name bodyName = factory.createName(elem.getNodeName(), prefix, UDDI_V2_NAMESPACE);
    SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
    bodyElement.addNamespaceDeclaration(prefix, UDDI_V2_NAMESPACE);
    appendAttributes(bodyElement, elem.getAttributes(), factory);
    appendElements(bodyElement, elem.getChildNodes(), factory);
    return message;
}

From source file:org.energy_home.jemma.ah.internal.greenathome.GreenathomeAppliance.java

private static SOAPMessage createSOAPRequest(String date) throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://ws.i-em.eu/v4/";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);

    // SOAP Body/*  w  ww.ja v a 2  s.  c o  m*/
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("Get72hPlantForecast", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("plantID", "example");
    soapBodyElem1.addTextNode("telecom_02");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("quantityID", "example");
    soapBodyElem2.addTextNode("frc_pac");
    SOAPElement soapBodyElem3 = soapBodyElem.addChildElement("timestamp", "example");
    soapBodyElem3.addTextNode(date);
    SOAPElement soapBodyElem4 = soapBodyElem.addChildElement("langID", "example");
    soapBodyElem4.addTextNode("en");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI + "Get72hPlantForecast");

    soapMessage.saveChanges();

    return soapMessage;
}

From source file:org.jboss.jaxr.juddi.transport.SaajTransport.java

private SOAPMessage createSOAPMessage(Element elem) throws Exception {
    String prefix = "uddi";
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPFactory factory = SOAPFactory.newInstance();

    SOAPMessage message = msgFactory.createMessage();
    message.getSOAPHeader().detachNode();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPBody soapBody = soapPart.getEnvelope().getBody();
    //Create the outer body element
    String uddins = IRegistry.UDDI_V2_NAMESPACE;
    Name bodyName = factory.createName(elem.getNodeName(), prefix, uddins);
    SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
    bodyElement.addNamespaceDeclaration(prefix, uddins);
    appendAttributes(bodyElement, elem.getAttributes(), factory);
    appendElements(bodyElement, elem.getChildNodes(), factory);
    return message;
}

From source file:org.jboss.jaxr.juddi.transport.WS4EESaajTransport.java

public Element send(Element request, URL endpointURL) throws RegistryException {
    log.debug("Request message:" + XMLUtils.toString(request));
    if ("true".equalsIgnoreCase(debugProp))
        System.out.println("Request Element:" + XMLUtils.toString(request));

    Element response = null;//from w w  w.  ja  v a  2  s .  c  o  m
    try {
        MessageFactory msgFactory = MessageFactory.newInstance();
        SOAPMessage message = msgFactory.createMessage();
        message.getSOAPHeader().detachNode();
        SOAPPart soapPart = message.getSOAPPart();
        SOAPBody soapBody = soapPart.getEnvelope().getBody();
        soapBody.addChildElement(getSOAPElement(soapBody, request));
        //There seems to be a bug in the Saaj/Axis implementation that requires
        //message to be written to an output stream
        ByteArrayOutputStream by = new ByteArrayOutputStream();
        message.writeTo(by); //Does not do anything
        by.close();
        if ("true".equalsIgnoreCase(debugProp))
            message.writeTo(System.out);

        //Make the SAAJ Call now
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnectionFactory.createConnection();
        SOAPMessage soapResponse = connection.call(message, endpointURL);
        if ("true".equalsIgnoreCase(debugProp)) {
            System.out.println("Response is:");
            soapResponse.writeTo(System.out);
        }

        soapBody = soapResponse.getSOAPBody();
        boolean hasFault = soapBody.hasFault();
        if (hasFault) {
            SOAPFault soapFault = soapBody.getFault();
            String faultStr = soapFault.getFaultCode() + "::" + soapFault.getFaultString();
            throw new RegistryException(faultStr);
        }
        response = getFirstChildElement(soapBody);
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error(ex);
        throw new RegistryException(ex);
    }

    log.debug("Response message:" + XMLUtils.getText(response));

    return response;
}

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 a 2s .co 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/*from www  .  j ava  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 ww w  .  j av a2  s .  c  o m*/
 *            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/*from   w  ww  . j  a v  a 2  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

/**
 * Sets all required namespaces and prepares the SOAP message to send.
 * Creates skeleton + body data./*from w w w  . j a  v a  2  s.com*/
 *
 * @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.sakaiproject.compilatio.util.CompilatioAPIUtil.java

public static Document callCompilatioReturnDocument(String apiURL, Map<String, String> parameters,
        String secretKey, final int timeout) throws TransientSubmissionException, SubmissionException {

    SOAPConnectionFactory soapConnectionFactory;
    Document xmlDocument = null;//from  ww  w .ja  v a  2 s  .c o  m
    try {
        soapConnectionFactory = SOAPConnectionFactory.newInstance();

        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyAction = soapBody.addChildElement(parameters.get("action"));
        parameters.remove("action");
        // api key
        SOAPElement soapBodyKey = soapBodyAction.addChildElement("key");
        soapBodyKey.addTextNode(secretKey);

        Set<Entry<String, String>> ets = parameters.entrySet();
        Iterator<Entry<String, String>> it = ets.iterator();
        while (it.hasNext()) {
            Entry<String, String> param = it.next();
            SOAPElement soapBodyElement = soapBodyAction.addChildElement(param.getKey());
            soapBodyElement.addTextNode(param.getValue());
        }

        URL endpoint = new URL(null, apiURL, new URLStreamHandler() {
            @Override
            protected URLConnection openConnection(URL url) throws IOException {
                URL target = new URL(url.toString());
                URLConnection connection = target.openConnection();
                // Connection settings
                connection.setConnectTimeout(timeout);
                connection.setReadTimeout(timeout);
                return (connection);
            }
        });

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

        // loading the XML document
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        soapResponse.writeTo(out);
        DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
        builderfactory.setNamespaceAware(true);

        DocumentBuilder builder = builderfactory.newDocumentBuilder();
        xmlDocument = builder.parse(new InputSource(new StringReader(out.toString())));
        soapConnection.close();

    } catch (UnsupportedOperationException | SOAPException | IOException | ParserConfigurationException
            | SAXException e) {
        log.error(e);
    }
    return xmlDocument;

}