Использование SoapUi, сгенерированного POJO - PullRequest
0 голосов
/ 02 ноября 2018

Я использовал soapUi для генерации Java Pojo из WSDL, один из сгенерированных классов выглядит следующим образом FACValidatyRequest class

package com.innovectives.octopus.gt.bank.agency.common.dto;

import javax.xml.stream.XMLStreamException;
import org.apache.axis2.databinding.ADBException;


/**
 *  FacValidityRequest bean class
 */
@SuppressWarnings({"unchecked",
"unused"
})
public class FacValidityRequest implements org.apache.axis2.databinding.ADBBean {
/* This type was generated from the piece of schema that had
   name = FacValidityRequest
   Namespace URI = http://tempuri.org/
   Namespace Prefix = ns1
 */

/**
 * field for FACCode
 */
protected java.lang.String localFACCode;

/*  This tracker boolean wil be used to detect whether the user called the set method
 *   for this attribute. It will be used to determine whether to include this field
 *   in the serialized XML
 */
protected boolean localFACCodeTracker = false;

/**
 * field for MobileNumber
 */
protected java.lang.String localMobileNumber;

/*  This tracker boolean wil be used to detect whether the user called the set method
 *   for this attribute. It will be used to determine whether to include this field
 *   in the serialized XML
 */
protected boolean localMobileNumberTracker = false;

/**
 * field for UniqueId
 */
protected java.lang.String localUniqueId;

/*  This tracker boolean wil be used to detect whether the user called the set method
 *   for this attribute. It will be used to determine whether to include this field
 *   in the serialized XML
 */
protected boolean localUniqueIdTracker = false;

/**
 * field for Hash
 */
protected java.lang.String localHash;

/*  This tracker boolean wil be used to detect whether the user called the set method
 *   for this attribute. It will be used to determine whether to include this field
 *   in the serialized XML
 */
protected boolean localHashTracker = false;

public boolean isFACCodeSpecified() {
    return localFACCodeTracker;
}

/**
 * Auto generated getter method
 * @return java.lang.String
 */
public java.lang.String getFACCode() {
    return localFACCode;
}

/**
 * Auto generated setter method
 * @param param FACCode
 */
public void setFACCode(java.lang.String param) {
    localFACCodeTracker = param != null;

    this.localFACCode = param;
}

public boolean isMobileNumberSpecified() {
    return localMobileNumberTracker;
}

/**
 * Auto generated getter method
 * @return java.lang.String
 */
public java.lang.String getMobileNumber() {
    return localMobileNumber;
}

/**
 * Auto generated setter method
 * @param param MobileNumber
 */
public void setMobileNumber(java.lang.String param) {
    localMobileNumberTracker = param != null;

    this.localMobileNumber = param;
}

public boolean isUniqueIdSpecified() {
    return localUniqueIdTracker;
}

/**
 * Auto generated getter method
 * @return java.lang.String
 */
public java.lang.String getUniqueId() {
    return localUniqueId;
}

/**
 * Auto generated setter method
 * @param param UniqueId
 */
public void setUniqueId(java.lang.String param) {
    localUniqueIdTracker = param != null;

    this.localUniqueId = param;
}

public boolean isHashSpecified() {
    return localHashTracker;
}

/**
 * Auto generated getter method
 * @return java.lang.String
 */
public java.lang.String getHash() {
    return localHash;
}

/**
 * Auto generated setter method
 * @param param Hash
 */
public void setHash(java.lang.String param) {
    localHashTracker = param != null;

    this.localHash = param;
}

/**
 *
 * @param parentQName
 * @param factory
 * @return org.apache.axiom.om.OMElement
 * @throws org.apache.axis2.databinding.ADBException
 */
@Override
public org.apache.axiom.om.OMElement getOMElement(
    final javax.xml.namespace.QName parentQName,
    final org.apache.axiom.om.OMFactory factory)
    throws org.apache.axis2.databinding.ADBException {
    return factory.createOMElement(new org.apache.axis2.databinding.ADBDataSource(
            this, parentQName));
}

/**
 *
 * @param parentQName
 * @param xmlWriter
 * @throws XMLStreamException
 * @throws ADBException
 */
@Override
public void serialize(final javax.xml.namespace.QName parentQName,
    javax.xml.stream.XMLStreamWriter xmlWriter)
    throws javax.xml.stream.XMLStreamException,
        org.apache.axis2.databinding.ADBException {
    serialize(parentQName, xmlWriter, false);
}

/**
 *
 * @param parentQName
 * @param xmlWriter
 * @param serializeType
 * @throws XMLStreamException
 * @throws ADBException
 */
@Override
public void serialize(final javax.xml.namespace.QName parentQName,
    javax.xml.stream.XMLStreamWriter xmlWriter, boolean serializeType)
    throws javax.xml.stream.XMLStreamException,
        org.apache.axis2.databinding.ADBException {
    java.lang.String prefix = null;
    java.lang.String namespace = null;

    prefix = parentQName.getPrefix();
    namespace = parentQName.getNamespaceURI();
    writeStartElement(prefix, namespace, parentQName.getLocalPart(),
        xmlWriter);

    if (serializeType) {
        java.lang.String namespacePrefix = registerPrefix(xmlWriter,
                "http://tempuri.org/");

        if ((namespacePrefix != null) &&
                (namespacePrefix.trim().length() > 0)) {
            writeAttribute("xsi",
                "http://www.w3.org/2001/XMLSchema-instance", "type",
                namespacePrefix + ":FacValidityRequest", xmlWriter);
        } else {
            writeAttribute("xsi",
                "http://www.w3.org/2001/XMLSchema-instance", "type",
                "FacValidityRequest", xmlWriter);
        }
    }

    if (localFACCodeTracker) {
        namespace = "http://tempuri.org/";
        writeStartElement(null, namespace, "FACCode", xmlWriter);

        if (localFACCode == null) {
            // write the nil attribute
            throw new org.apache.axis2.databinding.ADBException(
                "FACCode cannot be null!!");
        } else {
            xmlWriter.writeCharacters(localFACCode);
        }

        xmlWriter.writeEndElement();
    }

    if (localMobileNumberTracker) {
        namespace = "http://tempuri.org/";
        writeStartElement(null, namespace, "MobileNumber", xmlWriter);

        if (localMobileNumber == null) {
            // write the nil attribute
            throw new org.apache.axis2.databinding.ADBException(
                "MobileNumber cannot be null!!");
        } else {
            xmlWriter.writeCharacters(localMobileNumber);
        }

        xmlWriter.writeEndElement();
    }

    if (localUniqueIdTracker) {
        namespace = "http://tempuri.org/";
        writeStartElement(null, namespace, "UniqueId", xmlWriter);

        if (localUniqueId == null) {
            // write the nil attribute
            throw new org.apache.axis2.databinding.ADBException(
                "UniqueId cannot be null!!");
        } else {
            xmlWriter.writeCharacters(localUniqueId);
        }

        xmlWriter.writeEndElement();
    }

    if (localHashTracker) {
        namespace = "http://tempuri.org/";
        writeStartElement(null, namespace, "Hash", xmlWriter);

        if (localHash == null) {
            // write the nil attribute
            throw new org.apache.axis2.databinding.ADBException(
                "Hash cannot be null!!");
        } else {
            xmlWriter.writeCharacters(localHash);
        }

        xmlWriter.writeEndElement();
    }

    xmlWriter.writeEndElement();
}

private static java.lang.String generatePrefix(java.lang.String namespace) {
    if (namespace.equals("http://tempuri.org/")) {
        return "ns1";
    }

    return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}

/**
 * Utility method to write an element start tag.
 */
private void writeStartElement(java.lang.String prefix,
    java.lang.String namespace, java.lang.String localPart,
    javax.xml.stream.XMLStreamWriter xmlWriter)
    throws javax.xml.stream.XMLStreamException {
    java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);

