JAXB and Interfaces seem to confuce me - java

I know there are a lot of questions around here regarding JAXB and Interfaces and I did some search here but without any luck. So if you think this is already answered go ahead and link it to me please.
Now to my problem:
I have an arraylist filled with objects that get casted to an interface class:
private ArrayList<IEvent> eventLog;
And I want to save the eventLog as XML to file and load it again from the file.
I have a single interface class that gets implemented by a lot of classes.
Because of the amount of implementing classes I have, I want to do something like mentioned here in 3.2.1.
The problem is that I don't seem to get it, cause JAXB tells me every time I try to run the program, that it does not support interfaces.
My Interface looks like this:
public interface IEvent {
public abstract void process();
}
And my implementations look like this:
public class ProjectEdited implements IEvent {
private String newName;
private String newDate;
private int newNeededEmployees;
private int sender;
public ProjectEdited(int sender, String newName, String newDate, int newNeededEmployees) {
this.newName = newName;
this.newDate = newDate;
this.newNeededEmployees = newNeededEmployees;
this.sender = sender;
}
#Override
public void process() {
// call the responsible handler
}
If someone could give me a tip, what kind of annotations I need to use (and where AND WHY!) I would really appreciate it.
I am also open for alternatives for what I want to do, hope someone can help me.
Greetz Saladino

Related

Java Wrapper classes

I have a bunch of classes (a few 10s), that got generated from the .proto files I have. These classes are configuration items. So, let's say I have:
class config_item_1 {
string Id;
...
...
}
class config_item_2 {
string Id;
...
...
}
I have instances of these classes which represent my system configuration. I'm building logic in my code to keep them in-memory, performing some transformations, and at the end, I need to figure out which objects changed. That is, some objects might stay untouched, some might go away, some might change.
So, for all these classes, I need to add a "status" without changing the actual class definitions. Something like a wrapper.
What is the best way to achieve this?
EDIT:
Another "hack" I'm considering is, since my config item classes are generated classes from proto file, like I mentioned, I'm thinking of creating a wrapper proto, like this:
message ConfigCacheItem {
enum ItemState {
UNTOUCHED = 0;
CREATED = 1;
UPDATED = 2;
DELETED = 3;
}
ItemState item_state = 1;
String id = 2; /* ID stashed from one of the items below for lookup */
oneof config_item {
ConfigItem1 config_item_1 = 3;
ConfigItem2 config_item_2 = 4;
....
}
}
The initial problem is that generated code is almost always the wrong way to go--yet some people insist so let's make the best out of it.
You can extend the class and add functionality. This is probably a bad idea in your case:
class ConfigItem1Wrapper extends config_item_1 {
public Boolean getStatus()
{…}
...
}
The main problem here is that you will have ~10 of these classes so a lot of duplicated code or forwarding. It's also going to give you problems if whatever system you are using to create these classes also wants to instantiate them... if it does you will get instances of "config_item_1" instead of the more awesomely named "ConfigItem1Wrapper"
You can encapsulate the class in another class as a delegate. This isn't as bad as it seems. Some editors can automatically create classes like this. Each method is re-created and the call is forwarded to the copy you store internally.
class ConfigItem1Wrapper {
config_item_1 delegate;
String some_method1(var) {
return delegate.some_method1(var);
}
}
If you can use delegation like this (Hopefully using some IDEs code generation) it might be the best way, it gives you complete control.
Were you to use Groovy (A superset of Java) you'd find it has an #Delegate annotation that does this all for you. Just this:
class ConfigItem1Wrapper {
#Delegate config_item_1 delegate;
public Boolean getStatus() {
return status;
}
}
would generate all the methods from config_item_1 onto ConfigItem1Wrapper with your additional code. I'm guessing that won't work for you. Pity.
Honestly nearly any other solution I could give you is some type of delegation. I recommend you just find some way to make delegation work (without having to forward each method manually)
Straight forward way is to create wrapper class and extend/ override setter and use them for your status tracking
I believe that you need a Decorator Pattern.
Something like the example bellow.
public class Decorator_config_item_1 {
private config_item_1 item_1;
private Boolean status;
public Decorator_config_item_1(config_item_1 item_1) {
this.config_item_1 = item_1;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
}

Composition over inheritance for RealmObjects with Gson serialization

I'm considering Realm as a database solution for various reasons, but the big one currently being the TransactionTooLargeException now being thrown in Nougat has made it so I have to rework my current database architecture, based on ActiveAndroid, which has its own annoying limitations. The difficulty is that Realm does not support inheritance (https://github.com/realm/realm-java/issues/761) and they don't seem in any particular hurry to get around to it. Instead, they recommend using composition over inheritance, but I can't figure out how to make that work with Gson/Json deserialization.
Example:
Superclass: Animal, with subclasses Dog and German Shepherd
public class Animal {
private int numLegs;
private boolean hasFur;
}
public class Dog extends Animal {
private String color;
private boolean canDoTricks;
}
public class GermanShepherd extends Dog {
public boolean isGuardDog;
public boolean isAtRiskOfHipDysplasia()
}
(Sorry, this is a super canned example, just to illustrate).
Now let's say the json for this looks like:
{
"numLegs" : 4,
"hasFur" : true,
"color" : "Black & Brown",
"canDoTricks" : true,
"isGuardDog" : true,
"isAtRiskofHipDysplasia" : false
}
Now, I cannot modify the Json because it's an API that's giving it to me.
Looking at this answer: https://stackoverflow.com/a/41552457/4560689, it appears it is possible in a very hacky way to make it sort of work, but the answer notes that there are limitations including that the serialization would be wrong. Since the server only talks in the json format that doesn't involve crazy composition, this presents a problem.
Can I write a custom Gson deserializer/serializer to make this work? If so, what would that look like? I basically need to be able to convert a json payload into up to N objects, where N - 1 objects are nested inside the base object.
So with composition (note this isn't necessarily "Realm" composition, just an example, since it looks like Realm has to use some weird form of interface-composition), I'd have a class like below:
public class GermanShepherd {
public Animal animal;
public Dog dog;
// Generate a bunch of delegate methods here
}
Am I barking up the wrong tree? It feels like Realm might not work for what I'm trying to do, and inheritance is built into the API I'm using in multiple places, and specifically in the objects I want to persist, so I have to either figure out a workaround or use another solution. ActiveAndroid (what I'm using now) is also a less than ideal solution and I'm sick to death of dealing with skirting around deadlocks, crashes, querying on background threads that now cause crashes if the data is too big to pass in an Intent, etc...all issues with SQLite. I'm open to solutions to my main question or to alternatives that would solve this problem. Thanks in advance for your help!
You should create a new RealmObject class for each flattened concrete class, and map your JSON representation to them.
To retain inheritance, you can simulate it by inheriting getters/setters from interfaces that inherit from one another.
public interface IAnimal extends RealmModel {
int getNumberOfLegs();
void setNumberOfLegs(int legs);
boolean getHasFur();
void setHasFur(boolean hasFur);
}
public interface IDog extends IAnimal {
String getColor();
void setColor(String color);
boolean getCanDoTricks();
void setCanDoTricks();
}
public interface IGermanShepherd extends IDog {
boolean getIsGuardDog();
void setIsGuardDog(boolean isGuardDog);
boolean getIsAtRiskOfHipDysplasia();
void setIsAtRiskOfHipDysplasia(boolean isAtRisk);
}
Because then you can do
public class GermanShepard
extends RealmObject
implements IGermanShepard {
private int numLegs;
private boolean hasFur;
private String color;
private boolean canDoTricks;
private boolean isGuardDog;
private boolean isAtRiskofHipDysplasia;
// inherited getters/setters
}
You can even make repository class out of it
public abstract class AnimalRepository<T extends IAnimal> {
protected Class<T> clazz;
public AnimalRepository(Class<T> clazz) {
this.clazz = clazz;
}
public RealmResults<T> findAll(Realm realm) {
return realm.where(clazz).findAll();
}
}
#Singleton
public class GermanShepardRepository extends AnimalRepository<GermanShepard> {
#Inject
public GermanShepardRepository() {
super(GermanShepard.class);
}
}
And then
#Inject
GermanShepardRepository germanShepardRepository;
RealmResults<GermanShepard> results = germanShepardRepository.findAll(realm);
But you can indeed merge them into one class and then give it a String type; parameter to know what type it originally was. That's probably even better than having all these GermanShepards.

Java BuilderTestPattern - how to avoid boilerplate?

I have a lot of value objects in my project.
I'm using project lombok to eliminate some boilerplate, so my value objects look like the following one:
#Value
#Accessors(fluent = true)
public class ValueObject {
private final String firstProp;
private final int secondProp;
}
Not bad, almost no boilerplate.
And now, I'm using the all-args constructor quite often in my tests. It looks quite messy, so I thought I will introduce Builder Pattern variant instead:
public class ValueObjectBuilder {
private static final int DEFAULT_VALUE_FOR_SECOND_PROP = 666;
private String firstProp = "default value for first prop;
private int secondProp = DEFAULT_VALUE_FOR_SECOND_PROP;
private ValueObjectBuilder() {}
public static ValueObjectBuilder newValueObject() {
return new ValueObjectBuilder();
}
public ValueObjectBuilder withFirstProp(String firstProp) {
this.firstProp = firstProp
return this;
}
public ValueObjectBuilder withFirstProp(int secondProp) {
this.secondProp = secondProp;
return this;
}
public ValueObject build() {
return new ValueObject(
firstProp, secondProp
);
}
}
and the code looks quite nice now:
ValueObjectBuilder
.newValueObject()
.withFirstProp("prop")
.withSecondProp(15)
.build();
Now, the problem is - as I mentioned, I have to write a lot of similar classes... I'm already tired with copy-paste'ing them.
What I'm looking for, is a black-magic-smart-tool, which will somehow generate this code for me.
I know, there is a #Builder annotation in Lombok, but it doesn't meet my requirements. Here's why:
1) I'm unable to provide default values in lombok's Builder. Well, actually, it is possible - by implementing builder class template myself like
#Builder
public class Foo {
private String prop;
public static class FooBuilder() {
private String prop = "def value";
...
}
}
which generates some boilerplate too.
2) I can't find any way to put prefix on each field accessor in lombok's builder. Maybe #Wither could help here? But I don't know, how to use it properly.
3) The most important reason: I'm not creating a "natural" builder. As far as I understand, lombok is designed to create Builder for a given, annotated class - I don't know if there is a way to return any other object from within build() method.
So, to sum up:
Do you know any tool which could possibly help me? Or maybe all those things I mentioned are in fact possible to achieve using Lombok?
EDIT
Ok, so I probably found a solution to this particular case. With lombok we can use:
#Setter
#Accessors(chain = true, fluent = true)
#NoArgsConstructor(staticName = "newValueObject")
public class ValueObjectBuilder {
private String firstProp = "default";
private int secondProp = 666;
public ValueObject build() {
return new ValueObject(firstProp, secondProp);
}
}
Cheers,
Slawek
I know this is old but if anyone else runs into this, I found an alternative solution for providing default values for a builder.
Override the builder method and provide the default values before returning a builder. So in the above case:
#Builder
public class Foo {
private String prop;
public static FooBuilder builder() {
return new FooBuilder().prop("def value");
}
}
It's not an ideal solution but beats having to override the whole builder itself or have a custom constructor (which is painful IMHO if there are a lot of variables. It would still be nice to have something along the lines of a #With or #Default annotation to handle this.
Try Bob-the-builder for eclipse. Hmm.. I guess that works best if you happen to be using eclipse! If you are not using eclipse, there are a few related projects mentioned at the bottom of the page linked here that may be useful.

How can Extract Class Eclipse IDE refactoring functionality be useful?

I came across a refactoring functionality that looks to be useful as I learn eclipse and java. But I'm not sure how this could be useful. Is there a pattern that would benefit from this kind of refactoring? This refactoring option basically extracted out all variables into another class whose name was changed to append Data at the end.
Any examples of WHAT/WHY this kind of refactoring gives us would be really helpful.
Thank you in advance.
Extract Class is mostly used when a class has too many responsibilities; it is trying to do too much. It splits out the class into two individual classes and then transfers some functionality into the other class - obviously there will be a relationship between the classes because you still want all of the code to interact.
You can combine Extract Class with other refactoring patterns such as Move Method and Move Field that will move methods and fields to the other class in such a way that all of the code still works as intended.
This link has a good example of Extract Class: http://sourcemaking.com/refactoring/extract-class
If you had too many fields in your class and you see that this must be a extra class, you can use it.
Example:
public class Person {
private int age;
private String name;
private String street;
private int streetnumber;
}
to:
public class Person {
private int age;
private String name;
private Adress data = new Adress();
}
public class Address {
public String street;
public int streetnumber;
public Address() {}
}

Does the code-to-interface principle apply to entity classes?

I'm trying to follow code-to-interface on a project. Should I be creating an interface first then implementing that interface for entity classes? I'm thinking this might be taking the interface first approach too far and entities should be ignored. This is what I mean...
public interface Address {
public String getStreet();
public void setStreet(String street);
}
#Entity
public class AddressImpl implements Address {
private String street;
public String getStreet(){
return this.street;
}
public void setStreet(String street){
this.street = street;
}
}
#Entity
public class OfficeImpl /* implements Office */ {
private Address location;
public Address getLocation(){
return this.location;
}
public void setLocation(Address location){
this.location = location;
}
}
public class Driver {
public static void main(String[] args) {
Office work = new OfficeImpl();
Address workAddress = new AddressImpl();
workAddress.setStreet("Main St.");
work.setLocation(workAddress);
}
}
I think creating Interfaces for Entities is probably not necessary.
The purpose of creating Interfaces (or at least, one of the purposes) is to make it easier to swap out one concrete implementation in favour of another. This is obviously a good thing for your DAOs, Business Logic etc.
But unless you have plans for the implementation of your entities to change as well, I would avoid it!
In your example, you are probably taking it too far, but once you add methods, write test cases and possibly use dependency injection, it will make more sense.
For simple projects like this, it is overkill, but once you get into a 'real' application, then it is often a good idea. Just be careful not to overdo it, everything doesn't need to implement an interface, just where it makes sense.
the interface for Entities should be the behaviors and properties that are common to all Entities!
public interface IEntity
{
int EntityId { get; set; }
bool FindById(int id);
bool Create(object [] values);
bool Delete(int id);
//etc.
}
sorry for the C# example, but the language doesn't matter. Interfaces are for 'plug compatability'.
I think when you're talking about entities, it's probably overkill.
Interfaces are useful when you're working with entities that have a common usage, but aren't necessarily the same. Can't think of a good way to explain it, but here's an example:
interface IFlaggable {
bool IsFlagged ...
string Reason ...
}
class ForumPost implements IFlaggable { }
class PrivateMessage implements IFlaggable { }
Hope that helps!
I generally don't make interfaces for data holding beans, that is I don't make interfaces for classes with primitive type values and getters/setters for them. Haven't really ever hit a moment where I would've needed interfaces for anything I usually use them for (polymorphism and mocking, mostly) so I haven't bothered doing that.
I guess I should point out that most of the time when I use databeans I also reflect the values from those same objects with custom classes which work like this:
Reflector r = new Reflector(new DataBean( [ values given through constructor ] ));
long someNumber = r.get("method", Long.class);

Categories