Should I split up my XStream converter per class? - java

I am working on a program that uses XStream to write out to XML. As it stands I have only one class that implements Converter. This single converter takes in my ENTIRE configuration which is a HashMap at its root and the value of each key is an new instance of VMwareServer class which in turn has a HashMap where the value of key is a new instance of VMwareVirtualMachine class. Each of the respective classes have methods for setting and getting things like IP address and port number.
What I am wondering is if this is proper way to implement the XStream converter, or should I create a separate converter to convert each class to XML on it own?
I can show some code if there is still questions about what I mean.

This is somewhat debatable, but I would argue for having a separate converter for each class. This has several benefits: if you later need to return a subset of your complete view, you will be able to easily decompose the structure along class-based lines (perhaps, for example, to limit information by permissions). If you need to return slightly different representations in different contexts, you can do so on a class-by-class basis rather than duplicating all of the presentational logic in your monolithic class.

Related

Is decorator pattern suitable here

So I have a couple of classes, A, B, C, ... N. And a couple of possible properties, setP(), setQ(), setR(), ... setZ(). Now, each class can have a different combination of properties:
A B C N
- setX - setR - setP - setY
- setY - setZ - setQ - setZ
- setZ - setR
- setS
- setZ
all of the setters return an instance of the object itself so that chaining is possible.
im trying to find an elegant way to solve this problem. i dont want to redefine the tens of properties in each class (code duplication) and i dont wanna use inheritance since the there will be ugly, pointless intermediate classes (BaseABCD -> setZ) and cuz the base class setter will return an instance of type BaseABCD which will not allow full chaining of all properties.
here are some possible things im trying to look into:
somehow define each property as a decorator in an elegant fashion, and compose A something like Base.decorators().addX().addY().addZ().finalize().
define all possible properties in Base and hide non-required properties in derived classes. I dont think this is possible.
Is any of these things possible? or is there a better idea to solve a problem like this one?
More details
The classes are basically different message types used by the application to communicate with an external system. Different messages contain different fields of different types. For instance:
ECHO message:
- Timestamp (DateTime)
- SourceAddress (String)
CHECK RESOURCE message:
- Timestamp (DateTime)
- Resource Identifier (Integer)
MANIPULATE RESOURCE
- Resource Identifier (Integer)
- Operation Type (Enum)
The messages are serialized as a string when transmitted and type information is not retained. So I chose to go with a HashMap<String, String>. Each property corresponds to a key within that class's hashmap. When serializing, I just iterate over all key/value entries in that class's hashmap and produce a string message representation to be sent.
However, I want to enforce types towards the caller code. So I dont want to expose a method like A.set('RESOURCEIDENTIFIER', '123456'). Instead I want to expose methods like A.setResourceIdentifier(123456) and C.setOperation(OperationType.DELETE).
Internally, these setter functions are simply putting a relevant key in the hashmap and assigning a string value to it.
public A setOperation(OperationType operation) {
this.hashmap.put('OPERATION', operation.name());
return this;
}
There are about 40 unique field types and all messages employ a unique subset of these fields. Like A and B contain setTimestamp(). B and C contain setResourceIdentifier(). Only C contains setOperationType(). And so on.
I don't want to redefine these tens of properties in each class over and over again. That's why I want to explore the following two options:
Option 1
Define a Base class with ALL possible properties and in derived A class, override only the required properties to be public. This is do-able. But I want to see if it is possible to implement something like described in option #2.
Option 2
Somehow define decorators and a factory class such that
public ? getA() {
return Base.startDecorating()
.addTimestamp()
.addResourceIdentifier()
.finalize();
}
? objA = Factory.getA()
.setTimestamp(DateTime.now())
.setResourceIdentifier(123456);
Can this be possible? While writing out this question, I realized that Option 1 should be the way to go. It's simple and less error prone. But just out of curiosity I want to know if decorator pattern can be used here. After all, what I have here is a complete set of independent modules (properties) and different ways of assembling them together (the classes).
A decorator is made for something that you can keep adding to. Like a xmas tree. But once the xmas tree is decorated, then you use common methods like turnOn(). Its not made for adding new methods to an existing API. I think you can use regular old inheritance for this. I would also use examples like List. Your Base class can provide the common methods that all will share, and then each other sub-class will add new methods.
To help keep things clean you can add a Factory or a Builder to make things easier.
Here are some examples. Assuming base class is called Base, and sub-classes are one letter named classes, A, B, etc.
Factory example 1.
Base x = factory.getInstance(A.class);
Factory example 2.
Map props = ...;
Base x = factory.getInstance(A.class, props);
Builder example 1.
Base x = new ABuilder().setX(x).setY(y).setZ(z).create();
This involves creating a builder class for each individual sub-class. The sub-class builder classes may or may not inherit from an abstract BaseBuilder class that defines a method with signature public Base create();.
If the setters of the properties have some logic in them which is shared across multiple main classes, a decorator pattern can fit and be a good design approach. If not, e.g. you are sure that all they will ever do is this.x=x or that each class sets a property of some type diffrently then no.
You can define a class for each of the properties, and have your main classes have variables of types of the properties classes. this way when a property is being set on the main class it delegates the job to the setter of the appropriate property class, This way you define the setters of your properties once and use them everywhere. Again, in case you have more logic then this.x=x; in your setters this may be the best idea.
Oh and you can still return this for chainning after delegating the set job to the property class.
Also, if you are lazy and care less for real time performance, you can use reflections to ease the coding of your main classes.
From the names of the properties i would guess you are trying to define different coordinate representations? Why not use one base class with all properties?
Those are actually not that much properties and you can't combine them in random permutations. So why make every thing more complex then necessary?
I don't think Decorator would be a good fit here: the sense of a decorator is to stay transparent. If you define your properties like that, you would have to check (on type or existance of the property) for each and every access.