    if (writerPrefix != null) {
        xmlWriter.writeStartElement(writerPrefix, localPart, namespace);
    } else {
        if (namespace.length() == 0) {
            prefix = "";
        } else if (prefix == null) {
            prefix = generatePrefix(namespace);
        }

        xmlWriter.writeStartElement(prefix, localPart, namespace);
        xmlWriter.writeNamespace(prefix, namespace);
        xmlWriter.setPrefix(prefix, namespace);
    }
}

/**
 * Util method to write an attribute with the ns prefix
 */
private void writeAttribute(java.lang.String prefix,
    java.lang.String namespace, java.lang.String attName,
    java.lang.String attValue, javax.xml.stream.XMLStreamWriter xmlWriter)
    throws javax.xml.stream.XMLStreamException {
    java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);

    if (writerPrefix != null) {
        xmlWriter.writeAttribute(writerPrefix, namespace, attName, attValue);
    } else {
        xmlWriter.writeNamespace(prefix, namespace);
        xmlWriter.setPrefix(prefix, namespace);
        xmlWriter.writeAttribute(prefix, namespace, attName, attValue);
    }
}

/**
 * Util method to write an attribute without the ns prefix
 */
private void writeAttribute(java.lang.String namespace,
    java.lang.String attName, java.lang.String attValue,
    javax.xml.stream.XMLStreamWriter xmlWriter)
    throws javax.xml.stream.XMLStreamException {
    if (namespace.equals("")) {
        xmlWriter.writeAttribute(attName, attValue);
    } else {
        xmlWriter.writeAttribute(registerPrefix(xmlWriter, namespace),
            namespace, attName, attValue);
    }
}

