XMLEncoder not writing object data when class fields are private - java

I have a class with private fields and public methods. My methods follow the get/set naming convention. When my fields are private and I try to write my object data to an XML file, I get an empty XML file, but when I change them to public, the XML contains all the necessary data. What do you think is causing this?
public class ClassData {
private String name;
private ArrayList<String> methods;
public ClassData()
{
methods = new ArrayList<>();
}
public void setName(String cName)
{
name = cName;
}
public String getName()
{
return name;
}
public void setMethods(String mName)
{
methods.add(mName);
}
public ArrayList<String> getMethods()
{
return methods;
}
}
String fileName = cObj.getName() + ".xml";
XMLEncoder enc=null;
try{
enc=new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
}catch(FileNotFoundException fileNotFound){
System.out.println("Unable to save file.");
}
enc.writeObject(cObj);
enc.close();

This is because your methods do not have a "Setter" to make it an accessible "property". Change method setMethods(String mName) to addMethod(String mName) to add individual method and add a setter setMethods that sets same time as that of methods and things work. Sample below:
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
public class ClassData {
private String name;
private ArrayList<String> methods;
public ClassData() {
methods = new ArrayList<>();
}
public void setName(String cName) {
name = cName;
}
public String getName() {
return name;
}
public void addMethod(String mName) {
methods.add(mName);
}
public void setMethods(ArrayList<String> m)
{
methods.addAll(m);
}
public ArrayList<String> getMethods() {
return methods;
}
public static void main(String[] args) {
ClassData cObj = new ClassData();
cObj.setName("This_is_name");
cObj.addMethod("m1");
String fileName = cObj.getName() + ".xml";
XMLEncoder enc = null;
try {
enc = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
} catch (FileNotFoundException fileNotFound) {
System.out.println("Unable to save file.");
}
enc.writeObject(cObj);
enc.close();
}
}

Related

Serializing an object to file creates blank object in file