Is it possible to use Jackson views in combination with #JsonTypeName?

I'm working on an application where the serialized JSON includes the class name as a wrapper value. We need to continue supporting some of these names for legacy clients.
Using views, where the legacy object is the view and the new object is the instance, it's possible to get the correct fields serializing. However annotating the view with #JsonTypeName as well as #JsonTypeInfo is not causing the desired output.
So then, is it even possible to use a view to change the type name that the actual object instance would normally output?
Ok this had to do with a couple of things, namely my confusion of two different abstractions in Jackson: mixins and views. Plus a glitch related to static versus dynamic typing.

Structural design pattern

I'm working with three separate classes: Group, Segment and Field. Each group is a collection of one or more segments, and each segment is a collection of one or more fields. There are different types of fields that subclass the Field base class. There are also different types of segments that are all subclasses of the Segment base class. The subclasses define the types of fields expected in the segment. In any segment, some of the fields defined must have values inputted, while some can be left out. I'm not sure where to store this metadata (whether a given field in a segment is optional or mandatory.)
What is the most clean way to store this metadata?
I'm not sure you are giving enough information about the complete application to get the best answer. However here are some possible approaches:
Define an isValid() method in your base class, which by default returns true. In your subclasses, you can code specific logic for each Segment or FieldType to return false if any requirements are missing. If you want to report an error message to say which fields are missing, you could add a List argument to the isValid method to allow each type to report the list of missing values.
Use Annotations (as AlexR said above).
The benefit of the above 2 approaches is that meta data is within the code, tied directly to the objects that require it. The disadvantage is that if you want to change the required fields, you will need to update the code and deploy a new build.
If you need something which can be changed on the fly, then Gangus suggestion of Xml is a good start, because your application could reload the Xml definition at run-time and produce different validation results.
I think, the best placement for such data will be normal XML file. And for work with such data the best structure will be also XMLDOM with XPATH. Work with classes will be too complicated.
Since java 5 is released this kind of metadata can be stored using annotations. Define your own annotation #MandatoryField and mark all mandatory fields with it. Then you can discover object field-by-field using reflection and check whether not initiated fields are mandatory and throw exception in this case.

Best practice: Java/XML serialization: how to determine to what class to deserialize?

