Client-server. How to transfer to the client, a custom class? - java

I need reading data from database(MySQL) and transfer to client.
Can i somehow transfer the Object of type TopickOfVote to the client or only through String?
Writer and reader:
writer = new PrintWriter(new OutputStreamWriter(clientAPP.getWriter()));
reader = new BufferedReader(new InputStreamReader(clientAPP.getReader()));
Server:
private void LoadOfTopics() throws SQLException {
resultSet = statement.executeQuery("SELECT * FROM kursach.TopicOfVote");
StringBuffer id;
StringBuffer topic;
while(resultSet.next()){
TopicOfVote topicOfVote = new TopicOfVote();
topicOfVote.setId(Integer.parseInt(resultSet.getString("idVote")));
topicOfVote.setTopic(resultSet.getString("topic"));
ResultSet ans = statement.executeQuery("SELECT * FROM kursach.Answers_vote WHERE idVote=" + topicOfVote.getId());
ArrayList<Answer> answers = new ArrayList<>();
while (ans.next()){
Answer answer = new Answer();
answer.setId(Integer.parseInt(ans.getString("idAnswer")));
answer.setAnswer(ans.getString("answer"));
answer.setIdOfTopic(Integer.parseInt(ans.getString("idVote")));
answers.add(answer);
}
topicOfVote.setAnswers(answers);
writer.println(topicOfVote); // ???
writer.flush();
ans.close();
}
}
Client:
private void createPanelTopics(){
try {
writer.println(HandlerQueries.GET_VOTES + "?");
writer.flush();
reader.readLine();//?????
} catch (IOException e) {
e.printStackTrace();
}
}

Can i somehow transfer the Object of type TopickOfVote to the client
Yes, with Object Serialization, provided TopickOfVote implements Serializable and does all the other right things associated, such as defining a private static final long serialVersionUID, and doesn't evolve incompatibly.
or only through String? Writer and reader:
Yes, with XML, JSON, ...

Related

Java List serialization