/**
 * Util method to write an attribute without the ns prefix
 */
private void writeQNameAttribute(java.lang.String namespace,
    java.lang.String attName, javax.xml.namespace.QName qname,
    javax.xml.stream.XMLStreamWriter xmlWriter)
    throws javax.xml.stream.XMLStreamException {
    java.lang.String attributeNamespace = qname.getNamespaceURI();
    java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);

    if (attributePrefix == null) {
        attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
    }

    java.lang.String attributeValue;

    if (attributePrefix.trim().length() > 0) {
        attributeValue = attributePrefix + ":" + qname.getLocalPart();
    } else {
        attributeValue = qname.getLocalPart();
    }

    if (namespace.equals("")) {
        xmlWriter.writeAttribute(attName, attributeValue);
    } else {
        registerPrefix(xmlWriter, namespace);
        xmlWriter.writeAttribute(attributePrefix, namespace, attName,
            attributeValue);
    }
}

/**
 *  method to handle Qnames
 */
private void writeQName(javax.xml.namespace.QName qname,
    javax.xml.stream.XMLStreamWriter xmlWriter)
    throws javax.xml.stream.XMLStreamException {
    java.lang.String namespaceURI = qname.getNamespaceURI();

    if (namespaceURI != null) {
        java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);

        if (prefix == null) {
            prefix = generatePrefix(namespaceURI);
            xmlWriter.writeNamespace(prefix, namespaceURI);
            xmlWriter.setPrefix(prefix, namespaceURI);
        }

        if (prefix.trim().length() > 0) {
            xmlWriter.writeCharacters(prefix + ":" +
                org.apache.axis2.databinding.utils.ConverterUtil.convertToString(
                    qname));
        } else {
            // i.e this is the default namespace
            xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(
                    qname));
        }
    } else {
        xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(
                qname));
    }
}

private void writeQNames(javax.xml.namespace.QName[] qnames,
    javax.xml.stream.XMLStreamWriter xmlWriter)
    throws javax.xml.stream.XMLStreamException {
    if (qnames != null) {
        // we have to store this data until last moment since it is not possible to write any
        // namespace data after writing the charactor data
        StringBuilder stringToWrite = new StringBuilder();
        java.lang.String namespaceURI = null;
        java.lang.String prefix = null;

        for (int i = 0; i < qnames.length; i++) {
            if (i > 0) {
                stringToWrite.append(" ");
            }

            namespaceURI = qnames[i].getNamespaceURI();

            if (namespaceURI != null) {
                prefix = xmlWriter.getPrefix(namespaceURI);

                if ((prefix == null) || (prefix.length() == 0)) {
                    prefix = generatePrefix(namespaceURI);
                    xmlWriter.writeNamespace(prefix, namespaceURI);
                    xmlWriter.setPrefix(prefix, namespaceURI);
                }

                if (prefix.trim().length() > 0) {
                    stringToWrite.append(prefix).append(":")
                                 .append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(
                            qnames[i]));
                } else {
                    stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(
                            qnames[i]));
                }
            } else {
                stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(
                        qnames[i]));
            }
        }

        xmlWriter.writeCharacters(stringToWrite.toString());
    }
}

/**
 * Register a namespace prefix
 */
