Simple XML-serialization using Simple XML

In my last post I introduced Simple XML as an easy to use XML-Object mapper. I showed how to map XML-files to POJOs.
In this post I’ll deal with the other way round: store POJOs to XML-files. To show you how this is done with Simple XML, I’ll utilize and extend the calculator-example again.
After we have loaded the calculations, we should calculate them and store the results to our new Result-classes:

@Root(name="result")
public class Result {

	@Attribute
	private final int result;

	public Result(int result) {
		super();
		this.result = result;
	}

}
@Root(name="config")
public class Results {

	@ElementList
	private List results;

	public Results(List results) {
		this.results = results;
	}

}

There are no new annotations, just POJOs. In order to store the results, I modified the existing Calculation(s)-classes:

@Root(name="calculation")
public class Calculation {

	@Attribute
	private Operator operator;

	@Attribute
	private int valueA;

	@Attribute
	private int valueB;

	public Result getResult(){
		return new Result(operator.calculate(valueA, valueB));
	}
}
@Root(name="config")
public class Calculations {

	@ElementList(name="calculations")
	private List calculations;

	public List calculateAll(){
		List results = new ArrayList();
		for(Calculation c:calculations){
			results.add(c.getResult());
		}
		return results;
	}

}

What steps do we have to perform now?

  • Read the calculations from calculations.xml
  • Calculate the results
  • Store the results into results.xml

Translated into code, this is what it looks like:

        public static void main(String[] args) throws Exception {
		write(calculate(read()));
	}

	public static Calculations read() throws Exception{
		Serializer serializer = new Persister();
		File file = new File("calculations.xml");
		return serializer.read(Calculations.class, file);
	}

	public static Results calculate(Calculations calculations){
		return new Results(calculations.calculateAll());
	}

	public static void write(Results results) throws Exception{
		Serializer serializer = new Persister();
		File file = new File("results.xml");
		serializer.write(results, file);
	}

As you can see, serializing to XML is also pretty easy and nothing compared to the common DOM or SAX-frameworks.
Finally, let’s take a look at the written xml-file:

<config>
  <results class="java.util.ArrayList">
    <result result="3"/>
  </results>
</config>

This is almost what we expected, except of the new class-attribute in results-element. This attribute is automatically generated by Simple XML to determine the implementation of the java.util.List-interface that was used while the file was serialized (we created a new ArrayList instance in line 8 of Calculations-class). Whenever the file gets deserialized an instance of this class will be used to store the results (defaults to java.util.ArrayList).

Advertisements

JPA EntityManager.unwrap()-method

Last week I came in touch with the very useful

EntityManager.<T>unwrap(Class<T>)

-method from the javax.persistence-package. The method can be used to gain access of JPA-vendor-specific classes. At work, we are running Hibernate in “JPA-mode” which means we do only have access to methods that are provided by the EntityManager-interface. It was ok to us, until we wanted to get rid of those SELECT-statements that the EntityManager.merge()-method does before the UPDATE-statement is fired to the database. If we were running Hibernate in “Hibernate-mode” we wouldn’t have any problems at all: the EntityManager-equivalent Session-class offers a update()-method which fires only the UPDATE-Statement without any SELECTs. This is where the unwrap-method comes into play. Just fetch an EntityManager-instance via injection or create a new one on your own via EntityManagerFactory and place the following snippet into your code:

EntityManager em = ...
Session session = em.unwrap(Session.class);
//em.merge(myEntity);
session.update(myEntity);

Thanks to axtavt for his/her advice.

Combining Delegation- and Strategy-Pattern using an Enum

The Delegation- and  Strategy-patterns are extremly useful when you need to implement some operations (strategies) and want to bundle them in one class. I won’t explain the patterns in detail here, but give you an example of how to combine both of them.

Imagine the following interface which represents the “strategy” to implement:

public interface Calculatable {

/**
* Calculate something.
* @param valueA
* @param valueB
* @return
*/
public int calculate(int valueA, int valueB);

}

Now we have some concrete “strategy-implementations” which represent the four basic arithmetic operations:

class Add implements Calculatable{
@Override
public int calculate(int valueA, int valueB) {
return valueA + valueB;
}
}
class Subtract implements Calculatable{
@Override
public int calculate(int valueA, int valueB) {
return valueA - valueB;
}
}
class Multiply implements Calculatable{
@Override
public int calculate(int valueA, int valueB) {
return valueA * valueB;
}
}
class Divide implements Calculatable{
@Override
public int calculate(int valueA, int valueB) {
return valueA / valueB;
}
}

Nothing special until here, just a straight-forward implementation of the strategy-pattern.
But now we introduce the Delegation-pattern using an Enum.

public enum Operator implements Calculatable{
ADD(new Add()),
SUBTRACT(new Subtract()),
MULTIPLY(new Multiply()),
DIVIDE(new Divide())
;

private final Calculatable delegate;

private Operator(Calculatable delegate) {
this.delegate = delegate;
}

@Override
public int calculate(int valueA, int valueB) {
return this.delegate.calculate(valueA, valueB);
}

}

This enum does not implement the strategy provided by Calculateble-interface but just delegates it to the other implementations. What are the benefits:

  • All operations in one class
  • Having the four implementations placed inside the enum as nested classes ensures singleton-behaviour
  • Smart access to the strategies via enum
public static void main(String[] args) {
System.err.println(Operator.ADD.calculate(5, 5));
System.err.println(Operator.SUBTRACT.calculate(5, 5));
System.err.println(Operator.MULTIPLY.calculate(5, 5));
System.err.println(Operator.DIVIDE.calculate(5, 5));
}

Happy coding!

http://en.wikipedia.org/wiki/Strategy_pattern

http://en.wikipedia.org/wiki/Delegation_pattern