I am trying to create an object that is then serialized and written to file but regardless of what I try, a blank object is always written to file instead.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class FileIO implements Serializable {
private static final long serialVersionUID = 1L;
private VIAModel viaModel1;
private VIAView viaView1 = new VIAView();
private VIAController viaContr = new VIAController();
public void setVIAModelFromFile() throws IOException, ClassNotFoundException, EOFException {
boolean endOfFile = false;
FileInputStream fstream = new FileInputStream("viaModel.ser");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
while (!endOfFile) {
try {
viaModel1 = (VIAModel) inputFile.readObject();
} catch (EOFException eof) {
endOfFile = true;
}
}
inputFile.close();
}
public void setToFile() throws IOException {
viaContr = viaView1.getController();
viaModel1.setEventList(viaContr.getVIAMod().getEventList());
System.out.println(viaModel1.getEventList().getListOfEvents());
FileOutputStream fstream = new FileOutputStream("viaModel.ser");
ObjectOutputStream outputFile = new ObjectOutputStream(fstream);
try {
outputFile.writeObject(viaModel1);
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} catch (IOException ioe) {
System.out.println("Error.");
ioe.printStackTrace();
}
}
public VIAModel getVIAModel() {
return viaModel1;
}
public void setVIAModel(VIAModel viamod) {
this.viaModel1 = viamod;
}
}
The object being written has serializable on all objects inside and objects unable to be serialized have been manually serialized. The system.out.print shows the object with the information entered in the program, but this information doesn't appear in the .ser file at all and so only a blank object is read later.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javafx.beans.property.SimpleStringProperty;
public class Events implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5596571541918537611L;
private transient SimpleStringProperty name = new SimpleStringProperty("");
private transient SimpleStringProperty date = new SimpleStringProperty("");
private transient SimpleStringProperty duration = new SimpleStringProperty("");
private transient SimpleStringProperty type = new SimpleStringProperty("");
private transient SimpleStringProperty location = new SimpleStringProperty("");
private transient SimpleStringProperty category = new SimpleStringProperty("");
// private Lecturer conductor;
private transient SimpleStringProperty price = new SimpleStringProperty("");
private transient SimpleStringProperty minPartic = new SimpleStringProperty("");
private transient SimpleStringProperty maxPartic = new SimpleStringProperty("");
private boolean isFinalized = false;
// ArrayList<Members> eventMembList = new ArrayList<>();
public Events(String name, String date, String duration, String type, String location, String category,
/* Lecturer conductor, */ String price, String minPartic, String maxPartic, boolean isFinalized) {
setName(name);
setDate(date);
setDuration(duration);
setType(type);
setLocation(location);
setCategory(category);
setPrice(price);
setMinPartic(minPartic);
setMaxPartic(maxPartic);
this.isFinalized = isFinalized;
}
public Events() {
this("","","","","","","","","",false);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public String getDate() {
return date.get();
}
public void setDate(String date) {
this.date.set(date);
}
public String getDuration() {
return duration.get();
}
public void setDuration(String duration) {
this.duration.set(duration);
}
public String getType() {
return type.get();
}
public void setType(String type) {
this.type.set(type);
}
public String getLocation() {
return location.get();
}
public void setLocation(String location) {
this.location.set(location);
}
public String getCategory() {
return category.get();
}
public void setCategory(String category) {
this.category.set(category);
}
public String getPrice() {
return price.get();
}
public void setPrice(String price) {
this.price.set(price);
}
public String getMinPartic() {
return minPartic.get();
}
public void setMinPartic(String minPartic) {
this.minPartic.set(minPartic);
}
public String getMaxPartic() {
return maxPartic.get();
}
public void setMaxPartic(String maxPartic) {
this.maxPartic.set(maxPartic);
}
public boolean isFinalized() {
return isFinalized;
}
public void setFinalized(boolean isFinalized) {
this.isFinalized = isFinalized;
}
public void finalizeEvent() {
this.isFinalized = true;
}
// public void addMemToEvent(Members member) {
// eventMembList.add(member);
// }
public String toString() {
return this.name + "\n" + this.date+ "\n" + this.duration+ "\n" + this.type+ "\n" + this.location+ "\n" + this.category+ "\n" + this.price+ "\n" + this.minPartic+ "\n" + this.maxPartic+ "\n" + this.isFinalized;
}
public void readExternal(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
name = new SimpleStringProperty((String) in.readObject());
date = new SimpleStringProperty((String) in.readObject());
duration = new SimpleStringProperty((String) in.readObject());
type = new SimpleStringProperty((String) in.readObject());
location = new SimpleStringProperty((String) in.readObject());
category = new SimpleStringProperty((String) in.readObject());
price = new SimpleStringProperty((String) in.readObject());
minPartic = new SimpleStringProperty((String) in.readObject());
maxPartic = new SimpleStringProperty((String) in.readObject());
}
public void writeExternal(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(name.get());
out.writeObject(date.get());
out.writeObject(duration.get());
out.writeObject(type.get());
out.writeObject(location.get());
out.writeObject(category.get());
out.writeObject(price.get());
out.writeObject(minPartic.get());
out.writeObject(maxPartic.get());
}
}
Changing SimpleStringProperty to String seems to work perfectly and eliminates all of the issues involved with serializing, which is something that I don't have the knowledge to correct.
in your below code you will end up reading only the last object make sure you are reading correct contents from input file. Did you tried populating a new VIAModel object and then writing it to the file
while (!endOfFile) {
try {
viaModel1 = (VIAModel) inputFile.readObject();
} catch (EOFException eof) {
endOfFile = true;
}
It is exactly as I said. You have
public class Events implements Serializable
and a whole series of transient fields, and also
public void readExternal(ObjectInputStream in)
and
public void writeExternal(ObjectOutputStream out)
These methods are never called. There is nothing in the Object Serialization Specification about either of these method signatures.
If you want this class to be serialized, you need to either remove transient throughout, if SimpleStringProperty is Serializable, and remove these methods, or make it extends Externalizable, and fix the resulting compilation errors.
What you can't do is just make up your own semantics and signatures and then wonder why Java doesn't implement them.

Import csv's into data stax cassandra through spark (Java Api)

Is there a way to import csv into cassandra through spark's java api without creating a pojo class for the csv. I am able to insert the csv by creating a pojo class like below , Is there any way to do so without creating pojo class for the csv programatically using spark java api.
My csv looks like this
Name,Age,bg,sex
ammar,67,ab+,M
nehan,88,b+,M
moin,99,m+,M
arbaaz,67,a+,M
...
And the program is below.
import org.apache.commons.lang3.StringUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import com.cassandra.insertion.MergeGeneSymDataInsertion;
import com.cassandra.insertion.MergeGeneSymDataInsertion.HgIpsenGeneSym;
import com.publicdata.task.PublicDataInsertion.PublicData;
import static com.datastax.spark.connector.japi.CassandraJavaUtil.*;
public class InsertCsv {
static JavaSparkContext ctx = null;
static boolean isHeader = true;
public static void main(String[] args) {
try {
ctx = new JavaSparkContext(new SparkConf().setMaster("local[4]")
.setAppName("TestCsvInserion"));
insertCsv(ctx);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void insertCsv(JavaSparkContext ctx) {
JavaRDD<String> testfileRdd = ctx
.textFile("/home/syedammar/Pilot Project /test.csv");
JavaRDD<Bats> batsclassRdd = testfileRdd
.map(new Function<String, Bats>() {
#Override
public Bats call(String line) throws Exception {
// TODO Auto-generated method stub
if(!isHeader){
String[] words=StringUtils.split(line, ",");
String name = words[0];
String age = words[1];
String bg = words[2];
String sex = words[3];
return new Bats(name, age, bg, sex);
}
else
{
isHeader=false;
return null;
}
}
}).filter(new Function<Bats, Boolean>() {
#Override
public Boolean call(Bats obj) throws Exception {
// TODO Auto-generated method stub
return obj!=null;
}
}).coalesce(1);
javaFunctions(batsclassRdd).writerBuilder("test", "bats", mapToRow(Bats.class)).saveToCassandra();
}
public static class Bats {
public Bats() {
// TODO Auto-generated constructor stub
}
private String name;
private String age;
private String bg;
public Bats(String name, String age, String bg, String sex) {
super();
this.name = name;
this.age = age;
this.bg = bg;
this.sex = sex;
}
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getBg() {
return bg;
}
public void setBg(String bg) {
this.bg = bg;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
}
Yes you can do that. I found it while browsing... please refer -
How to Parsing CSV or JSON File with Apache Spark
There are two approaches, follow Procedure for approach B
POJO classes are not required for the approach B, but POJO classes would make your code easier to read if you are using Java
Hope this will help.

db4o - weird characters when retrieving objects

import java.io.File;
import com.db4o.Db4o;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Query;
public class Student {
private String name;
public AlumnoBDOO(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
ObjectContainer bd = Db4oEmbedded.openFile("students.db4o");
try {
Student s1 = new Student("Carl");
bd.store(s1)
showStudents(bd);
} catch (Exception e) {
e.printStackTrace();
} finally {
bd.close();
}
}
public static void showResult(ObjectSet rs){
System.out.println("Retrieved "+rs.size()+" objects");
while(rs.hasNext()){
System.out.println(rs.next());
}
}
public static void showStudents(ObjectContainer bd){
Query query = bd.query();
query.constrain(Student.class);
query.descend("name");
ObjectSet rs = query.execute();
showResult(rs);
}
}
I just simply want to store a Student in the db4o database but when I want to retrieve all of them it outputs like this:
Student#61070a02
I'm using Eclipse Juno and db40 v.8.0 which I already added as external jar.
Why am I getting those weird characters instead of "Carl"?
That is not weired, but the default implementation of the toString() method. To get meaningfull information you should override this method in your Student class.

HashSet equals, hashCode are overriden, styl have duplicates

public class DateObj extends Date implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String fName;
private String sName;
private String days;
private String country;
private boolean fitIn;
public DateObj(String id,String fName, String sName, String country, String days) {
this.id = id;
this.fName = fName;
this.sName = sName;
this.days = days;
this.country = country;
}
#Override
public boolean equals(Object obj) {
DateObj dateObj = (DateObj) obj;
System.out.println("method Call");
return getfName().equals(dateObj.getfName());
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public String getDays() {
return days;
}
public void setDays(String days) {
this.days = days;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String toString(){
return fName;
}
#Override
public int hashCode() {
return fName.hashCode();
}
}
==========================================================================================
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.TreeSet;
public class DataSaveTo {
private ArrayList<DateObj> listData = new ArrayList<DateObj>();
File file = new File("data3.csv");
public static void main(String[] args) {
DataSaveTo dataExperiment = new DataSaveTo();
dataExperiment.go();
}
public void go() {
loadData();
TreeSet<DateObj> data = new TreeSet<DateObj>();
data.addAll(listData);
// ObjComparInt comparId = new ObjComparInt();
// ObjectComparable comparObj = new ObjectComparable();
// Collections.sort(listData, comparId);
saveData();
// System.out.println(listData);
}
public void saveData() {
try {
File file = new File("dataNoDupl.csv");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
for(DateObj obj : listData){
bw.write(obj.getId()+";"+obj.getfName()+";"+obj.getsName()+";"+obj.getCountry()+";"+obj.getDays()+"\n ");
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Exception in save Data method: "+ e);
}
}
public void loadData() {
FileReader fr;
try {
fr = new FileReader(file);
String s = null;
String[] tokens;
BufferedReader br = new BufferedReader(fr);
while((s=br.readLine())!=null){
tokens = s.split(",");
createDateObj(tokens);
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("Exception in LoadData method"+e);
} catch (IOException e) {
System.out.println("Exception in LoadData method 2nd catch"+e);
e.printStackTrace();
}
}
private void createDateObj(String[] tokens) {
DateObj obj = new DateObj(tokens[4],tokens[0],tokens[2],tokens[3],tokens[1]);
listData.add(obj);
System.out.println(obj.hashCode()+"--"+obj.getfName()+"--"+obj.getsName());
}
// Name comparator
public class ObjectComparable implements Comparator<DateObj>{
#Override
public int compare(DateObj obj, DateObj obj1) {
return obj.getfName().compareTo(obj1.getfName());
}
}
// ID comparator
public class ObjComparInt implements Comparator<DateObj>{
#Override
public int compare(DateObj ob, DateObj ob1){
return Integer.parseInt(ob.getId()) - Integer.parseInt(ob1.getId());
}
}
}
I want HashSet to call equal method, because of overriden hashCode. And after equals compare,I want to remove duplicates in mine Collection I am passing into the hashSet.
HashSet<DateObj> data = new HashSet<DateObj>();
data.addAll(listData);
In console it prints me out, true (because of sys.out in equals method) but it does not do anything. I styl have duplicates.
With having same fName does not get same hash Value. As you consider sName also while generating hash code.
When you are putting the objects into your HashSet, hash code is generated and your hash code implementation generates hash code according to your fName and sName. On the other hand you are matching only fName in your equal method and get true printed!
First Define when you want to consider your objects same. Use those criteria to match in equals method and also consider them in hashCode method also. Because if two objects are equal, their hash code must to be equal!
The Java documentation of hashCode() states that:
If two objects are equal according to the equals(Object) method, then
calling the hashCode method on each of the two objects must produce
the same integer result.
Your implementation is breaking this rule, and you need to change either the implementation of hashCode() or equals() to fulfill it.
You probably want to update equals():
#Override
public boolean equals(Object obj){
if (obj == null || !(obj instanceof DateObj)) {
return false;
}
DateObj dateObj = (DateObj) obj;
return getfName().equals(dateObj.getfName()) && getsName().equals(dateObj.getsName());
}

Address book that reads and write from a data file

I'm doing a small program an addressbook that allows the user to: add contact, search contact and delete contact. All of this data is read and written to .dat file.
Also, how would you create a layout in the data file, (i.e. name, lastname, address and number)?
I'm terrible at Java and I need to get this done.
My code:
public interface Inter
{
//Interface class
public void addContact();
public void deleteContact();
public void searchContact();
public void readFile();
}
public class Contact
{
static String name;
static String lastName;
static String address;
static String number;
public Contact () { }
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader; // reads from dat file
import java.io.FileWriter; // writes from dat file
import java.io.IOException;
import java.io.InputStreamReader;
public class Phonebook extends Contact implements Inter
{
public static void main(String[] args)
{
} // main
#Override
public void deleteContact() { }
#Override
public void searchContact() { }
#Override
public void addContact()
{
String details = null;
System.out.println("Enter new contact i.e name:number:lastname ");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
try
{
details=in.readLine();
String[] tokens =details.split(":"); // eg david :098:Needham
name= tokens[0];
lastName = tokens[1];
address = tokens[2];
number = tokens[3];
} catch (IOException e1) { }
FileWriter fw = null; // writes contact info to the dat file
try
{
fw = new FileWriter("data.dat");
fw.write(name);
fw.write(lastName);
fw.write(address);
fw.write(number);
} catch (IOException e) { }
BufferedWriter bw = new BufferedWriter(fw);
}
public void readFile() // reads contacts from dat file
{
try
{
BufferedReader in = new BufferedReader(new FileReader("data.dat"));
String str;
while ((str = in.readLine()) != null)
{}
} catch(Exception ex) { }
}
}
Your file format should be a .csv, so it would look like:
name,lastname,address,number,
name,lastname,address,number,
name,lastname,address,number,
I know I shouldn't be posting code for you, but here:
class Contact {
public String name, lastname, address, number;
public Contact(String name, String lastname, String address, String number) {
this.name = name;
this.lastname = lastname;
this.address = address;
this.number = number;
}
public boolean equals(Contact c) {
if(name.equals(c.name) && lastname.equals(c.lastname)
&& address.equals(c.address) && number.equals(c.number))
return true;
return false;
}
public String toString() {
return name+","+lastname+","address+","+number+",";
}
}
public class ContactDriver {
public ArrayList<Contact> contacts = new ArrayList<Contact>();
public static void addContact(Contact c) {
contacts.add(c);
}
public static Contact deleteContact(Contact c) {
return contacts.remove(c);
}
public static int searchContact(Contact c) {
for(int i = 0; i < contacts.size(); i++)
if(contacts.get(i).equals(c))
return i;
return -1;
}
public static void readContacts(String file) throws Exception {
Scanner in = new Scanner(new File(file)).useDelimiter(",");
while(in.hasNextLine()) {
addContact(in.next(), in.next(), in.next(), in.next());
}
}
public static void writeContacts(String fileName) {
FileWriter dest = new FileWriter(fileName);
for(Contact c : contacts)
dest.write(c.toString());
}
public static void main() {
readContacts();
// Do logical stuffs
writeContacts();
}
}
That code is untested, so I'll edit anything that has an error.
Have fun learning more Java!

Categories