I have an application that saves its context to XML. In this application, there is a hierarchy of classes, that all implement a common interface, and that represent different settings. For instance, a first setting class may be made of 4 public float fields, another one can be made of a sole HashMap.
I am trying to determine what is the best way to handle writing and reading to XML in a generic way. I read on this site a lot about JAXB and XStream for instance, which are able to make a specific class instance from XML.
However my question is related to the fact that the actual class can be anything that implement a given interface. When you read the XML file, how would you guess the actual class to instantiate from the XML data? How do you do that in your applications?
I thought that I could write the .class name in a XML attribute, read it and compare it to all possible class .class names, until I find a match. Is there a more sensible way?
Thanks
xstream should already take care of this and create the object of correct type.
The tutorial seems to confirm that:
To reconstruct an object, purely from the XML:
Person newJoe = (Person)xstream.fromXML(xml);
If you don't know the type, you will have to first assign it to the common interface type:
CommonInterface newObject = (CommonInterface)xstream.fromXML(xml);
// now you can either check its type or call virtual methods
In my case I just have a kind of header that stores the class name that is serialized and when de-serializing it I just use the header value to figure out to which class shall I de-serialize the values.
A best practice would to use an established, well documented XML parser/mapper. All of the serialization/deserialization work has been done, so you can worry about your business logic instead. Castor and Apache Axiom are two APIs that I have used to marshal/unmarshall(serialize/deserialize) Java Classes and XML.
http://www.castor.org
Apache Axiom

How to avoid a large if-else statement in Java

I'm developing a framework in java which relies on a number of XML files with large number of parameters.
When reading the parameters from the XML file, I have to have a large if-else statement to decide what the parameters is and then call appropriate methods.
Is this normal? to have a large if-else statement?
I am thinking that there is a simple and neater way of doing this, e.g. Java XML mapping or Java Reflections? is this the answer? if so, can you please provide examples of how this is done so I don't have to rely on a large if-else statement?
Thanks!
You want to first create an interface:
public interface XMLParameterHandler {
public handle_parameter (String XMLData);
}
Next you want to create a map:
private Map<string, XMLParameterHandler> handlers;
...and initialize it with one of the relevant Map implementations:
this.handlers = new HashMap<>();
You need to implement the interface on a number of classes, one for each parameter you intend to handle. This is a good use of inner classes. Insert each of these implemented handerls into the map:
handlers.put ("Param1", new XMLParam1HandlerImpl());
handlers.put ("Param2", new XMLParam2HandlerImpl());
Then you can call the handler from the xml processing loop:
handlers.get (paramValue).handle_parameter(XmlData);
There is JAXB (http://en.wikipedia.org/wiki/Java_Architecture_for_XML_Binding) for mapping java class to xml.
But you can't map methods with it: you only can map attributes to xml file values (deserialize parameters from xml).
i recommend to use Map, that have parameter as key and xml entry as value(not whole xml)
Reflection would be one approach. Perhaps combined with a custom annotation on the target method to indicate which parameter to pass to that method. This is an advanced technique, though.
A more standard technique would be to use a map, where the key is the attribute name, and the value is an instance of an implementation of some interface you define, like AttributeHandler. The implementations then contain the code for each attribute. This involves writing a lot of little classes, but you can do them as anonymous classes to save space and keep the code inline.
a large if-else statement to decide what the parameters is and then call appropriate methods
You could instead use the Strategy design pattern, with one Strategy object per parameter, and use a map from the parameter name to the Strategy object to use. I've found this approach useful for even a moderately complicated application of XML.
It sounds to me as if you want a data-driven rule-based approach to writing your application, rather like you get in XSLT. One way of achieving this is to write it in XSLT instead of Java - XSLT, after all, was specifically designed for processing XML, while Java wasn't. If you can't do that, you could study how XSLT does it using rules and actions, and emulate this design in your Java code.
N functions with M parameters can always be implemented with a single function with M + 1 parameters.
If you need a big if then else statement to decide which method to dispatch to, then you can just add a parameter to your method and call a single method.
You shouldn't need an if-then-else statement to bind the parameter values.
If there is complex logic dependent on the particular parameter values, you might use a table driven approach. You can map various combinations of paramemter values into equivalence classes, then variouos equivalence class combinations into a row in a table with a unique id, then have a switch statement based on that unique id.

Categories