Java SAXException: No deserializer for - java

I'm trying to write a web service method that has a an object as one of it's parameters and that object has a property that is another object type. There seems to be no problem with passing in a object as long as all of the objects properties are primitive types. As soon as one of the properties is another object it has issues even if that embedded object is made of all primitives.
I'm using SoapUI to test it and the error I get is org.xml.sax.SAXException: No deserializer for {http://WebService}MyEmbeddedObject
I'm thinking there must be an easy way to tell it to deserialize the embedded object too but can't for the life of me figure out how. At this point I'll take the hard way too I just need a solution, I can always try to improve it later.
The method in the web service I'm writing looks like this:
public boolean MethodName(MyObject object, String sessionID) throws Exception
{
//do Stuff
}
The MyObject Class looks like this:
public class MyObject implements java.io.Serializable
{
public String Description;
public MyEmbeddedObject Thing1;
public MyEmbeddedObject Thing2;
public MyEmbeddedObject[] Things;
}
The MyEmbeddedObject Class looks like this:
public class MyEmbeddedObject implements java.io.Serializable
{
public String SubThing1;
public String SubThing2;
public String SubThing3;
}

In my case this problem had nothing to do with implementing java.io.Serializable. In fact you could remove that and it will work just fine as long as you fix the actual problem.
The actual problem being that you can't use an object as an argument unless all of it's properties are primitive types UNLESS you also use that embeded object in the method itself. It seems to be some sort of compiler voodoo if you ask me but here's the solution in code. Hopefully this makes sense. I'll even take it one level deeper just for illustration purposes.
One thing you'll notice that I've changed in the solution is that the "MyEmbeddedObject" class is much more complicated looking. This is because I didn't know how to properly define arrays in java at the time I asked this question. I assumed it was the same as C# and unfortunately for me that compounded my problem but I eventually figured it out by banging my head long enough and reviewing sample code from the vendor this project is for.
Program
public boolean MethodName(MyObject object, String sessionID)
{
//do Stuff
}
public MyEmbeddedObject unusedMyEmbeddedObject()
{
return null;
}
public MyDoubleEmbeddedObject unusedMyDoubleEmbeddedObject()
{
return null;
}
In a separate class file
public class MyObject
{
public String description;
public MyEmbeddedObject thing1;
public MyEmbeddedObject thing2;
}
In a separate class file
public class MyEmbeddedObject
{
public MyDoubleEmbeddedObject subThing1;
private MyDoubleEmbeddedObject[] subThings;
public MyDoubleEmbeddedObject[] getSubThings()
{
return this.subThings;
}
public void setSubThings(final MyDoubleEmbeddedObject[] value)
{
this.subThings = value;
}
}
In a separate class file
public class MyDoubleEmbeddedObject
{
public String subSubString1;
public String subSubString2;
public String subSubString3;
}

Related

Take string as a parameter, return an object

I'm relatively new to Java, came across this method from an assignment and got hard stuck.
Also I didn't really know how to describe this situation as a question so bear with me with the tittle.
The requirement for the method is to "Construct and return a complete Person object from text",
given example was Person.createName("John")
public class Person {
public static Person createName(String text) {
//TO-DO
}
}
As the comments pointed out this is a factory method. You create and return an object in a static method of the same class. So something like this:
public class Person {
public static Person createName(String text) {
// Depending on your contructor.
// You can further modify the person here if you need to.
return Person(text):
}
}
Also please have a look at this. w3schools is a excellent source to get started with java.

Facade pattern - return original object or modified original object

I have e.g. object like this:
Original obj = new Original();
And I use from this object e.g. method like(this object has many methods and fields):
obj.getMeYourName();
And I would like to have similar object which is almost same but some methods return something else. I want to solve it by facade.
So, at first I want to create facade and decided if I would return direct object or modified.
What is the best way?
Something like this: ?
Original obj = new Original();
OriginalFacade obj = new OriginalFacade(Original obj, boolean getDirectObject);
OriginalFacade(Original obj, boolean getDirectObject) {
if (getDirectObject) {
return obj //How to convert object into OriginalFacade type?
} else {
obj.setMeYourName("Something else");
return obj; //Howto convert object into OriginalFacade type?
}
}
So, I have 2 problems:
1, is it good solution choose original object or modified original object thru constructor with e.g. boolean getDirectObject?
2, how to easy return original object which must me mapped into OriginalFacade Object
Must I have implement all methods from original object?
Actually, the facade pattern uses a common interface that is used by clients.
For instance:
public interface Facade {
public String getMeYourName();
public void someOtherMethod();
}
public class Original implements Facade {
private String name;
Original(String name) {
this.name = name;
}
public String getMeYourName() {
return name;
}
public void someOtherMethod() {
// a lot of great code
}
}
public class Modified implements Facade {
private Facade original;
private String otherName;
Modified(Facade original, String otherName) {
this.original = original;
this.otherName = otherName;
}
public String getMeYourName() {
return otherName;
}
public void someOtherMethod() {
original.someOtherMethod();
}
}
The clients should only need to see the Facade interface, and shouldn't need to care which actual implementation they are dealing with.
Your code demonstrates you have not understood Facade at all.
In first place Facade should be used to provide a simple interface to complex algorithms.
Second, the facade pattern allows you to access its composed objects, for example:
public class OriginalFacade{
public Original original;
}
Unless you follow the Law of Demeter, this code is perfect valid.
Regardless, if Facade is used, you should not need to access those objects.
The following link explains a little bit of Facade
I recommend you buy and read this book
Facade is not the patter to be used here. It is used to make a complex interface simpler, for example, making out-of-the-box usage patterns.
In your case, why don't you just extend the Original class and overload the methods you want to behave differently?

