JAX-WS with user-defined types - web-services

I am trying to learn about JAX-WS, in particular how to use a complex type. In all three books on Java EE that I have access to, they mention that it is possible, but do not give any example... Strangely, neither search on the web finds one that is complete - including both service and client, but maybe I just cannot locate it.
Here is the service class:
package userobj;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
#WebService(serviceName = "UserObj")
public class UserObj
{
#WebMethod(operationName = "sum")
public int sum(#WebParam(name = "obj") Two obj)
{
return obj.getA() + obj.getB();
}
}
and the class for the corresponding complex type Two:
package userobj;
public class Two
{
private int a, b;
public int getA() { return a; }
public void setA(int newA) { a = newA; }
public int getB() { return b; }
public void setB(int newB) { b = newB; }
}
When I try to use this in a client webservice application, Glassfish4.1 automatically generates all the classes from the WSDL, but the generated
class Two looks like this:
package uowsapp;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for two complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="two">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "two")
public class Two {
}
If I manually insert the content of the original class Two to this one, then the application works as expected: UserObjWSApp, but this is probably not intended use case... because Clean&Build on this project regenerates the Two.java and breaks the project. Is there some way I can make sure that Netbeans8.0.2 will generate a proper complex type from the WSDL that it generated itself?
As suggested by maress in his answer, the Two class should follow the requirements of JAXB, however, modifying it like this:
package userobj;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="Two")
public class Two
{
#XmlElement
private int a;
#XmlElement
private int b;
public int getA() { return a; }
public void setA(int newA) { a = newA; }
public int getB() { return b; }
public void setB(int newB) { b = newB; }
}
results in the following exception during the app with service on deploy, and the deploy fails:
com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
Class has two properties of the same name "a"
this problem is related to the following location:
at public int userobj.Two.getA()
at userobj.Two
at public userobj.Two userobj.jaxws.Sum.obj
at userobj.jaxws.Sum
this problem is related to the following location:
at private int userobj.Two.a
at userobj.Two
at public userobj.Two userobj.jaxws.Sum.obj
at userobj.jaxws.Sum
and the same for the b property. Then, commenting-out all the getters and setters and making the members public so that they can be accessed directly results in the same behavior as before - the generated class Two has no members. And the same happens when I move the #XmlElement annotation in front of the getA() and getB() methods: deploy ok, WSDL contains a, b, but generated Two does not. Any ideas what else could one try, please?

jax-ws uses jaxb under the hood to generate the schema.
Hence, your classes must be jaxb compliant for them to generate a valid complextype.
For your two, it is very simple:
#XmlRootElement(name="Two")
public class Two {
#XmlElement
private int a;
#XmlElement
private int b;
public int getA() {return a;}
public void setA(int a) {this.a = a;}
public int getB() {return b;}
public void setB(int b) {this.b = b}
}

Following your modification, the problem you're now facing is related to the #XmlAccessorType annotation (or lack thereof) on your data types. The annotation determines how JAXB is going to access, and therefore be able to map the fields on your defined type. The annotation provides four options, defined by the #XmlAccessType annotation : FIELD, NONE, PROPERTY and PUBLIC_MEMBER.
The default is PUBLIC_MEMBER and what this means to JAXB is : map all non static, non transient fields and all javabean-standard property types (i.e. getXXX and setXXX pairs). Because you have both int a; and getA(), it amounts to having 2 fields of the same name - a.
What you now need to do is define an XmlAccessorType to clear up the confusion:
#XmlAccessorType(XmlAccessType.PROPERTY)
#XmlRootElement(name="Two")
public class Two {
//
}
I've chosen PROPERTY here because it's more in line with the Javabeans convention, but it also confers other advantages, as outlined in Blaise Doughan's blog post(granted these do not really apply to your use case)

The code was correct, the annotation #XMLRootElement was not required, neither the #XmlElement one.
The only reason why the NetBeans did not generate the proper class Two with the fields and accessors was that it was using an old copy of WSDL. I did not realize that Clean&Build - even though it deletes the old generated source code and regenerates it anew - does not download a current version of WSDL. It always used an old version of WSDL from my very first try, where the fields a and b were not included. To re-download the WSDL, open the project in Project Browser - open "Web Service References" item and right-click the specific web service reference (in this case UserObj) and say Refresh... and tick the "also WSDL..." checkbox in the upcoming dialog
With refreshing the WSDL, both the original version without JAXB annotations and the version with JAXB annotations worked well, and generated a complete class Two:
package uowsapp;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for two complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="two">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="a" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="b" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "two", propOrder = {
"a",
"b"
})
public class Two {
protected int a;
protected int b;
/**
* Gets the value of the a property.
*
*/
public int getA() {
return a;
}
/**
* Sets the value of the a property.
*
*/
public void setA(int value) {
this.a = value;
}
/**
* Gets the value of the b property.
*
*/
public int getB() {
return b;
}
/**
* Sets the value of the b property.
*
*/
public void setB(int value) {
this.b = value;
}
}

