Using SoapUi Generated POJO - java

I used soapUi to generate a Java Pojo from a WSDL, one of the generated class looks like the following below 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
}
I tried to use the POJO and set its values as I have done below but I can not view the String representation of my POJO when I print it out to console using system.out.println I can not also convert my POJO to string to be sent across the internet, rather it gives me the following below which I guess is an address in memory but I want the string representation
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));
SAMPLE REQUEST
<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>
How do I achieve this, with the generated POJO above.

What you get is an output of default Java Object.toString() implementation and it is correct - your class does not override toString().
So, either check Axis2/SoapUI documentation about is there a way to generate toString() method or (if not)
depends on how do you want to see your object String representation you can:
override toString() after class generated
create some utility to convert your object to String
simplest way is to use Apache BeanUtils.describe(Object obj) method
but if you want see actual XML as string you need to use one of serialize methods generated for you by Axis2.
something like:
// 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();
You need just find out what actual Parent QName parameter must be there (in my example it is just a fake one)

Related

How to make a JAVADOC of my program?

This is my code:
public class Client
{
protected int cod;
protected String name;
public void setCod(int cod) throws Exception
{
if(cod==null)
throw new Exception("Invalid code!");
this.cod = cod;
}
public int getCod()
{
return this.cod;
}
public void setName(String name) throws Exception
{
if(name==null || name.equals("")
throw new Exception("Invalid name!");
this.name = name;
}
public String getName()
{
return this.name;
}
public Client(int cod, String name) throws Exception
{
this.setCod(cod);
this.setName(name);
}
public boolean equals(Object obj)
{
if(this==obj)
return true;
if(obj==null)
return false;
if(!(obj instanceof Client))
return false;
Client client = (Client)obj;
if(this.cod!=client.cod)
return false;
if(this.name!=client.name)
return false;
return true;
}
public String toString()
{
return "Code: " + this.cod + "\n" +
"Name: " + this.name;
}
public int hashCode()
{
int ret = 444;
ret += ret*7 + new Integer (this.cod).hashCode();
ret += ret*7 + (this.name).hashCode();
return ret;
}
public Object clone()
{
Client ret = null;
try
{
ret = new Client(this);
}
catch(Exception error)
{
// this is never null
}
return ret;
}
public Client(Client model) throws Exception
{
if(model==null)
throw new Exception("Inexistent model!");
this.cod = model.cod;
this.name = model.name;
}
}
I know that, to make a comment, you'll have to put "//" or " /* " and " */ ". But how can I comment following the JAVADOC rule?
If you know how, can you copy my code and put it in your answer, with the JAVADOC? Thanks :)
And please tell me, what is a JAVADOC, and what is it for? Is there any simple way to make it?
Javadoc is a kind of comment that you use in your program, to organize it, to make the program more friendly and to create a page HTML with everything you commented, like this:
So, to create a javadoc, you'll have top put /** in place of /*.
There is types of commands that you need to know when you're creating the javadoc.
#author - who created the program
#throws - for exceptions
#param - the method parameters
#return - what the method returns
So, your code with javadoc will be like this:
/**
* #author IncredibleCoding
*/
public class Client
{
protected int cod;
protected String name;
/**
* instance the code passed
*/
public void setCod(int cod) throws Exception
{
if(cod==null)
throw new Exception("Invalid code!");
this.cod = cod;
}
/**
* #returns the code
*/
public int getCod()
{
return this.cod;
}
/**
* instance the name passed
* #param name, that is the name passed
* #throws Exception, if the name is in invalid format
*/
public void setName(String name) throws Exception
{
if(name==null || name.equals("")
throw new Exception("Invalid name!");
this.name = name;
}
/**
* #returns the name
*/
public String getName()
{
return this.name;
}
/**
* the constructor
* #param cod, that is the code passed
* #param name, that is the name passed
*/
public Client(int cod, String name) throws Exception
{
this.setCod(cod);
this.setName(name);
}
/**
* #param obj, that is the object that will be compared
* #returns true if the object is equal to this, false if the object isn't equal
*/
public boolean equals(Object obj)
{
if(this==obj)
return true;
if(obj==null)
return false;
if(!(obj instanceof Client))
return false;
Client client = (Client)obj;
if(this.cod!=client.cod)
return false;
if(this.name!=client.name)
return false;
return true;
}
/**
* returns the formatted variable like String
*/
public String toString()
{
return "Code: " + this.cod + "\n" +
"Name: " + this.name;
}
/**
* returns the hashCode of a variable
*/
public int hashCode()
{
int ret = 444;
ret += ret*7 + new Integer (this.cod).hashCode();
ret += ret*7 + (this.name).hashCode();
return ret;
}
/**
* clone the object
*/
public Object clone()
{
Client ret = null;
try
{
ret = new Client(this);
}
catch(Exception error)
{
// this is never null
}
return ret;
}
/**
* "copy" the variables
* #param model, that is the object that will be copied
* #throws Exception, if the model is inexistent
*/
public Client(Client model) throws Exception
{
if(model==null)
throw new Exception("Inexistent model!");
this.cod = model.cod;
this.name = model.name;
}
}
You should consider take a look in this ORACLE's page, this will help you too:
https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html

Mapping string into db to java class

I have an entity class (account), with a column called permission, to manage the access on my website. It's mapped as string in my db, like the follow:
#Column(length = 300)
private String permissions;
In truth, this field contains a json string, for example like:
{"permissionOne" : true, "permissionTwo" : false}
The field is not mapped as JSON, because my db is MySql with an older version, which doesn't support JSON type, and I cannot change the version.
I have also a JsonHelper class:
public class JsonHelper {
/** Singleton parser instance */
private static ObjectMapper parser = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(Feature.ALLOW_UNQUOTED_FIELD_NAMES, Feature.ALLOW_UNQUOTED_CONTROL_CHARS);
/** Logger instance */
private static Logger LOG = LoggerFactory.getLogger(JsonHelper.class);
/**
* converts one java object into json {#link String}g
*
* #param toConvert
* #return converted {#link String} object
*/
public static String toJsonString(Object toConvert) {
String result = null;
try {
result = parser.writeValueAsString(toConvert);
}
catch (JsonProcessingException e) {
LOG.error("Cannot parse value : " + toConvert + " StackTrace : ", e);
}
return result;
}
/**
* Converts one json {#link String} into java object
*
* #param toConvert json string to convert
* #param convertType class type to be converted into
* #return converted java object
*/
public static <T> T fromJsonString(String toConvert, Class<T> convertType) {
if (toConvert == null) return null;
T result = null;
try {
result = parser.readValue(toConvert, convertType);
}
catch (IOException e) {
LOG.error("Cannot parse value : " + convertType + " " + toConvert + " StackTrace : ", e);
}
return result;
}
/**
* Converts one java object to {#link JsonNode}
*
* #param toConvert object to convert
* #return converted json object
*/
public static JsonNode toJsonNode(Object toConvert) {
return parser.valueToTree(toConvert);
}
/**
* Converts one {#link JsonNode} into java object
*
* #param toConvert to be converted
* #param convertType type of class to convert to
* #return converted java object
*/
public static <T> T fromJsonNode(JsonNode toConvert, Class<T> convertType) {
T result = null;
try {
result = parser.treeToValue(toConvert, convertType);
}
catch (JsonProcessingException e) {
LOG.error("Cannot parse value : " + convertType + " " + toConvert +
" StackTrace : ", e);
}
return result;
}
/**
* Converts one json into list of objects
*
* #param toConvert json to convert
* #param convertType list type
* #return converted liist with objects
*/
public static <T> List<T> fromJsonNodeList(JsonNode toConvert, Class<T>
convertType) {
List<T> result = new ArrayList<>();
if (!toConvert.isArray()) return result;
for (JsonNode node : toConvert) {
result.add(fromJsonNode(node, convertType));
}
return result;
}
public static ObjectMapper getParser() {
return parser;
}
}
When I do:
Permission permission = JsonHelper.fromJsonString(account.getPermissions(), Permission.class);
permission variable is null.
I don't know why. It seems all good.
Am I missing something?
Can I do it in a different way?
thanks!
Judging from what I see in this piece of code:
public static <T> T fromJsonString(String toConvert, Class<T> convertType) {
if (toConvert == null) return null;
T result = null;
try {
result = parser.readValue(toConvert, convertType);
}
catch (IOException e) {
LOG.error("Cannot parse value : " + convertType + " " + toConvert + " StackTrace : ", e);
}
return result;
}
this method can only return null in case toConvert is null or the parser cannot read the value.
In case toConvert is null is an acceptable option (assuming the permissions field is really optional). You should perhaps log a warning that the toConvert parameter is null. Apart from that you could use Java 8's Optional as a return value here.
In the other case there is probably some garbage (non readable JSON) in your database and this will require some cleanup action apart from logging. You should try to avoid to have data in your storage which will persistently cause errors.

Microsoft Cognitive Speech Service - Android

I am using Microsoft Cognitive Services - Speech Recognition on an Android application. Everything works fine when the code is in my main activity, but when I want to move the part corresponding to speech recognition to a new class, it throws an error.
Here are the code samples:
In the main activity
int m_waitSeconds = 0;
MicrophoneRecognitionClient micClient = null;
FinalResponseStatus isReceivedResponse = FinalResponseStatus.NotReceived;
Boolean speechIntent = false;
SpeechRecognitionMode speechMode = SpeechRecognitionMode.ShortPhrase;
public enum FinalResponseStatus { NotReceived, OK }
/**
* Gets the primary subscription key
*/
public String getPrimaryKey() {
return this.getString(R.string.primaryKey);
}
/**
* Gets the secondary subscription key
*/
public String getSecondaryKey() {
return this.getString(R.string.secondaryKey);
}
/**
* Gets the LUIS application identifier.
* #return The LUIS application identifier.
*/
private String getLuisAppId() {
return this.getString(R.string.luisAppID);
}
/**
* Gets the LUIS subscription identifier.
* #return The LUIS subscription identifier.
*/
private String getLuisSubscriptionID() {
return this.getString(R.string.luisSubscriptionID);
}
/**
* Gets the default locale.
* #return The default locale.
*/
private String getDefaultLocale() {
return "en-us";
}
/**
* Handles the Click event of the _startButton control.
*/
private void StartButton_Click(View v) {
this.m_waitSeconds = this.speechMode == SpeechRecognitionMode.ShortPhrase ? 20 : 200;
if (this.micClient == null) {
if (this.speechIntent) {
this.WriteLine("--- Start microphone dictation with Intent detection ----");
this.micClient = SpeechRecognitionServiceFactory.createMicrophoneClientWithIntent(
this,
this.getDefaultLocale(),
this,
this.getPrimaryKey(),
this.getSecondaryKey(),
this.getLuisAppId(),
this.getLuisSubscriptionID());
}
else
{
this.micClient = SpeechRecognitionServiceFactory.createMicrophoneClient(
this,
this.speechMode,
this.getDefaultLocale(),
this,
this.getPrimaryKey(),
this.getSecondaryKey());
}
}
this.micClient.startMicAndRecognition();
}
public void onFinalResponseReceived(final RecognitionResult response) {
boolean isFinalDicationMessage = this.speechMode == SpeechRecognitionMode.LongDictation &&
(response.RecognitionStatus == RecognitionStatus.EndOfDictation ||
response.RecognitionStatus == RecognitionStatus.DictationEndSilenceTimeout);
if (null != this.micClient && ((this.speechMode == SpeechRecognitionMode.ShortPhrase) || isFinalDicationMessage)) {
// we got the final result, so it we can end the mic reco. No need to do this
// for dataReco, since we already called endAudio() on it as soon as we were done
// sending all the data.
this.micClient.endMicAndRecognition();
}
if (isFinalDicationMessage) {
this.isReceivedResponse = FinalResponseStatus.OK;
}
Confidence cMax = Confidence.Low;
int iMax = 0;
if (!isFinalDicationMessage && response.Results.length != 0) {
for (int i = 0; i < response.Results.length; i++) {
//get the text with highest confidence:
if(response.Results[i].Confidence.getValue() > cMax.getValue()){
cMax = response.Results[i].Confidence;
iMax = i;
}
}
this.WriteLine(response.Results[iMax].DisplayText);
}
}
/**
* Called when a final response is received and its intent is parsed
*/
public void onIntentReceived(final String payload) {
this.WriteLine("--- Intent received by onIntentReceived() ---");
this.WriteLine(payload);
this.WriteLine();
}
public void onPartialResponseReceived(final String response) {
this.WriteLine("--- Partial result received by onPartialResponseReceived() ---");
this.WriteLine(response);
this.WriteLine();
}
public void onError(final int errorCode, final String response) {
this.WriteLine("--- Error received by onError() ---");
this.WriteLine("Error code: " + SpeechClientStatus.fromInt(errorCode) + " " + errorCode);
this.WriteLine("Error text: " + response);
this.WriteLine();
}
/**
* Called when the microphone status has changed.
* #param recording The current recording state
*/
public void onAudioEvent(boolean recording) {
if (!recording) {
this.micClient.endMicAndRecognition();
}
}
/**
* Writes the line.
*/
private void WriteLine() {
this.WriteLine("");
}
/**
* Writes the line.
* #param text The line to write.
*/
private void WriteLine(String text) {
System.out.println(text);
}
In a separate class
public class SpeechRecognition implements ISpeechRecognitionServerEvents
{
int m_waitSeconds = 0;
private MicrophoneRecognitionClient micClient = null;
private FinalResponseStatus isReceivedResponse =FinalResponseStatus.NotReceived;
private Boolean speechIntent = false;
private SpeechRecognitionMode speechMode=SpeechRecognitionMode.ShortPhrase;
public enum FinalResponseStatus { NotReceived, OK }
/**
* Gets the primary subscription key
*/
public String getPrimaryKey() {
return Integer.toString(R.string.primaryKey);
}
/**
* Gets the secondary subscription key
*/
public String getSecondaryKey() {
return Integer.toString(R.string.secondaryKey);
}
/**
* Gets the LUIS application identifier.
* #return The LUIS application identifier.
*/
private String getLuisAppId() {
return Integer.toString(R.string.luisAppID);
}
/**
* Gets the LUIS subscription identifier.
* #return The LUIS subscription identifier.
*/
private String getLuisSubscriptionID() {
return Integer.toString(R.string.luisSubscriptionID);
}
/**
* Gets the default locale.
* #return The default locale.
*/
private String getDefaultLocale() {
return "en-us";
}
public void startSpeechRecognition() {
this.m_waitSeconds = this.speechMode == SpeechRecognitionMode.ShortPhrase ? 20 : 200;
if (this.micClient == null) {
if (this.speechIntent) {
this.micClient = SpeechRecognitionServiceFactory.createMicrophoneClientWithIntent(
this.getDefaultLocale(),
this,
this.getPrimaryKey(),
this.getSecondaryKey(),
this.getLuisAppId(),
this.getLuisSubscriptionID());
}
else
{
this.micClient = SpeechRecognitionServiceFactory.createMicrophoneClient(
this.speechMode,
this.getDefaultLocale(),
this,
this.getPrimaryKey(),
this.getSecondaryKey());
}
}
this.micClient.startMicAndRecognition();
}
public void endSpeechRecognition(){
this.micClient.endMicAndRecognition();
}
public void onFinalResponseReceived(final RecognitionResult response) {
boolean isFinalDicationMessage = this.speechMode == SpeechRecognitionMode.LongDictation &&
(response.RecognitionStatus == RecognitionStatus.EndOfDictation ||
response.RecognitionStatus == RecognitionStatus.DictationEndSilenceTimeout);
if (null != this.micClient && ((this.speechMode == SpeechRecognitionMode.ShortPhrase) || isFinalDicationMessage)) {
// we got the final result, so it we can end the mic reco. No need to do this
// for dataReco, since we already called endAudio() on it as soon as we were done
// sending all the data.
this.micClient.endMicAndRecognition();
}
if (isFinalDicationMessage) {
this.isReceivedResponse = FinalResponseStatus.OK;
}
Confidence cMax = Confidence.Low;
int iMax = 0;
if (!isFinalDicationMessage && response.Results.length != 0) {
for (int i = 0; i < response.Results.length; i++) {
//get the text with highest confidence:
if(response.Results[i].Confidence.getValue() > cMax.getValue()){
cMax = response.Results[i].Confidence;
iMax = i;
}
}
System.out.println("Action to take: " + response.Results[iMax].DisplayText);
}
}
/**
* Called when a final response is received and its intent is parsed
*/
public void onIntentReceived(final String payload) {
System.out.println("--- Intent received by onIntentReceived() ---");
System.out.println(payload);
}
public void onPartialResponseReceived(final String response) {
System.out.println("--- Partial result received by onPartialResponseReceived() ---");
System.out.println(response);
}
public void onError(final int errorCode, final String response) {
System.err.println("--- Error received by onError() ---");
System.err.println("Error code: " + SpeechClientStatus.fromInt(errorCode) + " " + errorCode);
System.err.println("Error text: " + response);
}
/**
* Called when the microphone status has changed.
* #param recording The current recording state
*/
public void onAudioEvent(boolean recording) {
System.out.println("--- Microphone status change received by onAudioEvent() ---");
System.out.println("********* Microphone status: " + recording + " *********");
if (recording) {
System.out.println("Please start speaking.");
}
if (!recording) {
this.micClient.endMicAndRecognition();
}
}
}
You can clearly see that it is basically the same code but it gives me this error in the onError function after i call this.micClient.startMicAndRecognition();
:
Error code: LoginFailed -1910505470
I solved the problem.
I was getting a wrong Primary key in this line of code:
public String getPrimaryKey() {
return Integer.toString(R.string.primaryKey);
}
It is because the primary key is too long to be read by the processor as an integer then transformed to a String. I had to get the primary key from the main activity via getString(R.string.primaryKey) then pass it as a parameter to the constructor of the SpeechRecognition class.

Loss of types in the abstract factory

I am developing an java application that accepts SOAP message. The body of the SOAP contains various documents. From time to time their number varies (depending on the version of the album).
For their analysis I am trying to apply a pattern Abstract Factory.
But my implementation, I ran into a problem:
IAlbumFactory albumFactory = AlbumFactory.buildDocument (Album.A_5_0_12);
The first parameter has I can point to any type of enum CustomDocument (although CustomDocument.DO1 only valid Du). And this error only shows up in RunTime
IDocumentEntity <Du, org.w3c.dom.Element> documentEntity =
albumFactory.getWorker (CustomDocument.DO1);
how to avoid it?
Some class:
public interface IDocumentEntity<T,E> {
T getReport(E e) throws JAXBException ;
}
public interface IAlbumFactory {
IDocumentEntity getWorker(CustomDocument document);
}
/**
* Class for convert document DO1 (album 5.0.12) from org.w3c.dom.Element to Du
* entity type
*
* #author uas
*/
public class DO1_5_0_12 implements IDocumentEntity<Du, org.w3c.dom.Element> {
protected DO1ReportInType unmarshall(org.w3c.dom.Element e) throws JAXBException {
DO1ReportInType resultType = null;
JAXBContext result = JAXBContextHelper_DO1.getJaxbContextInstance();
Unmarshaller u = result.createUnmarshaller();
Object c = u.unmarshal(e);
if (c instanceof JAXBElement) {
JAXBElement jaxbe = (JAXBElement) c;
resultType = (DO1ReportInType) JAXBIntrospector.getValue(jaxbe);
}
return resultType;
}
#Override
public Du getReport(org.w3c.dom.Element e) throws JAXBException {
DO1ReportInType dO1Report = unmarshall(e);
DO1ReportIn_JAXBtoORCL btoORCL = new DO1ReportIn_JAXBtoORCL(dO1Report);
return btoORCL.getReport();
}
}
Factory for Album 5_0_12.
public class AlbumFactory_5_0_12 implements IAlbumFactory {
/**
* Return documentWorker byn CustomDocument value
* #param customDocument
* #return throws IllegalArgumentException
*/
#Override
public IDocumentEntity getWorker(CustomDocument customDocument) {
IDocumentEntity doc = null;
switch (customDocument) {
case DO1:
doc = new DO1_5_0_12();
break;
case DO2:
doc = new DO2_5_0_12();
break;
default:
throw new IllegalArgumentException("For album 5.0.12 " + customDocument.DocName() + " not support");
}
return doc;
}
}
public class AlbumFactory {
private AlbumFactory() {
}
public static IAlbumFactory buildDocument(Album album) {
IAlbumFactory result = null;
switch (album) {
case A_5_0_12:
result = new AlbumFactory_5_0_12();
break;
default:
throw new IllegalArgumentException("This version " + album.AlbumName() + " is not support");
}
return result;
}
}

Bean validation on class level [duplicate]

I am trying to implement a crossfield validation (JSR-303) with a custom annotation on class level. However the isValid method is not called (but the initialize method).
So my question is: Why is the isValid method not being called for this class level validator? Defining it on property level works!
I tried it on JBoss AS 7 and Websphere AS 8.
Here is the code and a JUnit test (which works)
Test.java
public class Test {
#org.junit.Test
public void test() throws ParseException {
Person person = new Person();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMDD");
person.setPartyClosingDateFrom(new Date());
person.setPartyClosingDateTo(sdf.parse("20120210"));
Set<ConstraintViolation<Person>> violations = Validation.buildDefaultValidatorFactory().getValidator().validate(person);
for(ConstraintViolation<Person> violation : violations) {
System.out.println("Message:- " + violation.getMessage());
}
}
}
DateCompare.java
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
#Target({ TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = DateCompareValidator.class)
#Documented
public #interface DateCompare {
/** First date. */
String firstDate();
/** Second date. */
String secondDate();
Class<?>[] constraints() default {};
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String message() default "totally wrong, dude!";
DateValidator.DateComparisonMode matchMode() default
DateValidator.DateComparisonMode.EQUAL;
}
DateCompareValidator.java
public class DateCompareValidator implements ConstraintValidator<DateCompare, Object> {
/** describes the mode the validator should use**/
private DateValidator.DateComparisonMode comparisonMode;
/** The first date field name. */
private String firstDateFieldName;
/** The second date field name. */
private String secondDateFieldName;
/** the message to be used **/
private String messageKey = "failure";
/**
* Initialize.
*
* This method is used to set the parameters ans is REQUIRED even if you don't use any parameters
*
* #param constraintAnnotation the constraint annotation
*/
#Override
public void initialize(final DateCompare constraintAnnotation) {
this.comparisonMode = constraintAnnotation.matchMode();
this.firstDateFieldName = constraintAnnotation.firstDate();
this.secondDateFieldName = constraintAnnotation.secondDate();
}
/**
* Checks if it is valid.
*
* #param target the target
* #param context the context
* #return true, if is valid
*/
#Override
public boolean isValid(final Object target, final ConstraintValidatorContext context) {
boolean isValid = true;
final Date valueDate1 = DateCompareValidator.getPropertyValue(Date.class, this.firstDateFieldName, target);
final Date valueDate2 = DateCompareValidator.getPropertyValue(Date.class, this.secondDateFieldName, target);
if (isValid) {
isValid = DateValidator.isValid(valueDate1, valueDate2, this.comparisonMode);
} else {
// at this point comparisonMode does not fit tp the result and we have to
// design an error Message
final ResourceBundle messageBundle = ResourceBundle.getBundle("resources.messages");
final MessageFormat message = new MessageFormat(messageBundle.getString(this.messageKey));
final Object[] messageArguments = { messageBundle.getString(this.messageKey + "." + this.comparisonMode) };
// replace the default-message with the one we just created
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message.format(messageArguments)).addConstraintViolation();
isValid = false;
}
return isValid;
}
public static <T> T getPropertyValue(final Class<T> requiredType, final String propertyName, final Object instance) {
if (requiredType == null) {
throw new IllegalArgumentException("Invalid argument. requiredType must NOT be null!");
}
if (propertyName == null) {
throw new IllegalArgumentException("Invalid argument. PropertyName must NOT be null!");
}
if (instance == null) {
throw new IllegalArgumentException("Invalid argument. Object instance must NOT be null!");
}
T returnValue = null;
try {
final PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, instance.getClass());
final Method readMethod = descriptor.getReadMethod();
if (readMethod == null) {
throw new IllegalStateException("Property '" + propertyName + "' of " + instance.getClass().getName()
+ " is NOT readable!");
}
if (requiredType.isAssignableFrom(readMethod.getReturnType())) {
try {
final Object propertyValue = readMethod.invoke(instance);
returnValue = requiredType.cast(propertyValue);
} catch (final Exception e) {
e.printStackTrace(); // unable to invoke readMethod
}
}
} catch (final IntrospectionException e) {
throw new IllegalArgumentException("Property '" + propertyName + "' is NOT defined in "
+ instance.getClass().getName() + "!", e);
}
return returnValue;
}
DateValidator.java
public class DateValidator {
/**
* The Enum DateComparisonMode.
*
* Determins which Type of validation is used
*/
public enum DateComparisonMode {
/** the given Date must be BEFORE the referenced Date */
BEFORE,
/** the given Date must be BEFORE_OR_EQUAL the referenced Date */
BEFORE_OR_EQUAL,
/** the given Date must be EQUAL the referenced Date */
EQUAL,
/** the given Date must be AFTER_OR_EQUAL the referenced Date */
AFTER_OR_EQUAL,
/** the given Date must be AFTER the referenced Date */
AFTER;
}
/**
* Compare 2 Date Values based on a given Comparison Mode.
*
* #param baseDate the base date
* #param valuationDate the valuation date
* #param comparisonMode the comparison mode
* #return true, if is valid
*/
public static boolean isValid(final Date baseDate, final Date valuationDate, final DateComparisonMode comparisonMode) {
// Timevalue of both dates will be set to 00:00:0000
final Date compValuationDate = DateValidator.convertDate(valuationDate);
final Date compBaseDate = DateValidator.convertDate(baseDate);
// compare the values
final int result = compValuationDate.compareTo(compBaseDate);
// match the result to the comparisonMode and return true
// if rule is fulfilled
switch (result) {
case -1:
if (comparisonMode == DateComparisonMode.BEFORE) {
return true;
}
if (comparisonMode == DateComparisonMode.BEFORE_OR_EQUAL) {
return true;
}
break;
case 0:
if (comparisonMode == DateComparisonMode.BEFORE_OR_EQUAL) {
return true;
}
if (comparisonMode == DateComparisonMode.EQUAL) {
return true;
}
if (comparisonMode == DateComparisonMode.AFTER_OR_EQUAL) {
return true;
}
break;
case 1:
if (comparisonMode == DateComparisonMode.AFTER) {
return true;
}
if (comparisonMode == DateComparisonMode.AFTER_OR_EQUAL) {
return true;
}
break;
default:
return false; // should not happen....
}
return false;
}
/**
* Convert date.
*
* sets the time Value of a given Date filed to 00:00:0000
*
* #param t the t
* #return the date
*/
private static Date convertDate(final Date t) {
final Calendar calendar = Calendar.getInstance();
calendar.setTime(t);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return (calendar.getTime());
}
Especially the property retrieval was taken from this post question
JSF 2.0 doesn't call class level validation constraints.
From JSF validation:
JSF 2 provides built-in integration with JSR-303 constraints. When you
are using bean validation in your application, JSF automatically uses
the constraints for beans that are referenced by UIInput values.
You have to call it manually, or you can try Seam Faces which has an extension <f:validateBean>

Categories