Example usage for javax.xml.soap SOAPBodyElement addChildElement

List of usage examples for javax.xml.soap SOAPBodyElement addChildElement

Introduction

In this page you can find the example usage for javax.xml.soap SOAPBodyElement addChildElement.

Prototype

public SOAPElement addChildElement(Name name) throws SOAPException;

Source Link

Document

Creates a new SOAPElement object initialized with the given Name object and adds the new element to this SOAPElement object.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
    SOAPConnection connection = sfc.createConnection();

    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage sm = mf.createMessage();

    SOAPHeader sh = sm.getSOAPHeader();
    SOAPBody sb = sm.getSOAPBody();
    sh.detachNode();//  w  w  w.  j  av  a 2 s. c  o m
    QName bodyName = new QName("http://quoteCompany.com", "GetQuote", "d");
    SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);
    QName qn = new QName("aName");
    SOAPElement quotation = bodyElement.addChildElement(qn);

    quotation.addTextNode("TextMode");

    System.out.println("\n Soap Request:\n");
    sm.writeTo(System.out);
    System.out.println();

    URL endpoint = new URL("http://yourServer.com");
    SOAPMessage response = connection.call(sm, endpoint);
    System.out.println(response.getContentDescription());
}

From source file:SOAPRequest.java

public static void main(String[] args) {
    try {//from www .j  av  a  2s  .c o  m
        SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = sfc.createConnection();

        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage sm = mf.createMessage();

        SOAPHeader sh = sm.getSOAPHeader();
        SOAPBody sb = sm.getSOAPBody();
        sh.detachNode();
        QName bodyName = new QName("http://quoteCompany.com", "GetQuote", "d");
        SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);
        QName qn = new QName("aName");
        SOAPElement quotation = bodyElement.addChildElement(qn);

        quotation.addTextNode("TextMode");

        System.out.println("\n Soap Request:\n");
        sm.writeTo(System.out);
        System.out.println();

        URL endpoint = new URL("http://yourServer.com");
        SOAPMessage response = connection.call(sm, endpoint);
        System.out.println(response.getContentDescription());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:edu.xtec.colex.client.beans.ColexIndexBean.java

/**
 * Calls the web service operation <I>importCollection(User,Collection,FILE)
 * : void</I>/*w  w  w  .j  av a  2 s.com*/
 *
 * @param importName the String name of the Collection to import
 * @param fiImport the FileItem Zip of the Collection to import
 * @throws java.lang.Exception when an Exception error occurs
 */
private void importCollection(String importName, FileItem fiImport) throws Exception {
    User uRequest = new User(getUserId());
    Collection cRequest = new Collection(importName);
    File fTemp = null;

    try {
        smRequest = mf.createMessage();

        SOAPBody sbRequest = smRequest.getSOAPBody();

        Name n = sf.createName("importCollection");

        SOAPBodyElement sbeRequest = sbRequest.addBodyElement(n);

        sbeRequest.addChildElement(uRequest.toXml());
        sbeRequest.addChildElement(cRequest.toXml());

        String sNomFitxer = Utils.getFileName(fiImport.getName());

        fTemp = File.createTempFile("attach", null);

        fiImport.write(fTemp);

        URL urlFile = new URL("file://" + fTemp.getPath());

        AttachmentPart ap = smRequest.createAttachmentPart(new DataHandler(urlFile));

        smRequest.addAttachmentPart(ap);

        smRequest.saveChanges();

        SOAPMessage smResponse = sendMessage(smRequest,
                this.getJspProperties().getProperty("url.servlet.collection"));

        SOAPBody sbResponse = smResponse.getSOAPBody();

        if (sbResponse.hasFault()) {
            checkFault(sbResponse, "import");
        } else {

        }

    } catch (Exception e) {
        throw e;
    } finally {
        if (fTemp != null) {
            fTemp.delete();
        }
    }
}

From source file:cl.nic.dte.net.ConexionSii.java

@SuppressWarnings("unchecked")
public String getToken(PrivateKey pKey, X509Certificate cert)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException,
        XMLSignatureException, SAXException, IOException, ParserConfigurationException, XmlException,
        UnsupportedOperationException, SOAPException, ConexionSiiException {

    String urlSolicitud = Utilities.netLabels.getString("URL_SOLICITUD_TOKEN");

    String semilla = getSemilla();

    GetTokenDocument req = GetTokenDocument.Factory.newInstance();

    req.addNewGetToken().addNewItem().setSemilla(semilla);

    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("", "http://www.sii.cl/SiiDte");
    XmlOptions opts = new XmlOptions();

    opts = new XmlOptions();
    opts.setSaveImplicitNamespaces(namespaces);
    opts.setLoadSubstituteNamespaces(namespaces);
    opts.setSavePrettyPrint();/*from  w w  w  . j av  a 2 s . c o m*/
    opts.setSavePrettyPrintIndent(0);

    req = GetTokenDocument.Factory.parse(req.newInputStream(opts), opts);

    // firmo
    req.sign(pKey, cert);

    SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection con = scFactory.createConnection();
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPBody body = envelope.getBody();
    header.detachNode();

    Name bodyName = envelope.createName("getToken", "m", urlSolicitud);
    SOAPBodyElement gltp = body.addBodyElement(bodyName);

    Name toKname = envelope.createName("pszXml");

    SOAPElement toKsymbol = gltp.addChildElement(toKname);

    opts = new XmlOptions();
    opts.setCharacterEncoding("ISO-8859-1");
    opts.setSaveImplicitNamespaces(namespaces);

    toKsymbol.addTextNode(req.xmlText(opts));

    message.getMimeHeaders().addHeader("SOAPAction", "");

    URL endpoint = new URL(urlSolicitud);

    message.writeTo(System.out);

    SOAPMessage responseSII = con.call(message, endpoint);

    SOAPPart sp = responseSII.getSOAPPart();
    SOAPBody b = sp.getEnvelope().getBody();

    cl.sii.xmlSchema.RESPUESTADocument resp = null;
    for (Iterator<SOAPBodyElement> res = b.getChildElements(
            sp.getEnvelope().createName("getTokenResponse", "ns1", urlSolicitud)); res.hasNext();) {
        for (Iterator<SOAPBodyElement> ret = res.next().getChildElements(
                sp.getEnvelope().createName("getTokenReturn", "ns1", urlSolicitud)); ret.hasNext();) {

            namespaces = new HashMap<String, String>();
            namespaces.put("", "http://www.sii.cl/XMLSchema");
            opts.setLoadSubstituteNamespaces(namespaces);

            resp = RESPUESTADocument.Factory.parse(ret.next().getValue(), opts);
        }
    }

    if (resp != null && resp.getRESPUESTA().getRESPHDR().getESTADO() == 0) {
        return resp.getRESPUESTA().getRESPBODY().getTOKEN();
    } else {
        throw new ConexionSiiException(
                "No obtuvo Semilla: Codigo: " + resp.getRESPUESTA().getRESPHDR().getESTADO() + "; Glosa: "
                        + resp.getRESPUESTA().getRESPHDR().getGLOSA());
    }

}

From source file:cl.nic.dte.net.ConexionSii.java

@SuppressWarnings("unchecked")
private RESPUESTADocument getEstadoDTE(String rutConsultante, Documento dte, String token, String urlSolicitud)
        throws UnsupportedOperationException, SOAPException, MalformedURLException, XmlException {

    String rutEmisor = dte.getEncabezado().getEmisor().getRUTEmisor();
    String rutReceptor = dte.getEncabezado().getReceptor().getRUTRecep();
    Integer tipoDTE = dte.getEncabezado().getIdDoc().getTipoDTE().intValue();
    long folioDTE = dte.getEncabezado().getIdDoc().getFolio();
    String fechaEmision = Utilities.fechaEstadoDte
            .format(dte.getEncabezado().getIdDoc().getFchEmis().getTime());
    long montoTotal = dte.getEncabezado().getTotales().getMntTotal();

    SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection con = scFactory.createConnection();
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPBody body = envelope.getBody();
    header.detachNode();//  w w  w . j  a v  a2 s  .c o  m

    Name bodyName = envelope.createName("getEstDte", "m", urlSolicitud);
    SOAPBodyElement gltp = body.addBodyElement(bodyName);

    Name toKname = envelope.createName("RutConsultante");
    SOAPElement toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutConsultante.substring(0, rutConsultante.length() - 2));

    toKname = envelope.createName("DvConsultante");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutConsultante.substring(rutConsultante.length() - 1, rutConsultante.length()));

    toKname = envelope.createName("RutCompania");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutEmisor.substring(0, rutEmisor.length() - 2));

    toKname = envelope.createName("DvCompania");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutEmisor.substring(rutEmisor.length() - 1, rutEmisor.length()));

    toKname = envelope.createName("RutReceptor");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutReceptor.substring(0, rutReceptor.length() - 2));

    toKname = envelope.createName("DvReceptor");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(rutReceptor.substring(rutReceptor.length() - 1, rutReceptor.length()));

    toKname = envelope.createName("TipoDte");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(Integer.toString(tipoDTE));

    toKname = envelope.createName("FolioDte");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(Long.toString(folioDTE));

    toKname = envelope.createName("FechaEmisionDte");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(fechaEmision);

    toKname = envelope.createName("MontoDte");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(Long.toString(montoTotal));

    toKname = envelope.createName("Token");
    toKsymbol = gltp.addChildElement(toKname);
    toKsymbol.addTextNode(token);

    message.getMimeHeaders().addHeader("SOAPAction", "");

    URL endpoint = new URL(urlSolicitud);

    SOAPMessage responseSII = con.call(message, endpoint);

    SOAPPart sp = responseSII.getSOAPPart();
    SOAPBody b = sp.getEnvelope().getBody();

    for (Iterator<SOAPBodyElement> res = b.getChildElements(
            sp.getEnvelope().createName("getEstDteResponse", "ns1", urlSolicitud)); res.hasNext();) {
        for (Iterator<SOAPBodyElement> ret = res.next().getChildElements(
                sp.getEnvelope().createName("getEstDteReturn", "ns1", urlSolicitud)); ret.hasNext();) {

            HashMap<String, String> namespaces = new HashMap<String, String>();
            namespaces.put("", "http://www.sii.cl/XMLSchema");
            XmlOptions opts = new XmlOptions();
            opts.setLoadSubstituteNamespaces(namespaces);

            return RESPUESTADocument.Factory.parse(ret.next().getValue(), opts);
        }
    }

    return null;

}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdController.java

