Test Serialization and Deserialization of objects in Java - java

Earlier, I had a java class:
public enum Currency
{
PENNY,
NICKLE,
DIME,
QUARTER;
}
Now I have made changes in the class and it looks like this:
public enum Currency
{
PENNY("Penny"),
NICKLE("Nickle"),
DIME("Dime"),
QUARTER("Quarter");
/**
* Instantiates a new currency.
*
* #param currencyType the currency type
*/
Currency(String currencyType)
{
this.value = currencyType;
}
String value;
/**
* Gets the value
*
*/
public String getValue()
{
return this.value;
}
}
I want to check if the Currency class object is getting serialized and deserialized properly. How should I check this through unit testing in java ?
I'm using DynamoDB to store the values of Currency. Currently they are being stored as Enum constants. Now when I have customized the enum's and added the value field. As far as I understood, serialization and deserialization is necessary when data transfer takes place through network. Please correct me here if I'm wrong. Also I'm using this value field to write to excel file using Apache POI. My question is the serialization and deseralization check necessary here for the custom enum class here ?

Related

Getter (accessor) based serialization (json or xml)

I need to serialize a couple of objects in my Android app and send them to web service.
The model classes for objects have various int fields which need to be converted into meaningful string representations from various arrays before sending to web service.
So, I am assuming that easiest way will be to use gson or xstream (JSON or XML - anything is fine) but with following method:
- I'll mark all existing int fields as transient and exclude them from serialization
- I'll create new get method per field. The get method will read value of corresponding integer and return its string representation.
But in either of 2 libraries - gson or xstream, I am unable to find way to serialize based on getters instead of fields. Please suggest.
And yes, I DO NOT need to deserialize the data back.
I think you need a wrapper class.
Consider this:
public class Blammy
{
private int gender;
... imagine the rest of the class.
}
public class BlammyWrapper
{
private String gender;
public BlammyWrapper(final Blammy blammy)
{
if (blammy.gender == 1)
{
gender = "Its a Boy";
}
else if (blammy.gender == 2)
{
gender = "girl";
}
else // always check your boundary conditions.
{
throw new InvalidArgumentException("Naughty blammy; unrecognized gender value");
}
public String gender()
{
return gender;
}
}
Ok, finally, I followed this approach:
1. Removed all resource arrays from my app code
2. Added enums with toString for each current array
3. Changed all int properties to be of corresponding enum type
4. Used XStream
5. Added a custom convertor for XStream for generic enum types where if it finds any property of type enum, then it will marshal it using toString method.
Thanks for all support btw. All your answers and comments atleast made me clear that my current code architecture needed drastic improvement.

SimpleXML framework: How to convert a non-standard basic type representation?

I am trying to convince SimpleXML to convert my Java objects to and from XML. I have a (seemingly) simple problem but I have now already wasted substantial time searching a description or an example for doing the following:
The XML format that I need to read or generate contains integer values that define colors and which are represented as hex integers (but without a leading "0x", same as in HTML or in misc. Android .xml files), i.e. red="ff0000", blue="00ff00", green="0000ff", etc.
My XML contains elements like:
<SomeObject name="foobar" checkedColor="123456" flaggedColor="FEDCBA" ... />
The corresponding Java class reads:
public class SomeObject
{
#Attribute
String name;
#Attribute #######
int checkedColor;
#Attribute #######
int flaggedColor;
// ...
}
I marked the two attributes I am talking about here with ####### above. The color values should be of type "int".
How do I teach SimpleXML that these value are represented as hex-string and how to convert them?
What transformer or converter or whatever do I need to write so that these int values are converted to/from hex-strings as shown and what do I have to annotate in the above code to achieve that?
Use a Transform, see the documentation below
http://simple.sourceforge.net/download/stream/doc/javadoc/org/simpleframework/xml/transform/Transform.html
I was finally able to implement what I want by defining a type "HexInt" which looks as follows
public class HexInt
{
private int value;
public HexInt(int value) {
setValue(value);
}
public HexInt(String value) {
setValue(value);
}
protected int getValue() {
return this.value;
}
protected void setValue(int value) {
this.value = value;
}
protected void setValue(String value) {
setValue(Integer.parseInt(value, 16));
}
#Override
public String toString() {
return Integer.toHexString(getValue());
}
}
and defining the corresponding attributes as
...
#Attribute(required=false)
protected HexInt checkedcolor;
#Attribute(required=false)
protected HexInt flaggedcolor;
...
plus defining a Matcher which for HexInt-s provides a corresponding Transformer that properly converts these values to and from strings.
But what I hate about this solution is, that I not only had to annotate my java code to achieve that result but actually had to use special, representation-specific classes, even though from the program logic there would be absolutely no need to define a special class containing only an int, just because I want to serialize these two fields in a special way. IMHO following an aspect oriented spirit the internal representation ("int") should be defined in the basic Java-code and that code should be agnostic of how the data gets represented when externalized.
The external representation on the other hand (i.e. whether I want to represent int-value as a decimal or hexadecimal string) should be defined in the annotations ONLY (plus supportive classes like Matcher and Transformer) but not in the basic Java code.
Is there really no way in the SimpleXML-framework to keep these different aspects more cleanly separated?

Is there a method in java that returns member variables of a class

I have a requirement to check if the member variables of a class are there in a list or not. For this, I need to get all the variables of a class dynamically (if possible as a list). Is there a method for that in java?
Thanks,
KD
This is the concept of Reflection. You should be able to do something like the following (untested) code snippet:
/**
* #return {#code true} if all of the values of the fields in {#code obj} are
* contained in the set of {#code values}; {#code false} otherwise.
*/
public boolean containsAllValues(HashSet<Object> values, MyClass obj) {
Field[] fields = MyClass.class.getFields();
for (Field field : fields) {
Object fieldValue = field.get(obj);
if (values.contains(fieldValue)) {
return false;
}
}
return true;
}
You may get all of the field names (and their values) by calling Class#getFields()
Example: Consider the class below
public class Test{
public int x, y, z;
}
Test.class.getFields() will return the fields x,y,z, in which you could get their name through Field#getName() and get their value by calling the appropriate get method. In the Test class above, you could do something like this:
Test instance = new Test();
instance.x = 50;
int xValue = Test.class.getField("x").getInt(instance);
The value of xValue would be 50.
For a better demonstration of how it works, please see this.
You're talking about reflection.
Have a look at Class.getFields():
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html
See also:
http://forgetfulprogrammer.wordpress.com/2011/06/13/java-reflection-class-getfields-and-class-getdeclaredfields/
There are quite a lot of fishhooks with reflection. Property-based access -- bean properties, of the form getX()/setX() or isX()/setX() -- may be a little better in helping you avoid unstable implementation internal of the class.
You can use the getFields() method, that will return a Field array: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getFields()
And then the getName() method for each element in the Field[] to get the name: http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Field.html#getName().
Most answers recommend Class.getFields() but as the JavaDoc states, it will only return the public fields:
Returns an array containing Field objects reflecting all the
accessible public fields of the class or interface represented by this
Class object.
I rarely make my class fields public and rather make them private with getters and setters. To get the list of all fields (including private, protected and package private) you need to use Class.getDeclaredFields():
Returns an array of Field objects reflecting all the fields declared
by the class or interface represented by this Class object. This
includes public, protected, default (package) access, and private
fields, but excludes inherited fields.
Note that unlike Class.getFields(), Class.getDeclaredFields() will not returned the inherited fields. To get those you need to loop through the class hierarchy (loop over Class.getSuperclass() until you reach Object.class). Private fields names could be repeated in parent classes.

Enum: Did I just do something unwanted?

I have an enum class which has several constants, and I want to add some static value FOCUSED which indicates which of the enum values has focus...
I found a way:
package messagesystem;
/**
*
* #author Frank
*/
public enum MessageType {
ALL,
GENERAL,
SEND,
RECEIVE,
LOG,
EXCEPTION,
DEBUG,
PM;
public final static MessageType FOCUSED = GENERAL;
private final String value;
MessageType() {
String firstLetter = name().substring(0, 1);
String otherLetters = name().substring(1, name().length());
this.value = firstLetter.toUpperCase() + otherLetters.toLowerCase();
}
#Override
public String toString() {
return value;
}
}
However, now I wonder: Did I just mess with the enum class? Because I don't want FOCUSED to be selectable when specifying the message type, however a class handling an enum of MessageType should be able to determine the FOCUSED value... Such that I do not need to hardcore it in every class.
Any thoughts are appreciated.
EDIT: It is behaving correctly though.
This code gives the expected output:
this.focused = MessageType.FOCUSED.toString();
System.out.println(focused);
The output is "General".
FOCUSED is just an alias to GENERAL. It won't appear in the values() of the enum, and if some client code uses FOCUSED, it will in fact use GENERAL, as both variables refer to the same enum value. So no, I don't think you messed up.
To reduce the confusion, maybe you should make focused() a static method, which returns GENERAL. This would also avoid the need to recompile client code in case you decide that the focused type is another one.

How to keep track of non empty field in Joda date buffer

I'm writing a set of objects that should be able to alter fields in a Joda Time MutableDateTime instance.
Each object is applied in sequence to the buffer, and when all that set is applied, a complete valid MutableDateTime will be built.
Each instance have to be able to know which date time fields has already been set by other instances in the set.
I get stucked because I get following problems:
How to create the MutableDateTime instance with empty values in all
date time fields in order to use it as the initial value to build?
How could I know if some field of MutableDateTime has been set?
MutableDateTime internally keep track it's data in a long instance field initialized to number of milliseconds elapsed from start of era to now. It thus has all field already set to some value.
Do you know if MutableDateTime has some concept of an empty value?
Edit:
as I show in my response, I develop a solution using a manager class as Vladimir suggested.
You should create "Manager" class to remember fields which was already set. It should throw exception if user tries to retrieve instance of MutableDateTime before all fields was set.
And if you always set all fields for MutableDateTime then [1] is not important (values will be overwriten).
I finally changed my initial design, and I implemented it exactly as Vadim Ponomarev suggested. Since each field type in Joda buffer has a corresponding DateTimeFieldType instance, I use a private Set object to keep track of the fields present.
The code below show how I've done:
private final Set<DateTimeFieldType> fieldTypes = Sets.newHashSet();
/**
* Allow to set to or reset one of the DateTimeFieldType fields
* #param fieldType the DateTimeFieldType field to change
* #param value the value to set it
*/
public void changeField(DateTimeFieldType fieldType, boolean value) {
if (value)
fieldTypes.add(fieldType);
else
fieldTypes.remove(fieldType);
}
/**
* Check if one of the DateTimeFieldType is present in this set.
* #param fieldType The field type to check for presence.
* #return true if the DateTimeFieldType is present, otherwise false
*/
public boolean isFieldSet(DateTimeFieldType fieldType) {
return !fieldTypes.contains(fieldType);
}
I've also added some utility methods allowing to change all fields for the date and all fields for the time at once. This could be useful in client to code to easy a common operation on date field sets.
/**
* Allow to set the fields that build the time part
* of a date time
* <p/>
*
* #param value value to set the DateTime fields
*/
public void changeTimeFields(boolean value) {
changeField(DateTimeFieldType.hourOfDay(), value);
changeField(DateTimeFieldType.minuteOfHour(), value);
}
/**
* Allow to set the fields that build the date part
* of a date time
* <p/>
*
* #param value value to set the DateTime fields
*/
public void changeDateFields(boolean value) {
changeField(DateTimeFieldType.dayOfMonth(), value);
changeField(DateTimeFieldType.monthOfYear(), value);
changeField(DateTimeFieldType.yearOfEra(), value);
}
And finally, I also added some method to query if all date fields are set and if all time fields are set:
/**
* Allow to check if the DateTimeFieldType fields that build the
* date part of a datetime has been set in this instance.
* <p/>
*
* #return true if date part has yet to be applied to
* the instance, false otherwise
*/
public boolean isDateSet() {
return fieldTypes.contains(DateTimeFieldType.dayOfMonth()) &&
fieldTypes.contains(DateTimeFieldType.monthOfYear()) &&
fieldTypes.contains(DateTimeFieldType.yearOfEra());
}
/**
* Allow to check if the DateTimeFieldType fields that build the
* time part of a datetime has been set in this instance.
* <p/>
*
* #return true if time part has yet to be applied to
* the instance, false otherwise
*/
public boolean isTimeSet() {
return fieldTypes.contains(DateTimeFieldType.minuteOfHour()) &&
fieldTypes.contains(DateTimeFieldType.hourOfDay());
}
I finally made it a DateTimeFieldTypeSet class. I think it encapsulate well a common concept that is lacking in Joda classes. I hope it can be useful to some one else too.

Categories