Java SOJO CSV Serialization - java

I am trying to use SOJO to serialize a Java object to CSV. The example looks pretty straight forward:
Car car = new Car("My Car");
car.setDescription("This is my car.");
Serializer csvSerializer = new CsvSerializer();
String csvStr = (String) csvSerializer.serialize(car);
System.out.println(csvStr);
// print:
// description,build,properties,name,~unique-id~,class
// This is my car.,,,My Car,0,test.net.sf.sojo.model.Car
I tried implementing my own version of the example. I made a really simple Car class with two String fields (build and description) which implements a setDescription(..) method.
This is what I implemented:
import net.sf.sojo.interchange.csv.CsvSerializer;
public class Main {
private class Car
{
private String build;
private String description;
public Car(String build) {
this.build = build;
this.description = null;
}
public void setDescription(String description) {
this.description = description;
}
}
public static void main(String[] args) {
Main m = new Main();
Car car = m.new Car("My Car");
car.setDescription("This is my car.");
CsvSerializer csvSerializer = new CsvSerializer();
String csvStr = (String) csvSerializer.serialize(car);
System.out.println(csvStr);
}
}
However, when I run my implementation I get the following output:
~unique-id~,class,description
0,Main$Car,
I don't understand why in my implementation neither the build or description fields are serialized, can you help?
Cheers,
Pete

From the SOJO home page: "The intention for this project is a Java framework, that convert JavaBeans in a simplified representation"
The Car object in your example does not qualify. You must have a getter (and, probabaly, a setter as well) for every property that you wish SOJO to write to (or read from) your file. Add getBuild() and getDescription()

I haven't used SOJO, but for private fields you probably need getter methods; or you could try declaring the fields public.

Related

Class Cast Exception while adding Objects to Apache Pool

