Solved

serialization and deserialization

Posted on 2000-04-29
9
392 Views
Last Modified: 2012-06-21
How do you go about serialization and deserialization of the Airplane Class ?

We are still not doing objects in class which is why I am asking this question ,
:JIM YOU THERE :-):

From the problem description, several classes jumped out at me: Airplane, SeatingClass, Seat, and Passenger. Pretty much everything else seemed to be attributes of these four classes.

Airplane knows it two seating classes and provides upper level assistance for the assignment of seats and printing of the passenger manifest.

SeatingClass creates and manages Seats. It can find an unassigned seat of the supplied seating preference      and collaborates in printing the manifest.

Seat knows its occupant of Passenger. It provides a reserve() method for establishing this relationship along with the price charged for the booking. The date of the booking is assumed to be the current date. It collaborates in printing the manifest by providing a toString() implementation appropriate to the task.

Passenger is the occupant. It knows first and last name and provides a toString() method that can be used for adding this detail to the manifest.

These four classes with initial implementation appear below. The final class is the TicketAgent which is where most of your implementation remains to be done. The text prompts, gathering and parsing user input, and acting upon the input need to be added. Object serialization and deserialization becomes fairly simple because all the objects are related to Airplane:

Airplane -- has 2 -- SeatingClass -- has many -- Seat -- has 1 -- Passenger

All the classes implement Serializable so all you have to do is serialize Airplane to a file and you're done. Serialization takes care of traversing the network of objects and getting them all written. I think Date and String are the only jdk objects I used and these both implement Serializable. Deserialize from the file when the program starts and you can work with the objects in memory as you please.

Note that creating a new Airplane creates all the necessary objects except the Passenger objects. These need to be created just prior to reserving a seat as shown in TicketAgent.reserveSeat().

One bell I stubbed in would allow for working with multiple airplanes as chosen by a command line argument which names the file that contains the serialized object Airplane object. You can choose not to implement this.

I hope that I have neither provided too much assistance nor too little. I think that the code is mostly self-explanatory. All the code compiles as is and basically runs -- although the only thing it does is print a manifest of unoccupied seats.

Good luck.
Jim Cakalic

---------- Airplane.java ----------
import java.io.Serializable;

public class Airplane implements Serializable {
    private SeatingClass firstClass;
    private SeatingClass economyClass;

    public Airplane() {
        // create seating classes of fixed size
        economyClass = new SeatingClass(10, 6);
        firstClass = new SeatingClass(5, 4);
    }

    public Seat assignSeat(int seatingClass, int preference) {
        if (seatingClass == SeatingClass.FIRST) {
            return firstClass.assignSeat(preference);
        } else if (seatingClass == SeatingClass.ECONOMY) {
            return economyClass.assignSeat(preference);
        } else {
            return null;
        }
    }

    public void printManifest() {
        System.out.println("First class:");
        firstClass.printManifest();
        System.out.println("Economy class:");
        economyClass.printManifest();
    }

}

---------- SeatingClass.java ----------
import java.io.Serializable;

public class SeatingClass implements Serializable {
    public static final int FIRST = 1;
    public static final int ECONOMY = 2;

    private Seat[][] seats;

    public SeatingClass(int rows, int seatsPerRow) {
        // Technically, we should require seatsPerRow to be even.
        // Assume that it is for this assignment
        seats = new Seat[rows][seatsPerRow];
        for (int i = 0; i < rows; ++i) {
            seats[i][0] = new Seat(Seat.WINDOW);
            for (int j = 1; j < seatsPerRow - 1; ++j) {
                boolean aisle = (j == (seatsPerRow / 2 - 1) || j == (seatsPerRow / 2 + 1));
                seats[i][j] = new Seat(aisle ? Seat.AISLE : Seat.CENTER);
            }
            seats[i][seatsPerRow - 1] = new Seat(Seat.WINDOW);
        }
    }

    public Seat assignSeat(int preference) {
        for (int i = 0; i < seats.length; ++i) {
            for (int j = 0; j < seats[0].length; ++j) {
                Seat seat = seats[i][j];
                if (seat.isPosition(preference) && seat.isReserved() == false) {
                    // Found an unoccupied seat matching the stated preference
                    return seats[i][j];
                }
            }
        }
        // No qualifying unoccupied seats found
        return null;
    }