private byte[] createRequestXml(String action, ImmutablePair<String, String>... params) {
    try {/*w  w w .ja  v a 2  s . co  m*/
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage soapMessage = factory.createMessage();

        SOAPBodyElement actionElement = soapMessage.getSOAPBody().addBodyElement(new QName(null, action, "m"));
        actionElement.addNamespaceDeclaration("m", serviceType);

        for (Pair<String, String> param : params) {
            SOAPElement paramElement = actionElement.addChildElement(QName.valueOf(param.getKey()));
            paramElement.setValue(param.getValue());
        }

        soapMessage.getSOAPPart().setXmlStandalone(true);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new DOMSource(soapMessage.getSOAPPart()), new StreamResult(baos));

        return baos.toByteArray();
    } catch (IllegalArgumentException | SOAPException | TransformerException | DOMException e) {
        throw new IllegalStateException(e); // should never happen
    }
}

From source file:edu.xtec.colex.client.beans.ColexRecordBean.java

/**
 * Calls the web service operation/*from  w  w  w  .  j ava  2  s .c om*/
 * <I>importRecords(User,Owner,Collection,FILE) : void</I>
 *
 * @param fiImport the FileItem Zip of the Records to import
 * @throws java.lang.Exception when an Exception error occurs
 */
protected void importRecords(FileItem fiImport) throws Exception {
    User uRequest = new User(getUserId());
    Collection cRequest = new Collection(collection);
    File fTemp = null;

    try {
        smRequest = mf.createMessage();

        SOAPBody sbRequest = smRequest.getSOAPBody();

        Name n = sf.createName("importRecords");

        SOAPBodyElement sbeRequest = sbRequest.addBodyElement(n);

        sbeRequest.addChildElement(uRequest.toXml());

        if (owner != null) {
            Owner oRequest = new Owner(owner);
            sbeRequest.addChildElement(oRequest.toXml());
        }

        sbeRequest.addChildElement(cRequest.toXml());

        String sNomFitxer = Utils.getFileName(fiImport.getName());

        fTemp = File.createTempFile("attach", null);

        fiImport.write(fTemp);

        URL urlFile = new URL("file://" + fTemp.getPath());

        AttachmentPart ap = smRequest.createAttachmentPart(new DataHandler(urlFile));

        smRequest.addAttachmentPart(ap);

        smRequest.saveChanges();

        SOAPMessage smResponse = sendMessage(smRequest,
                this.getJspProperties().getProperty("url.servlet.record"));

        SOAPBody sbResponse = smResponse.getSOAPBody();

        if (sbResponse.hasFault()) {
            checkFault(sbResponse, "importRecords");
        } else {

        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (fTemp != null) {
            fTemp.delete();
        }
    }
}

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.  ja v  a  2  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   www. j  a va 2  s  .  co 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));
    }

}