I have written a java program that needs to save a list of an Object I created called User. This is my code for saving and loading the list:
/**
* Save list to file
* #param saveList list to be saved
*/
public void saveUsers(List<User> saveList){
try{
FileOutputStream fileOut = new FileOutputStream("data/userlist.ser", true);
OutputStream out = new BufferedOutputStream(fileOut);
ObjectOutput output = new ObjectOutputStream(out);
output.writeObject(saveList);;
out.close();
fileOut.close();
output.close();
for(User u : saveList){
System.out.println(u.getUsername());
}
System.out.println("List written to file");
}catch(IOException e){
e.printStackTrace();
}
}
/**
*
* #return list of all users in system.
*/
#SuppressWarnings({ "resource", "unchecked" })
public static List<User> loadUsers(){
try{
InputStream saveFile = new FileInputStream("data/userlist.ser");
InputStream buffer = new BufferedInputStream(saveFile);
ObjectInput input= new ObjectInputStream(buffer);
LinkedList<User> loadList = (LinkedList<User>) input.readObject();
System.out.println(loadList.size());
for(User u : loadList){
u.reload();
System.out.println(u.getUsername());
}
return loadList;
}catch(Exception e){
e.printStackTrace();
}
List<User> l = new LinkedList<User>();
return l;
}
And my code seems to work for save because the output each time it is called shows all the users being added to the list, however on the load it only loads the first User. This is my user class:
public class User implements Serializable{
/**
* Variables
*/
private transient StringProperty usernameProperty;
private String username;
private List<Album> albums = new LinkedList<Album>();
private List<Photo> photos = new LinkedList<Photo>();;
private List<Tag> tags = new LinkedList<Tag>();;
private static final long serialVersionUID = 1738L;
/**
* public constructor to create a user
* #param username
*/
public User(String username){
this.username = username;
this.usernameProperty = new SimpleStringProperty(username);
}
And all of my other classes are implementing the Serializable as well. Is there any reason the list is being saved to the file but not loading fully?
I figured out the answer, apparently every time I was calling the save class, I was not overwritting the file but appending to it, so I was only reading the first array list being stored, pretty simple fix I just added the lines
File file = new File("data/userlist.ser");
file.delete();
to the beginning of my saveUsers function to clear the file, now it works perfectly.
Change LinkedList loadList = (LinkedList) input.readObject(); to ArrayList. Edit the file userlist.ser delete the contents or create a new file and use it in your code. It works fine for me.
Finding the error in your code is for me more complex than testing my own solution, so I have made a quick model for you, using a the same classes you use, but using a custom class (car) for this...
the Code:
public static void main(String[] args) throws Exception {
final Car c0 = new Car("bmw", 1990);
final Car c1 = new Car("VW", 2000);
final Car c2 = new Car("Audi", 2010);
final Car c3 = new Car("Mini", 2015);
final LinkedList<Car> lisCar = new LinkedList<Car>();
lisCar.add(c0);
lisCar.add(c1);
lisCar.add(c2);
lisCar.add(c3);
serialThis(lisCar);
deserializeFileToList();
}
Serialize to file:
private static void serialThis(LinkedList<Car> lisCar) throws Exception {
final FileOutputStream fos = new FileOutputStream("serialized.txt");
final ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(lisCar);
oos.close();
}
Deserialize from file:
private static void deserializeFileToList() throws Exception {
final FileInputStream fis = new FileInputStream("serialized.txt");
final ObjectInputStream ois = new ObjectInputStream(fis);
final LinkedList<Car> ds = (LinkedList<Car>) ois.readObject();
ois.close();
System.out.println(ds);
}
The Car class:
private static final long serialVersionUID = -427928246789764110L;
#Override
public String toString() {
return "Car [year=" + year + ", type=" + type + "]";
}
private final int year;
private final String type;
public Car(String type, int year) {
this.type = type;
this.year = year;
}

Java - InvalidClassException local class incompatible serialVersionUID

I created a client application that gets some data from the database (Oracle) and serialized them. With some data (happens once in 100), when serialized a data, fails with this exception:
Exception in thread "main" java.io.InvalidClassException: org.jdom.Element; local class incompatible: stream classdesc serialVersionUID = -5756298698047880134, local class serialVersionUID = -1584223699423688446
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:621) at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:621)
The data are inserted in the database with other application.
Looking at Google, I see that maybe should define a serialVersionUID. I do it (Im not entirely sure that it´s correctly) but is not resolved. My code:
public class Test1{
/(private static final long serialVersionUID = -5756298698047880134L;//-1584223699423688446L
public static void main(String[] args) throws Exception {
// TODO code application logic here
ExecutionContext ret = null;
System.out.println("Connection with BD...");
String url = "url";
String user = "user";
String password = "password";
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Connection ok...");
System.out.println("Create Query...");
String query = "SELECT ... FROM ...";
Statement st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery(query);
if (rs.next()) {
Blob blob = rs.getBlob("EXECUTION_CONTEXT");
if (blob == null) {
System.out.println ("Blob null");
}
try{
InputStream is = blob.getBinaryStream();
GZIPInputStream gzip = new GZIPInputStream(is);
ObjectInputStream os = new ObjectInputStream(gzip);
//Here is where fail:
ret = (ExecutionContext)os.readObject();
//
}catch(ZipException ie){
if(ie.getMessage().equals("Not in GZIP format")){
System.out.println("Not in GZIP format");
InputStream is = blob.getBinaryStream();
ObjectInputStream os = new ObjectInputStream(is);
//Here is where fail:
ret = (ExecutionContext) os.readObject();
//
}else{
JOptionPane.showMessageDialog(null, "Error when extracting data");
}
}
}
}
}
Any idea?
EDIT with the solution:
In the ExecutionContext class that I pick the serialize object, in this class must implement Serializable and define serialVersionUID.
ret = (ExecutionContext) os.readObject();
The serialVersionUID needs to be defined with the same value as in the stream: -5756298698047880134.
You must have deployed two different versions of the JDOM library.

writing object to internal storage

I have succeeded in writing and reading a string to a file on my android app's internal storage, but I want to write an object and it's not working. I've read Oracle's documentation on the matter, which says for object fields to be transmitted over the stream the object needs to implement serializable, or something. I added imports serializable and implements serializable to the cat class but it threw an error. Without it "oos.writeObject(myCat);" causes an error too. I'm very confused.
The below code exists in a java activity class tied to a layout.xml. The user presses a button and the object is saved or loaded. As stated writing and reading a string seems to work fine, but objects less so.
private void writeFile()
{
try
{
String myFile = "myFile";
cat myCat = new cat("Harry", "blue", 11);
FileOutputStream fos = openFileOutput(myFile,MODE_WORLD_READABLE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(myCat);
oos.close();
fos.close();
Toast.makeText(getBaseContext(),"object saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
And
private void readFile()
{
try
{
String myFile = "myFile";
FileInputStream fis = openFileInput(myFile);
ObjectInputStream ois = new ObjectInputStream(fis);
cat yourCat = (cat) ois.readObject();
ois.close();
fis.close();
String output = yourCat.name + " the " + yourCat.colour + " cat";
Toast.makeText(getBaseContext(),output,Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
}
}
The cat object
public class cat
{
public String name = "";
public String colour = "black";
public int age = 0;
public cat(String pName, String pColour, int pAge)
{
name = pName;
colour = pColour;
age = pAge;
}
}
Adding "implements Serializable" to the cat class works. I'm not sure why it didn't in the first place. Sorry for the fuss.
Try using:
MODE_PRIVATE
In the openFileOutput() method.

ObjectOutputStream won't save my arrayList

I have this arrayList in my UserArchive class, and a saveFile() method in my MainWindow class.
My problem is that every time I close the program all that shows in src/customerlist.txt is:
¨ÌsrUserArchiveYï≈ùÅ—ÀDLlisttLjava/util/ArrayList;xpsrjava.util.ArrayListxÅ“ô«aùIsizexpw
x.
Heres my code: Can anyone spot any problems?
public class UserArchive implements Serializable {
ArrayList<User> list = new ArrayList<User>();
public void regCustomer(User u) {
list.add(u);
}
public String toString() {
sorter();
String users = "";
Iterator<User> iterator = list.iterator();
while (iterator.hasNext()) {
users += iterator.next().toString() + "\n";
}
return users;
}
MainWindow class:
public class MainWindow extends JFrame {
private SaleWindow sW;
private UserArchive userA;
int customerID = 0;
////
public void saveFile() {
try {
FileOutputStream outStream = new FileOutputStream(
"src/customerlist.txt");
ObjectOutputStream utfil = new ObjectOutputStream(outStream);
utfil.writeObject(userA);
utfil.close();
} catch (NotSerializableException nse) {
JOptionPane
.showMessageDialog(this, "Objektet er ikke serialisert!");
} catch (IOException ioe) {
JOptionPane
.showMessageDialog(this, "Problem med utskrift til fil!");
}
}
Yes because ObjectOutputStream serializes objects in binary form. If you want serialize in some ASCII form try a JSON Serializer for example Jackson.
Please take a look at Javas serialization mechanismn. You're not writing the String content but the String objects (and the sourrounding list) in their binary form.
ObjectOutputStream is the wrong choice if all you want to do is write a plain text file. Take a closer look at java.io.FileWriter or java.io.PrintWriter.

Java serialization of transient fields

I am reading Thinking in Java 4th Edition.
There described a strange workaround for serialization of transient fields:
import java.io.*;
public class SerializationTest implements Serializable {
private String firstData;
//transient field, shouldn't be serialized.
transient private String secondData;
public SerializationTest(String firstData, String test2) {
this.firstData = firstData;
this.secondData = test2;
}
/**
* Private method, same signature as in Serializable interface
*
* #param stream
* #throws IOException
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(secondData);
}
/**
* Private method, same signature as in Serializable interface
*
* #param stream
* #throws IOException
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
secondData = (String) stream.readObject();
}
#Override
public String toString() {
return "SerializationTest{" +
"firstData='" + firstData + '\'' +
", secondData='" + secondData + '\'' +
'}';
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("object.out");
oos = new ObjectOutputStream(fos);
SerializationTest sTest = new SerializationTest("First Data", "Second data");
oos.writeObject(sTest);
} finally {
oos.close();
fos.close();
}
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("object.out");
ois = new ObjectInputStream(fis);
SerializationTest sTest = (SerializationTest) ois.readObject();
System.out.println(sTest);
} finally {
ois.close();
fis.close();
}
//Output:
//SerializationTest{firstData='First Data', secondData='Second data'}
}
}
As you can see, there are implemented private methods writeObject and readObject.
The questions are:
For what ObjectOutputStream and ObjectInputStream are using Reflection for accessing private methods ?
How many back doors like this are included in the Java ?
Backdoor? It's always been in the spec. It is the only way to implement non-default serialization of an object.
Non-default serialization puts you in the serialization driver's seat. You can write whatever to the output stream and as long as you can read it back and construct your object on the other end of the stream, you'll be ok.
The fact that this person decided to serialize transient fields is just not the issue, the point is that you can do whatever you want if you are implementing your own serialization scheme.
Erm, it isn't a "backdoor" ... you implemented a custom serialization that output the transient fields to the output stream after calling the default serialization which ignored them.
The Serializable interface is marker interface. So its like a tag to explain the java compiler. There are other marker interfaces like Clonable, etc. See here for more.
However now a days #annotations are used more.

Categories