    public void printManifest() {
        for (int i = 0; i < seats.length; ++i) {
            for (int j = 0; j < seats[0].length; ++j) {
                Seat seat = seats[i][j];
                // This needs a lot of work!!
                System.out.println(i + "-" + j + ": " + seat.toString());
            }
        }
    }

}

---------- Seat.java ----------
import java.io.Serializable;
import java.util.Date;

public class Seat implements Serializable {
    // Seating positions
    public final static int WINDOW = 1;
    public final static int CENTER = 2;
    public final static int AISLE = 3;

    private Passenger passenger;
    private Date bookingDate;
    private float ticketPrice;
    private int position;

    public Seat(int position) {
        this.position = position;
    }

    public boolean isReserved() {
        return passenger != null;
    }

    public void reserve(Passenger passenger, float price) {
        this.passenger = passenger;
        ticketPrice = price;
        bookingDate = new Date();
    }

    public Passenger getPassenger() {
        return passenger;
    }

    public Date getBookingDate() {
        return bookingDate;
    }

    public float getTicketPrice() {
        return ticketPrice;
    }

    public boolean isPosition(int preference) {
        return position == preference;
    }

    public String toString() {
        if (isReserved() == false) {
            return "unoccupied";
        }
        return passenger.toString();
    }
}

---------- Passenger.java ----------
import java.io.Serializable;

public class Passenger implements Serializable {
    private String lastName;
    private String firstName;

    public Passenger(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String toString() {
        return lastName + ", " + firstName;
    }

}

---------- TicketAgent.java  ----------
public class TicketAgent {
    Airplane airplane;

    public TicketAgent() {
        airplane = new Airplane();
    }

    public void selectFlight(String[] args) {
        // Deserialize airplane from serialized file
        // Maybe take name of file from args?
        // Sets the airplane instance variable
    }

    public void interact() {
        // Loop asking for next choice: reserve seat, print manifest, quit
        // Method doesn't return until quit is chosen
        System.out.println("What do you want to do today?");
        printManifest();
    }

    public void updateFlight(String[] args) {
        // Serialize airplane to file
        // Maybe take name of file from args?
    }

    public void reserveSeat() {
        int seatingClass = SeatingClass.FIRST;
        int seatingPreference = Seat.AISLE;

        // Ask for class and seating preference

        Seat assignment = airplane.assignSeat(seatingClass, seatingPreference);
        if (assignment == null) {
            // apologize because no seats matching the preference
        } else {
            // ask for passenger name
            // set the price for the seat?
            // reserve this seat
            Passenger passenger = new Passenger("John", "Doe");
            float price = 1000.0f;
            assignment.reserve(passenger, price);
        }
    }

    public void printManifest() {
        airplane.printManifest();
    }

    public static void main(String[] args) {
        TicketAgent agent = new TicketAgent();
        agent.selectFlight(args);
        agent.interact();
        agent.updateFlight(args);
    }
}
---------- end ----------
0
Comment
Question by:norfarm
  • 6
  • 3
9 Comments
 
LVL 19

Accepted Solution

by:
Jim Cakalic earned 180 total points
ID: 2763065
Hi, Mike. Good to hear from you again.

I just saw your comment on the previous question about email attempts to me bouncing. I'm not sure that would be. It looks like you have the right address. Why don't you tell me your address and we'll try it the other way around?

As for serialization, its actually very simple for a client perspective. You use ObjectOutputStream.writeObject() to serialize an object and ObjectInputStream.readObject() to deserialize an object. Java streams are split into two primary groups: data sink streams and processing streams. Data sink streams read or write to what you could reasonably think of as terminal points for your data: files, sockets, pipes, or a place in memory -- someplace that 'records' the data. Processing streams perform some sort of operation like buffering, data conversion, or object serialization. To write to a file you use a FileOutputStream. To write an object to a file you use a FileOutputStream wrapped or 'decorated' by an ObjectOutputStream. To read a file you use a FileInputStream. To read an object from a file you use a FileInputStream decorated by an ObjectInputStream. Here is how it looks in code:

    Airplane airplane = <whatever>
    File file = new File("airplane.dat");
    FileOutputStream fos = new FileOutputStream(file);
    ObjectOutputStream out = new ObjectOutputStream(fos);

These four lines construct the the objects we need to write our object to a file named 'airplane.dat'. Now to actually write the object, we need to do this:

    out.writeObject(airplane);
    out.flush();
    fos.close();
    fos = null;
    out = null;

The first method call on ObjectOutputStream requests that the serialization mechanism be invoked on our airplane object. The ObjectOutputStream converts our object to bytes that represent its current state. Because the airplane object refers to other objects that are part of its current state or knowledge, all of the those objects that are reachable from airplane must be written at the same time so as to maintain the relationships between them. Thus the writeObject method serializes the specified object, traverses its references to other objects recursively, and writes them all. ObjectOutputStream.flush() then makes sure that anything that may have been buffered is written to the underlying data sink, and then the FileOutputStream is closed. You've just serialized airplane.

Exactly the reverse process occurs for deserialization. Since you should have a basic understanding of it now, I won't explain it in such excruciating detail. Here's the code to deserialize the airplane object we just finished serializing:

    File file = new File("airplane.dat");
    FileInputStream fis = new FileInputStream(file);
    ObjectInputStream in = new ObjectInputStream(fis);
    Airplane airplane = (Airplane)in.readObject(in);
    fis.close();
    fis = null;
    in = null;

What makes an object serializable? Its class must implement the Serializable interface. The good news is that Serializable is an empty interface. It doesn't contain any method declarations; it's purpose is simply to identify classes whose objects are serializable. You'll notice looking back at Airplane, SeatingClass, Seat, and Passenger, that all of those classes implement Serializable. As a result they are serializable! No more work necessary. The only other objects referenced by Airplane or any of its collaborators are instantiated from Date and String. Those java classes also implement the Serializable interface. As a result, all of the object related to an Airplane are serializable. Meaning the entire network of objects that make up your problem can be written to a file by the simple bit of code that I showed above.

There is more to serialization than this. You can customize the serialization process by implementing additional methods which, if they exist, will be called by the serialization mechanism. You can take even more control by implementing Externalizable and the methods defined by it. And you can prevent sensitive information held by your objects from being serialized. But I think this enough to know for now.

To add this code to your project, you would put the bit to serialize an airplane object into the updateFlight method of TicketAgent and put the deserialization bit into the selectFlight method.

Best regards,
Jim Cakalic
0
 

Author Comment

by:norfarm
ID: 2763219
Thanks for that super fast reply ,we must have been online at the same time.
We have not started objects till this week coming but we were allowed to use objects in the assignment.
I have a couple of questions I'd like to ask of you ,not in this forum so my e-mail is

norfarm@primus.com.au,

see if you can email me and i should be able to respond without it bouncing around 17 times as it has been doing.

I'll need some time to print out everything again and see if i still have problems (how long have you been into java, you sure seem to know your way around :-)
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2764042
I've been having trouble getting onto my mail server at work all weekend. Maybe they took it down for some sort PM or upgrade? I'm sure that it will be back up by tomorrow so if we both try we might have some luck.

I've been developing software for about 17 years now but only for a little more than 1 year in Java. Most of what I know is because I get up around 5am, read/work/experiment for 2-3 hours before work, and then do the same thing at night after I get the family in bed. I've always tried to take the initiative for learning anything I don't know. If I have a question, I go find the answer. Sometimes other people have the same questions so my research proves to be useful. It also helps to keep references like the online Java Tutorial and JDK documentation handy :-)

Best regards,
Jim Cakalic
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2766584
Mike, I sent you email. Let me know if you don't get it.
Jim
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:norfarm
ID: 2766740
Just got your email 4.00am,
I work part time on the family farm and whish i had the energy to get up at 5 study, work, go to uni ,do my other studies and keep on going till late after dinner. Mayhaps I could with a little more effort :-) I really enjoyed Visual Basic , I think Java is making me think about better programming style.
0
 

Author Comment

by:norfarm
ID: 2779465
Adjusted points from 100 to 150
0
 

Author Comment

by:norfarm
ID: 2779466
Jim, had a computer crash,(brand new celeron 450 32meg TNT2 vid card etc etc.

could u email me please,

norfarm@primus.com.au

hope to hear from you when u get the time.

Mike.
0
 

Author Comment

by:norfarm
ID: 2786704
Adjusted points from 150 to 180
0
 

Author Comment

by:norfarm
ID: 2786705
Great help from Jim. Tripple AAA rating
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now