Related

How to mock config file for unit test

I have a class in which there is a parameter less constructor. But when this constructor is called, there are five properties of the class that gets values from config file in the constructor. There are two method in the class which uses the parameters that get initialized in the constructor.
I want to write unit test for two methods using mock framework. But, I am not sure of how to initialize the parameters in the constructor as calling the method will not provide the value to those properties.
public class ABC
{
public ABC()
{
a = ConfigurationManager.AppSetting["GetValue"];
b = ConfigurationManager.AppSetting["GetValue1"];
}
public int Method1(IDictionary<string, string> dict)
{
d = a + b /2; (how to mock values of a and b while writing unit tests
using mock framework. In reality, a in my case is
dictionary)
//some business logic
return d;
}
}
Thanking in advance,
You cannot Mock values of a and b as your code is tightly coupled with app.config file. You can create an interface. Refactor code like below to inject an interface to you constructor and then mock it,
public class ABC
{
private int a;
private int b;
public ABC(IConfig config)
{
a = config.a;
b = config.b;
}
public int Method1(IDictionary<string, string> dict)
{
int d = a + b / 2;
return d;
}
}
public interface IConfig
{
int a { get; }
int b { get; }
}
public class Config : IConfig
{
public int a => Convert.ToInt32(ConfigurationManager.AppSettings["GetValue"]);
public int b => Convert.ToInt32(ConfigurationManager.AppSettings["GetValue1"]);
}
And in you test class Mock and inject IConfig like below,
Mock<IConfig> _mockConfig = new Mock<IConfig>();
_mockConfig.Setup(m => m.a).Returns(1);
_mockConfig.Setup(m => m.b).Returns(2);
ABC abc = new ABC(_mockConfig.Object);
Now your code is decoupled with app.config and you will get mock values of a and b while running unit test.

Why doesn't dynamic partial mocking work for JMockit's #Injectable?

In the following test case where no Expectations have been recorded, I would expect that the dynamic partial mocking feature will be used for the fields A and B which are initialized in UnitToTest using #Injectable. But instead always the method calls are mocked. Only using an invalid filter value for static partial mocking, it is possible to call the real methods:
#Service
class A {
public String doSomething() { return "doSomething"; }
public String doSomethingElse() { return "doSomethingElse"; }
}
#Service
class B {
public String doSomething() { return "doSomething"; }
public String doSomethingElse() { return "doSomethingElse"; }
}
#Service
class UnitToTest {
#Autowired B b;
#Autowired A a;
public B getB() { return b; }
public A getA() { return a; }
}
public class TestClass {
#Tested UnitToTest unit;
// #Mocked({ "someInvalidFilter()" })
#Injectable A a;
// #Mocked({ "someInvalidFilter()" })
#Injectable B b;
#Test
public void test() {
// actual return value is always null if no invalid static partial
// mocking filters are specified above
assertEquals("doSomething", unit.getA().doSomething());
assertEquals("doSomethingElse", unit.getA().doSomethingElse());
assertEquals("doSomething", unit.getB().doSomething());
assertEquals("doSomethingElse", unit.getB().doSomethingElse());
}
}
For me it looks like dynamic partial mocking with JMockit doesn't work for #Injectables. Is that a known restriction?
#Injectables always get injected into #Tested objects, assuming a matching field or constructor parameter can be found; the injection process even takes into consideration DI annotations such as #Inject and #Autowired.
However, an #Injectable instance is always created as an uninitialized (ie, with no state) and fully mocked instance. Partial mocking, on the other hand, is meant for real instances that you instantiate (and initialize) yourself in the test.
So, what you seem to be asking for is that said real instances (partially mocked or not) could be injected into #Tested objects. Indeed, this is not supported (except by calling Deencapsulation.setField), since a motivating use case was never presented by users.
That said, the example test will pass if it is changed to the following:
public class TestClass {
#Tested(fullyInitialized = true) UnitToTest unit;
#Test
public void test() {
assertEquals("doSomething", unit.getA().doSomething());
assertEquals("doSomethingElse", unit.getA().doSomethingElse());
assertEquals("doSomething", unit.getB().doSomething());
assertEquals("doSomethingElse", unit.getB().doSomethingElse());
}
}
The above is an integration test, though, not a unit test.

How to avoid the fat/polluted interface in this scenario of C++ design - OOPS?