private java.lang.String registerPrefix(
    javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace)
    throws javax.xml.stream.XMLStreamException {
    java.lang.String prefix = xmlWriter.getPrefix(namespace);

    if (prefix == null) {
        prefix = generatePrefix(namespace);

        javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();

        while (true) {
            java.lang.String uri = nsContext.getNamespaceURI(prefix);

            if ((uri == null) || (uri.length() == 0)) {
                break;
            }

            prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
        }

        xmlWriter.writeNamespace(prefix, namespace);
        xmlWriter.setPrefix(prefix, namespace);
    }

    return prefix;
}

/**
 *  Factory class that keeps the parse method
 */
public static class Factory {
    private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(Factory.class);

    /**
     * static method to create the object
     * Precondition:  If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
     *                If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
     * Postcondition: If this object is an element, the reader is positioned at its end element
     *                If this object is a complex type, the reader is positioned at the end element of its outer element
     * @param reader
     * @return 
     * @throws java.lang.Exception 
     */
    public static FacValidityRequest parse(
        javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
        FacValidityRequest object = new FacValidityRequest();

        int event;
        javax.xml.namespace.QName currentQName = null;
        java.lang.String nillableValue = null;
        java.lang.String prefix = "";
        java.lang.String namespaceuri = "";

        try {
            while (!reader.isStartElement() && !reader.isEndElement())
                reader.next();

            currentQName = reader.getName();

            if (reader.getAttributeValue(
                        "http://www.w3.org/2001/XMLSchema-instance", "type") != null) {
                java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
                        "type");

                if (fullTypeName != null) {
                    java.lang.String nsPrefix = null;

                    if (fullTypeName.indexOf(":") > -1) {
                        nsPrefix = fullTypeName.substring(0,
                                fullTypeName.indexOf(":"));
                    }

                    nsPrefix = (nsPrefix == null) ? "" : nsPrefix;

                    java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(
                                ":") + 1);

                    if (!"FacValidityRequest".equals(type)) {
                        //find namespace for the prefix
                        java.lang.String nsUri = reader.getNamespaceContext()
                                                       .getNamespaceURI(nsPrefix);

                        return (FacValidityRequest) ExtensionMapper.getTypeObject(nsUri,
                            type, reader);
                    }
                }
            }

            // Note all attributes that were handled. Used to differ normal attributes
            // from anyAttributes.
            java.util.Vector handledAttributes = new java.util.Vector();

            reader.next();

            while (!reader.isStartElement() && !reader.isEndElement())
                reader.next();

            if (reader.isStartElement() &&
                    new javax.xml.namespace.QName("http://tempuri.org/",
                        "FACCode").equals(reader.getName())) {
                nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
                        "nil");

                if ("true".equals(nillableValue) ||
                        "1".equals(nillableValue)) {
                    throw new org.apache.axis2.databinding.ADBException(
                        "The element: " + "FACCode" + "  cannot be null");
                }

                java.lang.String content = reader.getElementText();

                object.setFACCode(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(
                        content));

                reader.next();
            } // End of if for expected property start element

            else {
            }

            while (!reader.isStartElement() && !reader.isEndElement())
                reader.next();

            if (reader.isStartElement() &&
                    new javax.xml.namespace.QName("http://tempuri.org/",
                        "MobileNumber").equals(reader.getName())) {
                nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
                        "nil");

                if ("true".equals(nillableValue) ||
                        "1".equals(nillableValue)) {
                    throw new org.apache.axis2.databinding.ADBException(
                        "The element: " + "MobileNumber" +
                        "  cannot be null");
                }

                java.lang.String content = reader.getElementText();

                object.setMobileNumber(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(
                        content));

                reader.next();
            } // End of if for expected property start element

            else {
            }

            while (!reader.isStartElement() && !reader.isEndElement())
                reader.next();

            if (reader.isStartElement() &&
                    new javax.xml.namespace.QName("http://tempuri.org/",
                        "UniqueId").equals(reader.getName())) {
                nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
                        "nil");

                if ("true".equals(nillableValue) ||
                        "1".equals(nillableValue)) {
                    throw new org.apache.axis2.databinding.ADBException(
                        "The element: " + "UniqueId" + "  cannot be null");
                }

                java.lang.String content = reader.getElementText();

                object.setUniqueId(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(
                        content));

                reader.next();
            } // End of if for expected property start element

            else {
            }

            while (!reader.isStartElement() && !reader.isEndElement())
                reader.next();

            if (reader.isStartElement() &&
                    new javax.xml.namespace.QName("http://tempuri.org/",
                        "Hash").equals(reader.getName())) {
                nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
                        "nil");

                if ("true".equals(nillableValue) ||
                        "1".equals(nillableValue)) {
                    throw new org.apache.axis2.databinding.ADBException(
                        "The element: " + "Hash" + "  cannot be null");
                }

                java.lang.String content = reader.getElementText();

                object.setHash(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(
                        content));

                reader.next();
            } // End of if for expected property start element

            else {
            }

            while (!reader.isStartElement() && !reader.isEndElement())
                reader.next();

            if (reader.isStartElement()) {
                // 2 - A start element we are not expecting indicates a trailing invalid property
                throw new org.apache.axis2.databinding.ADBException(
                    "Unexpected subelement " + reader.getName());
            }
        } catch (javax.xml.stream.XMLStreamException e) {
            throw new java.lang.Exception(e);
        }

        return object;
    }
} //end of factory class
}