Extending enum fields Java

I know that it isn't possible to extend enum in Java, but I am trying to find an elegant solution for the below
I am trying to model enums (or classes) which will contain http end points of various web services across regions, say I have service A and B, each will have 4 region specific end points in US, EU, JP or CN. (This is basically for some seperate debug code that I am writing, in production the end points will be picked from configuration)
I was hoping to do something like this (not compliant java code).
public enum IEndPoint {
NA_END_POINT,
EU_END_POINT,
JP_END_POINT,
CN_END_POINT,
}
public enum ServiceAEndPoint extends IEndPoint {
NA_END_POINT("http://A.com/");
EU_END_POINT("http://A-eu.com/");
JP_END_POINT("http://A-jp.com/");
CN_END_POINT("http://A-cn.com/");
}
I could do this using interfaces where I have a method for each region, but in my opinion the enum way is more expressive, is there any better way I could model this ? What I am looking for is if there is any better way to model the inheritence relation and also having the expressive power of enumerations.
ServiceAEndPoint.NA_END_POINT
vs
serviceAEndPoint.getNAEndPoint()
I'm assuming that you will also want a ServiceBEndPoint enum (and similar). In which case I don't think your model really makes that much sense.
IEndPoint is really an enumeration of the kind of environments/regions where a service might be running. It is not an enumeration of the services themselves. Each individual service (A, B or whatever) will have different addresses for each of the regions.
Therefore I would stick with just the IEndPoint enum, and then in some service-specific code have a lookup map that will give you the address for a given end-point. Something like this:
public enum IEndPoint {
NA_END_POINT,
EU_END_POINT,
JP_END_POINT,
CN_END_POINT,
}
public class ServiceABroker {
private static final Map<IEndPoint, String> addressesByEndPoint;
static {
addressesByEndPoint = new EnumMap<>();
addressesByEndPoint.put(NA_END_POINT, "http://A.com/");
addressesByEndPoint.put(EU_END_POINT, "http://A-eu.com/");
addressesByEndPoint.put(JP_END_POINT, "http://A-jp.com/");
addressesByEndPoint.put(CN_END_POINT, "http://A-cn.com/");
}
public String getAddressForEndPoint(IEndPoint ep) {
return addressesByEndPoint.get(ep);
}
}
If these are static final constants, then just put them in an interface. Name the interface something like IServiceAEndPointKeys, where the keys part is a convention.
Here's where I consider enums to be more appropriate and useful:
Example 1: File type. An enum containing jpg, pdf etc.
Example 2: Column definitions. If I have a table with 3 columns, I would write an enum declaring ID, Name, Description (for example), each one having parameters like column header name, column width and column ID.
Im not sure I understand you question, but you can add methods to an enum for example you could do something like the following:
public enum ServiceAEndPoint{
NA_END_POINT("http://A.com/");
EU_END_POINT("http://A-eu.com/");
JP_END_POINT("http://A-jp.com/");
CN_END_POINT("http://A-cn.com/");
private final String url;
private EndPoint(String url){
this.url=url;
}
public String getURL(){
return url;
}
}
Enums cannot be extended in such a manner, mostly because enums cannot be sub-classed or the constraints they must adhere to will not be possible to impose.
Instead leverage interfaces, like so
public interface IEndPoint;
public enum DefaultEndPoints implements IEndPoint {
NA_END_POINT,
EU_END_POINT,
JP_END_POINT,
CN_END_POINT,
}
public enum DefaultServiceEndPoints implements IEndPoint {
NA_END_POINT("http://A.com/");
EU_END_POINT("http://A-eu.com/");
JP_END_POINT("http://A-jp.com/");
CN_END_POINT("http://A-cn.com/");
}
public void doSomething(IEndPoint endpoint) {
...
}
The reason why one can't subclass in the manner you wish is related to the contract that enums will be both equal via .equals(object) and via ==. If you could subclass, would this make sense?
if ( (DefaultEndPoints)JP_END_POINT == (DefaultServiceEndPoints)JP_END_POINT) {
}
if you say "yes" then I would expect to be able to do this
DefaultEndPoint someEndpoint = DefaultServiceEndPoints.JP_END_POINT;
which would leave a door open for error, as there is no guarantee that a enum entry in one enum declaration is in the other enum declaration.
Could it be different? Perhaps, but it isn't, and changing it would definately introduce a lot of complications that would have to be thoroughly thought out (or it would open avenues to work around Java's strong static-type checking).
You may want to consider something like this:
public abstract class EndpointFactory {
public abstract String getNAEndPoint();
public abstract String getEUEndPoint();
}
public class ServiceAEndpointFactory extends EndpointFactory {
public static final String NA_END_POINT = "http://A.com/";
public static final String EU_END_POINT = "http://A-eu.com/";
public String getNAEndPoint() {
return ServiceAEndpointFactory.NA_END_POINT;
}
public String getEUEndPoint() {
return ServiceAEndpointFactory.EU_END_POINT;
}
}
public class ServiceBEndpointFactory extends EndpointFactory {
public static final String NA_END_POINT = "http://B.com/";
public static final String EU_END_POINT = "http://B-eu.com/";
public String getNAEndPoint() {
return ServiceAEndpointFactory.NA_END_POINT;
}
public String getEUEndPoint() {
return ServiceAEndpointFactory.EU_END_POINT;
}
}
Then you can refer to your strings directly like this:
ServiceAEndpointFactory.NA_END_POINT;
Or, you can use the base object if the type of service is not known until execution:
EndpointFactory ef1 = new ServiceAEndpointFactory();
String ep = ef1.getNAEndPoint();
The drawback of this is the redefinition of the get*Endpoint() functions in each sub-class. You could eliminate that by moving the static final variables to be not static in the base class and putting the getter/setter in the base class only one time. However, the drawback of that is you are not able to reference the values without instantiating an object (which essentially emulates what I find valuable with ENUMs).
How does a pattern like this appeal to you? I let the enum implement an interface and implement the interface in a Debug set and a Release set. The release set can then derive the property name from the enum name - which is neat.
public interface HasURL {
public String getURL();
}
public enum DebugEndPoints implements HasURL {
NA,
EU,
JP,
CN;
#Override
public String getURL() {
// Force debug to go to the same one always.
return "http://Debug.com/";
}
}
public enum NormalEndPoints implements HasURL {
NA,
EU,
JP,
CN;
final String url;
NormalEndPoints () {
// Grab the configured property connected to my name.
this.url = getProperty(this.name());
}
#Override
public String getURL() {
return url;
}
}