I'm trying to figure out how to implement Apache Pool 2 (I'm using 2.5). As an initial POC I created an Employee Object with firstName, lastName, employeeId and age (Observer Pattern). I created an EmployeeObjectFactory which implements PooledObjectFactory and in the main class I was trying to add objects of Employee class. But I'm getting a class cast exception(EmployeeObjects cannot be cast to PooledObjects). So what changes do I need to make to my EmployeeObjects?
Employee Class
public class Employee{
private String firstName;
// omitting the getters and setters for other fields
public static class Builder {
private String firstName = "Unsub";
// declared and initialized lastName, emailId and age
public Builder firstName(String val) {
firstName = val;
return this;
}
// Similarly for other values
public EmployeeObject build() {
return new EmployeeObject(this);
}
}
private EmployeeObject(Builder builder) {
firstName = builder.firstName;
// omitting rest of the code
}
}
In the EmployeeObjectFactory
public class EmployeeObjectFactory implements PooledObjectFactory<EmployeeObject> {
#Override
public PooledObject<EmployeeObject> makeObject() {
return (PooledObject<EmployeeObject>) new EmployeeObject.Builder().build(); // This is where I'm getting the class cast
}
// Omitting rest of the code
}
Main Class
public static void main(String arg[]) throws Exception {
GenericObjectPool employeeObjectPool = new GenericObjectPool(new EmployeeObjectFactory());
employeeObjectPool.addObject();
I have tried to add as much little code as possible, because even I hate going through loads of code. Any help would be appreciated.
Finally got the answer after reading through the Apache Docs. DefaultPooledObject is what I need to use. DefaultPooledObject - "Create a new instance that wraps the provided object so that the pool can track the state of the pooled object." In the makeObject() function, I returned a DefaultPooledObject. So my code would look like
#Override
public PooledObject<EmployeeObject> makeObject() {
return new DefaultPooledObject<>(new EmployeeObject.Builder().build());
}

How to safely publish a mutable object?

I don't want to do the deep copy way.
Say, I have a field of some mutable type, a x,y,z Coordinate for example. Occasionally, I need to expose this field to some viewers. And I want it be read-only. I remember reading something like a wrapper to do these kind of stuff, but I don't remember the details.
The x,y,z Coordinate example may be too simple because x,y,z are primitive type. So getX() always return a copy.
I want a general solution even if the x,y,z fields are of yet another mutable type.
Can anybody help?
EDIT:
public class Client
{
public static final Holder holder = new Holder();
public static void main(String[] args)
{
UserWrapper user = holder.getUser();
System.out.println(user); //UserWrapper{user=User{address=Address{street='street 101'}}}
user.getAddress().setStreet("mars"); //UserWrapper{user=User{address=Address{street='mars'}}}
System.out.println(user);
}
}
public class Holder
{
private User user;
public Holder()
{
user = new User();
Address address = new Address();
address.setStreet("street 101");
user.setAddress(address);
}
public UserWrapper getUser()
{
return new UserWrapper(user);
}
}
public class User
{
private Address address;
public Address getAddress()
{
return address;
}
public void setAddress(Address address)
{
this.address = address;
}
}
public class UserWrapper
{
private User user;
public UserWrapper(User user)
{
this.user = user;
}
public Address getAddress()
{
return user.getAddress();
}
}
EDIT:
credit to I don't know who(he deletes the answer), I find this link he mentioned in his original post very helpful.
The traditional ways:
deep copy - prevents mutations from impacting the client who is reading
immutable objects - instead of copying for the client, you copy to update and the client gets an old pointer reference.
customer iterator - you provide your own iterator / navigation interface, which is sensitive to a "version" field embedded with the data structure. Before visiting each element, it checks that the version has not been changed since the iterator was created (java collections does this).
strong synchronization - while a reader is reading, the reader holds a lock on the data structure preventing update. Generally a bad solution, but occasionally useful (included for completeness).
lazy copy - you construct an object that mostly references the original, but is triggered (as a listener) to the original, such that when a mutation is done on the original, you copy the pre-mutated value locally.
This is like a lazy deep copy strategy.
There's others, but this should get you started.
There is no built-in mechanism in Java that will enable you to do that. Usually, if you move instances around, you'd either:
Use immutable objects
Pass on copies of the objects
Since you don't want/can't choose either of these ways, you'll need to use an alternative. There are a lot of different ways to implement this depending on your requirements and how complex is your class structure, but the general approach would be to publish an immutable wrapper instead of the original.
Here are some examples:
public class XYZ {
public int x, y, z;
}
public class XYZWrapper {
private XYZ xyz;
public XYZWrapper(XYZ xyz) {
this.xyz = xyz;
}
public int getX() { return x; }
public int getY() { return y; }
public int getZ() { return z; }
}
public class Address {
public String name;
public XYZ xyz;
}
public class AddressWrapper {
private String name; // Note that this could be public since any String is immutable
private XYZWrapper xyzWrapper;
public AddressWrapper(String name, XYZ xyz) {
this.name = name;
this.xyzWrapper = new XYZWrapper(xyz);
}
public String getName() {
return name;
}
public XYZWrapper getXYZWrapper() {
return xyzWrapper;
}
}
Now, if instead of XYZ and Address classes, you work with interfaces, you can have 2 implementations (e.g. XYZMutable & XYZImmutable) which will allow you to abstract which type of class you're returning, and also will enable you to create an instance of XYZImmutable from an instance of XYZMutable (assuming that the interface defines only & all getter methods).
One more note about this approach (especially if you do it the preferred way by using interfaces): Even if you have a complex class hierarchy, you can do this relatively effortlessly by creating a generator class that receives an interface instance, a mutable implementation instance and returns an immutable implementation instance as the return value.
Perhaps you're thinking of the "copy on write" idiom. This allows you to avoid copying unless you have to. It's use is generally not recommended because it is not thread-safe unless you use synchronization which will unnecessarily slow down single-threaded applications.
It works by keeping a reference count of its internal data; something like this untested bit of code:
public class User
{
private int addressReferenceCount;
private Address address;
public User(Address address) {
addressReferenceCount = 0;
this.address = address;
}
public Address getAddress() {
addressReferenceCount++;
return address;
}
public void setAddress(Address address)
{
if (addressReferenceCount == 0) {
this.address = address;
}
else {
this.address = new Address(address);
addressReferenceCount = 0;
}
}
}
This ensures that user code like this will get different addresses when necessary:
User u = new User(new Address("1 Acacia Avenue"));
Address oldAddress = u.getAddress();
Address stillOldAddress = u.getAddress();
u.setAddress(new Address("2 Acacia Avenue"));
Address newAddress = u.getAddress();
assert (oldAddress == stillOldAddress); // both refer to same object
assert (oldAddress != newAddress);

Best way to store collection of objects in Java?

I am creating a dump Java app for student information system for learning and implementing OOPS Concepts like inheritance, abstraction, polymorphism and encapsulation.
What I am doing is, I have created Faculty Class, Student Class and a College Class. Now i want to add new faculty in College. So my approach is to create a method in College class i.e. addFaculty(Faculty f) and fireFaculty(Faculty f), now i want to add Faculties in College class.
Whats the best way to do it? How do i store list of Faculty Object in College Object. Because i can add more than one faculty and more than one student in college.
Whats the best approach to solve this problem in OOPS?
Here is College.java code which i have implemented, it works fine but is this the best way i can solve it?
public class College
{
String name;
String location;
String courses[];
HashMap<String,Faculty> faculties;
int noOfFaculties = 0;
int noOfStudents = 0;
public College(String name,String location,String courses[])
{
this.name = name;
this.location = location;
this.courses = courses;
faculties = new HashMap<>();
}
public void addFaculty(Faculty faculty)
{
faculties.put(faculty.getName(),faculty);
}
public void printFaculties()
{
Set<String> set = faculties.keySet();
if(set.size()>0)
{
for(String s:set)
{
System.out.println(faculties.get(s).getName());
}
}
else
{
System.out.println("No Faculties Currently Working");
}
}
public void fireFaculty(Faculty faculty)
{
faculties.remove(faculty.getName());
}
public String getName()
{
return name;
}
public String getLocation()
{
return location;
}
public String[] getCourses()
{
return courses;
}
}
If you cannot have duplicates use HashSet<Faculty> if you dont mind use a List<Faculty>.
Example:
class College {
private List<Faculty> listFactories = new ArrayList<>(); // dupes allowed
private Set<Faculty> setFactories = new HashSet<>(); // no dupes allowed
}
Check collections API.
There's a ton of ways you can do it. Probably the easiest way to handle storing a collection of objects is by using one of the Collections provided by Java. For beginners, probably the easiest one to understand is an ArrayList, which is basically an array that grows in size dynamically depending on the amount of objects in the collection.
So, as an axample, your code might be something like this:
public class College
{
private ArrayList<Faculty> faculty;
public College()
{
faculty = new ArrayList<Faculty>();
}
public void addFaculty(Faculty f)
{
faculty.add(f);
}
public void fireFaculty(Faculty f)
{
faculty.remove(f);
}
}
imho It depends what kind of services College college offers. If I were coding, I would start with:-
List<Faculy> faculties = new ArrayList<>();
....
public void addFaculty(Faculty f) {
faculties.add(f);
}
//... etc
And change to an altearnative later if needed.

Simplest way to enforce "single-use", two step Builder implementation of a factory class in java

Hi guys : I have a builder class, which should only be used once. For example, there is a "setup" constructor, and then a "to..." method which specifies the type of object to be built.
For example
AnimalBuilder a = new AnimalBuilder("myTiger");
Animal tiger = a.toTiger(4);
//or
Animal dog = a.toDog(4) ;
etc.....
However, I don't want the Builder to ever be reused, and since it maintains state internally (i.e. unlike a factory, builders are two step process).
Thus, I'm currently wrapping each "toXXX" method by a precondition - that checks a true/false bit, which records wether or not the Builder has been completed. If so, then an IllegalStateException is then thrown.
A possible critique of this approach : Why am I using a builder (rather than a factory?) .... Because construction of these objects is much more modularized and easily understood using a two-step builder process - I don't want to copy the generic (first step) input args into all the specific methods.
1) Is there a simpler way to ensure that a builder class is used only once ? Im thinking maybe there is a Factory/Builder library out there which might make construction of these design patterns with less required boiler plate.
2) Is there a better way to implement a two-step object builder design pattern which is evading me at the moment ?
I'm not sure that you're going about using the Builder pattern correctly as you shouldn't have heaps of boilerplate code checking for the state. I'm also not sure why you would only want the builder to be used once, it seems counter-intuitive to me; but none the less - you shouldn't have to have lots of boilerplate code to stop the builder being used once if you set up the classes appropriately. For example:
public class CarBuilder {
//builder class
String make;
String model;
String colour;
boolean isUsed = false;
public Car build() {
if (isUsed) {
throw new IllegalStateException("Builder already used!");
}
isUsed = true;
return new Car(this);
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public String getColour() {
return colour;
}
public CarBuilder setMake(String make) {
this.make = make;
return this;
}
public CarBuilder setModel(String model) {
this.model = model;
return this;
}
public CarBuilder setColour(String colour) {
this.colour = colour;
return this;
}
}
public class Car {
//director class
private final String make;
private final String model;
private final String colour;
Car(CarBuilder theBuilder) {
make = theBuilder.getMake();
model = theBuilder.getModel();
colour = theBuilder.getColour();
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public String getColour() {
return colour;
}
}
public class Main {
public static void main(String[] args) {
CarBuilder subaruBuilder = new CarBuilder();
subaruBuilder.setColour("Blue");
subaruBuilder.setMake("Subaru");
subaruBuilder.setModel("Impreza");
Car subaruImpreza = subaruBuilder.build();
}
}
Using the above example, CarBuilder can only be used once as the build method has the check on it. I purposely didn't put the check on all of the set methods, as if this is the pattern of development that you are going to use then the developers in your area (or you, if you're solo) will know it and will not use them multiple times. Even if you do, when you try to build it will throw you the exception.
Force the user of your builder to choose one or the other implementation during construction.
Use the Step builder pattern for this kind of problems.

SimpleXML Constructor Exception - Can not create Inner Class

I'm just beginning to experiment with Android Development with SimpleXML and thought it was going quite well until I hit a snag. The code below produces an exception of
W/System.err(665): org.simpleframework.xml.core.ConstructorException: Can not construct inner class
I've looked through the questions on inner classes and think I understand why you would use them (not that mine was necessarily intentional) but despite moving my code round to try and avoid usage I'm still a little stuck and would appreciate any help.
Source Code:
public class InCaseOfEmergencyMedAlertAllergiesActivity extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Serializer serializer = new Persister();
InputStream xmlstream = this.getResources().openRawResource(R.raw.sample_data_allergies);
try {
medalertdata allergyObject = serializer.read(medalertdata.class, xmlstream);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setContentView(R.layout.allergies);
}
#Root
public class medalertdata {
#ElementList
private List<allergy> allergyList;
public List getAllergies() {
return allergyList;
}
}
#Root
public class allergy{
#Element
private String to;
#Element
private Boolean medical;
#Element
private String notes;
public allergy(String to, Boolean medical, String notes){
this.to = to;
this.medical = medical;
this.notes = notes;
}
public String getTo() {
return to;
}
public Boolean getMedical() {
return medical;
}
public String getNotes() {
return notes;
}
}
}
With the XML file referenced structured as:
<?xml version="1.0" encoding="ISO-8859-1"?>
<medalertdata>
<allergy>
<to>Penicillin</to>
<medical>true</medical>
<notes></notes>
</allergy>
<allergy>
<to>Bee Stings</to>
<medical>false</medical>
<notes>Sample</notes>
</allergy>
</medalertdata>
Is the problem with how I have annotated the SimpleXML classes or where I am trying to read them? Thanks!
I ran into this too while reading some deeply nested XML data into Java objects (and wanting to keep the object structure simple by defining the classes in the same file).
The solution (that doesn't involve splitting into separate files) was to make the nested classes static. (In other words, convert inner classes into static nested classes.) Kinda obvious in retrospective.
Example;
Nested structure:
// ScoreData
// Sport
// Category
// Tournament
Java:
#Root
public class ScoreData {
#ElementList(entry = "Sport", inline = true)
List<Sport> sport;
static class Sport {
#ElementList(entry = "Category", inline = true)
List<Category> category;
}
// ...
}
Disclaimer: I realise OP got the problem solved already, but maybe this helps others who run into
org.simpleframework.xml.core.ConstructorException: Can not construct inner class and don't want to define the classes in separate files as Peter's answer suggests.
Try removing #Root from the allergy class.
Also: do you have this two classes each in it's separate file: allergy.java and medalertdata.java?

Categories