Я попытался использовать POJO и установить его значения, как я сделал ниже, но я не могу просмотреть строковое представление моего POJO, когда я печатаю его на консоль, используя system.out.println Я не могу также преобразовать мой POJO в строку в быть посланным через Интернет, скорее это дает мне следующее ниже, я думаю, это адрес в памяти, но я хочу строковое представление

com.innovectives.octopus.gt.bank.agency.common.dto.FacValidityRequest@2d9b42e2

FacValidityRequest commonGTRequest = new FacValidityRequest();

commonGTRequest.setFACCode("1095780292");
commonGTRequest.setMobileNumber("08036952110");
commonGTRequest.setUniqueId(OctopusHelper.randomUUIDString()); 
commonGTRequest.setHash("hashing");
JAXBContext context = JAXBContext.newInstance(FacValidityRequest.class);
System.out.println("data = "+ ConvertXmlToString(commonGTRequest, context));

exchange.getIn(FacValidityRequest.class);
exchange.getIn().setBody(commonGTRequest);
LOG.info("end convertFacValidationRequest...\n" + exchange.getIn().getBody(String.class));

ЗАПРОС ОБРАЗЦА

<soapenv:Envelope 
 xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
 xmlns:tem="http://tempuri.org/">
<soap:Header/>
<soap:Body>
  <tem:FACValidityRequest>
     <!--Optional:-->
     <tem:facreq>
        <!--Optional:-->
        <tem:FACCode>?</tem:FACCode>
        <!--Optional:-->
        <tem:MobileNumber>?</tem:MobileNumber>
        <!--Optional:-->
        <tem:UniqueId>?</tem:UniqueId>
        <!--Optional:-->
        <tem:Hash>?</tem:Hash>
     </tem:facreq>
  </tem:FACValidityRequest>
  </soap:Body>
 </soap:Envelope>

Как мне этого добиться, сгенерированным POJO выше.

1 Ответ

0 голосов
/ 02 ноября 2018

То, что вы получаете, является выводом реализации Java Object.toString() по умолчанию, и это правильно - ваш класс не переопределяет toString().

Итак, либо проверьте документацию Axis2 / SoapUI о том, есть ли способ сгенерировать метод toString(), либо (если нет)

зависит от того, как вы хотите видеть свой объект Строковое представление вы можете:

  1. переопределить toString() после создания класса
  2. создайте утилиту для преобразования вашего объекта в строку
    • Простейшим способом является использование Apache BeanUtils.describe(Object obj) method
    • но если вы хотите видеть фактический XML как строку, вам нужно использовать один из serialize методов, сгенерированных для вас Axis2.

что-то вроде:

 // use ByteArrayOutputStream as example
 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    XMLStreamWriter xmlWriter = XMLStreamWriterFactory.create(outStream);

    // fake line !!! check Axis2 documentation what you need to pass as Parent QName to Serialize an object 
    javax.xml.namespace.QName parentQName = new javax.xml.namespace.QName("http://tempuri.org/","FacValidityRequest", "ns1");

    // This is a main point to get a XML String out of POJO 
    myFacValidityRequestObject.serialize(parentQName , xmlWriter);

    System.out.println(new String(outStream.toByteArray()));

    xmlWriter.close();

Вам просто нужно выяснить, какой фактический параметр Parent QName должен быть там (в моем примере это просто фальшивка)

...