How can we add transient to existing class using reflection in java?

Is there any way to make field static or transient using java reflection API.
EDIT: I have some Beans that are already being serialised using soap api and is being used by some clients, for some clients i don't want to expose one or two fields.
Sure there are so many ways to do it without changing or adding transient keyword.
Just want to know if it can be done, and if so, how ?
EDIT: I wouldn't call it an API or framework issue, more like a design flaw...
I'm using apache axis2 for soap
No. Such a thing would require modifying the byte code of the class. A particular difficulty in the case of static fields is that they are accessed using different bytecodes than object fields.
I don't see a why a field couldn't be made transient in runtime, at least in theory, but the current reflection API doesn't allow it. See also: Can a field's transient property/flag be set through reflection in java?
You can't do it with the reflection api. I think there are some byte-code manipulation tools but in this case you can use the Decorator pattern. It solves the problem but I think it is extremely ugly:
(I omited the usual boilerplate from here such as interfaces)
public class StaticDecorator {
private static Object staticField;
private Object yourObject;
public StaticDecorator(Object yourObject) {
this.yourObject = yourObject;
}
public static Object getStaticField() {
return staticField;
}
public static void setStaticField(Object object) {
staticField = object;
}
}
I used Object for the type of the class you are going to wrap but of course you can substitute any type you want. Using an approach like this you can "decorate" any class with a static field.
If you are really, extremely must want a static field in an object at run time this can help you but I think that there is a design flaw lurking somewhere.
You can wrap your bean inside another bean that only exposes the fields that you'd like to expose through your API. For example, with an internal bean with the fields foo, bar, and baz, where you do not want to expose baz.
Lombok Delegation can make this incredibly simple, but here's an example using plain-old-Java.
public class ExposedBean {
private InternalBean internalBean;
public ExposedBean(InternalBean internalBean) {
this.internalBean = internalBean;
}
public String getFoo() { return internalBean.getFoo(); }
public String getBar() { return internalBean.getBar(); }
}
public class InternalBean {
private String foo;
private String bar;
private String baz;
public String getFoo() { return foo; }
public String getBar() { return bar; }
public String getBaz() { return baz; }
}
Original answer, regarding setting modifiers
You can not set modifiers. You can check them, however.
Field myField = /* get a field object */;
if (Modifier.isTransient(myField.getModifiers()) {
System.out.println("myField is transient.");
}
if (Modifier.isFinal(MyClass.class.getModifiers()) {
System.out.println("MyClass is final.");
}
With more information about the problem you're trying to solve, we can suggest alternatives. Member#getModifiers() is not declared final, so you could possibly use a decorator. (The below code is 100% untested.)
public class FieldModifierDecorator extends Field {
protected Field field;
private int modifiers = -1;
public static void decorate(Field field) {
FieldModifierDecorator newInstance = new FieldModifierDecorator();
newInstance.field = field;
return newInstance;
}
public void overrideModifiers(int modifiers) {
this.modifiers = modifiers;
}
public int getModifiers() {
if (-1 == modifiers) {
return field.getModifiers();
}
return modifiers;
}
}
// Example usage
public Field makeFieldAppearTransient(Field field) {
FieldModifierDecorator decoratedField = FieldModifierDecorator.decorate(field);
decoratedField.overrideModifiers(field.getModifiers() | Modifier.TRANSIENT);
// if (Modifier.isTransient(decoratedField.getModifiers())) {
// System.out.println("It looks transient, but really isn't.");
//}
return decoratedField;
}
Modfifying class information or byte code modification is definitely the wrong tool for the job. You are trying to solve a business problem with solely technical tools.
It sounds more like you need a permission concept. Users may have permission to see some fields. Based on that you could use java bean introspection to clear the values of those fields just before they are sent to the client.
However this might have its problems as well. A client should be able to determine if it has permission to see that field or not.

Design patterns for converting objects with nested lists

I have a service where the flow is basically the following:
Receive an input object. This is just a POJO object and I don't have much say in the design of it.
Convert to a normalized object for my service.
Perform some business logic on the normalized object, and gather some extra data about it.
Convert to an output object for another service that the data gets passed to. (Another POJO.)
Pass the converted data to another service.
What this means, though, is that a good portion of my service is converting from type InputFoo to type NormalizedFoo to type OutputFoo.
This would be a pretty easy task. I'm using the Google Collections library and can have a class like this:
public class InputFooToNormalizedFooConverter implements Function<InputFoo, NormalizedFoo> {
public NormalizedFoo apply(InputFoo input) {
NormalizedFoo output = new NormalizedFoo();
output.setProperty(input.getProperty());
}
}
and another class like this:
public class NormalizedFooFooToOutputFooConverter implements Function<NormalizedFoo, OutputFoo> {
public NormalizedFoo apply(InputFoo input) {
NormalizedFoo output = new NormalizedFoo();
output.setProperty(input.getProperty());
}
}
But each type of Foo essentially has a hierarchy like so:
public class Foo {
List<Bar> barItems;
// .. other properties
}
public class Bar {
List<Baz> bazItems;
List<Quux> quuxItems;
// .. other properties
}
public class Baz {
// .. other properties
}
public class Quux {
// .. other properties
}
This means that I have NormalizedFooToOutputFooConverter that has a NormalizedBarToOutputBarConverter implements Function<NormalizedBar, OutputBar> type and so on and so forth.
Even worse, the input doesn't quite match up exactly to the normalized model. It's more like
public class InputFoo {
public List<InputBar> bars;
public List<InputBaz> bazs;
public List<InputQuux> quuxs;
// .. other properties
}
public class InputBar {
private String barId;
// .. other properties
}
public class InputBaz {
private String barId;
private String bazId;
// .. other properties
}
public class InputQuux {
private String barId;
private String quuxId;
// .. other properties
}
In these models, I can figure out which Baz and Quux belongs to which Bar based on the barId that each one has.
At this point, I have about 20 different converters for going from Input to Normalized and Normalized to Output. And worse still, some of them have name like ReallyLongInputTypeToReallyLongNormalizedTypeConverter creating extremely long class names. I feel like I'm doing something wrong here, with all the converters. Is there a better way to organize my converters?

Categories

Resources