We are writing a generic middleware for the gadget- DTV. We have a module called ContentMgr, which is a base class. Now, for the different customer needs, we have the VideoconContentMgr ( for instance)- which is derived from ContentMgr.
class ContentMgr
{
public:
virtual void setContent()
{
cout<<"Unused function";
}
};
class VideoconContentMgr: public ContentMgr
{
virtual void setContent()
{
cout<<"Do some useful computation;
}
};
client code - based on the product type - the
/** if the product is generic **/
ContentMgr *product = new ContentMgr();
/** If the product is videocon **/
ContentMgr *product = new VideoconContentMgr();
My question is according to the Interface Segregation Principle - One should avoid fat/polluted interfaces. How can I avoid the polluted method - setContent() here. For the generic product,setContent() is not useful. However, for the videocon product it is useful. How can I avoid the fat/polluted method setContent()?
For the generic product, setContent() is not useful. However, for the videocon product it is useful.
One solution is to keep the member function where it is useful - put it into VideoconContentMgr only, and use it in the context specific to the VideoconContentMgr subtype:
/** if the product is generic **/ ContentMgr *product = new ContentMgr();
/** If the product is videocon **/ {
VideoconContentMgr *vcm = new VideoconContentMgr();
vcm->setContent();
ContentMgr *product = vcm;
}
If the usefulness of the member function specific to a subclass extends past the initialization time, use a visitor-like approach. Subclass-specific code remains bound to subclasses, but now you add a visitor that does nothing for a generic class, and calls setContent() on VideoconContentMgr class:
struct ContentMgrVisitor {
virtual void visitGeneric(ContentMgr& m) {};
virtual void visitVideo(VideoconContentMgr& vm) {};
};
struct ContentMgr
{
virtual void accept(ContentMgrVisitor& v)
{
v.visitGeneric(this);
}
};
struct VideoconContentMgr: public ContentMgr
{
virtual void setContent()
{
cout<<"Do some useful computation;
}
virtual void accept(ContentMgrVisitor& v)
{
v.visitVideo(this);
}
};
Now a client who wants to call setContent can do it from a visitor:
class SetContentVisitor : public ContentMgrVisitor {
void visitVideo(VideoconContentMgr& vm) {
vm.setContent();
}
};
...
ContentMgr *mgr = ... // Comes from somewhere
SetContentVisitor scv;
mgr->accept(scv);

How to test two objects are equal in xunit.net?

I am reading Test Driven Development: By Example. All examples use Java and Junit (I am on chapter 10). There are one test method that test for equality of two objects. I already override Equals of the class but when run my test it failed.
This is sample code
public class BaseX
{
public string Test { get; set; }
public override bool Equals(object obj)
{
return this.Test == ((BaseX)obj).Test;
}
public override string ToString()
{
return string.Format("Tyep: {0}, Test: {1}", this.GetType().Name, this.Test);
}
}
public class A : BaseX
{
}
This is my test code
[Fact]
public void FunTest2()
{
var b1 = new BaseX();
var a1 = new A();
b1.Test = "a";
a1.Test = "a";
Assert.Equal(a1, b1);
}
When I run the test, it will failed with this message.
TDD1.UnitTest.UnitTest1.FunTest2 : Assert.Equal() Failure
Expected: Tyep: A, Test: a
Actual: Tyep: BaseX, Test: a
I think Assert.Equal compare both value and type of objects. So, I looked on xunit code and found that Assert.Equal call IEqualityComparer.Equals. If I want to compare two object with override method, what method should I use?
Update
I test this on Windows 7, Visual Studio 11 Beta, xunit.net 1.9.0.1566 (get files from nuget)
Before comparing both objects using T's Equals method, xunit compares types:
// Same type?
if (!skipTypeCheck && x.GetType() != y.GetType())
return false;
As I see it, you have two choices:
The simple choice
Assert.True(b1.Equals(a1));
It might be less expected than an Equal overload, but KISS...
The less simple choice
public class BaseXComparer : IEqualityComparer<BaseX>
{
public bool Equals(BaseX x, BaseX y)
{
return x.Test.Equals(y.Test);
}
public int GetHashCode(BaseX obj)
{
return obj.Test.GetHashCode();
}
}
And then:
Assert.Equal(a1, b1, new BaseXComparer());
In this case, consider this.
Until someone will add a new overload (shouldn't be tricky, as the inner implementation has a bool parameter for this) or an extension, I'd recommend using the simple method above.

What concurrency warnings should I expect from FindBugs?

I have the following code:
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
#ThreadSafe
public class Aoeu {
#GuardedBy("this")
private long aoeu;
public long getAoeu() {
return aoeu;
}
public void setAoeu(long aoeu) {
this.aoeu = aoeu;
}
}
From what I've read, FindBugs understands the JCiP annotations (indeed, 1.3.9 ships with them) but I don't get any warnings from the above code. According to, I expect to see:
IS: Field not guarded against concurrent access (IS_FIELD_NOT_GUARDED)
This field is annotated with net.jcip.annotations.GuardedBy, but can be accessed in a way that seems to violate the annotation.
Please check below code it shows the bug
class Test
{
#net.jcip.annotations.GuardedBy("this")
private int field;
/**
*
*/
public Test()
{
}
/**
*
*/
public void setField()
{
field++;
}
}