Externalizable vs DataOutputStream/DataInputStream (Storable Interface)

I have created an interface Storable as below which I use to save a complex Object to a byte array and ultimately to a database. The total processing time is 1hour and 5 minutes.
public interface Storable
     void readData(DataInputStream in) throws IOException;
     void writeData(DataOutputStream out) throws IOException;
I then swapped to Externalizable.
I changed the top Object readData/writeData functions to
readExternal and writeExternal.
Then I added new readData/writeData functions to the contained Objects
as below - so these objects are "new"ed and filled in by my code.
void readData(InputObject in) throws IOException;
void writeData(OutputObject out) throws IOException;
Total processing time was reduced to 33minutes.
Can anybody explain this >50% speed improvement?
Also I would rather not use Externalizable so I can decouple the persisted data away from the Java code but it looks like one heck of a time penalty for doing so.

The point is the only difference between the code I have written is that one is using
ObjectInput/ObjectOutput (Externalizable) (34 minutes)
the other is using
DataOutputStream/DataInputStream (Storable) (1hour 5 minutes)
and my code for the 2 methods is basically the same.
This would lead to the conclusion that one of or both Java classes DataOutputStream/DataInputStream are very inefficient and I want to know why?

Similar Messages

  • DataOutputStream / DataInputStream   ( Losing information? )

    I have written a client server program. The client program establishes a URL connection to a ServerSocket. I am using a DataOutputStream to pass a large amount of data back to the client. The problem is that it appears that every now and then a byte is skipped or lost. Here is the important part of the code. (psudo) This loss appears to happen when I read the bytes into the Buf Array.
    On the ServerSide :
    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
    while (notcomplete){
           dos.writeInt(acuiredInt);
           dos.writeLong(acuiredLong);
            byte[] acuiredBuf ;
            for(int i=0; i < acuiredBuf; i++)
                      dos.writeByte( acuiredBuf) ;
    On the Client Side
    DataInputStream dis = new DataInputStream(new BufferedInputStream(os));
    while (notcomplete){
           dis.readLong(acuiredLong);
           dis.readInt(acuiredInt);
            byte[] acuiredBuf  = new byte[1024];  //always the same size
            for(int i=0; i < acuiredBuf; i++)
                      dis.readByte( ) ;
    }I know that one byte is being lost because I tried to send the same int value acros constantly, and then instead of calling readInt, i called readByte four times (four bytes of an int) , and gradually everytime the mysterios 'loss' happend, the values would shift. See my example:
    Should Be:  
                  1    =>       0 , 0 , 0 , 10      
                  2    =>       0 , 0 , 10 , 020 
                  3    =>       0 , 10, 152, 102    etc. 1 <= This displays lets say 500 times and is the correct Representation of the int then...
    2 <= The 020 is not correct, it should be like the line above. This means that the first 0 has disapeared. (But when i check the last entry in the Buf, the 0 is there) . Afer even some more time it becomes the 3rd line. and the first two zeros are the last two entries in the Buf array.
    So i dont' know if i'm losing information? Using the streams wrong, or how to fix it. All i want to do is pass a large amount of information from the server to the client.
    Any help would be greatly appreciated.

    In your loop, what aren't you checking the byte array's length rather than comparing against the byte array itself? Does that even compile? Post the actual code that is having issues.
    Also, flushing after writing a single byte is a huge waste. Flush after a 'message' from the client is complete to send to the server and vice versa.
    - Saish

  • Using DataOutputStream/DataInputStream

    Hi, evveryone.
    I'm needing to use an applet, and this applet uses the following code.
    URL hp = new URL(stringURL);
    URLConnection hpCon = hp.openConnection();
    DataOutputStream dataoutputstream = new DataOutputStream(hpCon.getOutputStream());
    dataoutputstream.writeBytes(DataToSend);
    dataoutputstream.flush();
    dataoutputstream.close();
    DataInputStream datainputstream = new DataInputStream(hpCon.getInputStream());
    Mydoubts are:
    One: the URL used in URLConnection can be an asp page that uses JavaScript, or it must be an pure HTML, or an CGI, etc...
    Two: how, in this URL, can I retrieve the information of DataOutputStream ( I think that is through Request.DataInputStream, but I'm not sure, though ) , and then parse it to a String?
    Third: How I must sent the information that the Applet is waiting ( by an DataInputStreamReader ) back to it? The information is a String.
    Thanks,
    Mivil

    The Usage of URL objects can be facilitated by the following code.
    * Connect to the aURL use the aQueryString
    * as the request parameters and return the
    * data Stream.
    public static InputStream getHTTPResponse(String aURL, String aQueryString) throws MalformedURLException, IOException
    URL url = new URL(aURL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    if (aQueryString != null)
    PrintWriter out = new PrintWriter(connection.getOutputStream());
    out.println(aQueryString);
    out.close();
    return connection.getInputStream();
    * Connect to the aURL use the aQueryString
    * as the request parameters and return the
    * String response (when expected).
    public static String getHTTPResponseString(String aURL, String aQueryString) throws MalformedURLException, IOException
    InputStreamReader ipstr = new InputStreamReader(getHTTPResponse(aURL, aQueryString));
    BufferedReader reader = new BufferedReader(ipstr);
    String inputLine;
    StringBuffer sbuf = new StringBuffer();
    while ((inputLine = reader.readLine()) != null)
    sbuf.append(inputLine);
    reader.close();
    ipstr.close();
    return new String(sbuf);
    Regards

  • Input-/ouputStream hanging

    Hi all.
    I'm having some trouble with sending an XML-file via outputstream.
    I think the problem is, that the receiving part, a SAXBuilder, doesn't recognize any end of file in the incoming data, and therefore keeps reading. My assumption is based on the fact, that if the sender's outputstream is closed, the receiver reads everything just fine. Flushing the stream doesn't appear to have any effect.
    How do I avoid this? Is it perhaps possible to communicate an EOF after sending the document?
    ServerConnection (sender):
    import java.io.*;
    import java.net.*;
    import java.net.InetAddress;
    import java.util.ArrayList;
    import fsr.universal_classes.Customer;
    import java.math.BigDecimal;
    import org.jdom.*;
    import org.jdom.output.Format;
    import org.jdom.output.XMLOutputter;
    public class ServerConnection implements Runnable{
        private InetAddress hostname;
        private int portNumber;
        private Socket connection;
        private BufferedWriter out;
        private BufferedReader in;
        private boolean connected = false;
        private String threadName = "ServerConnection";
        public ServerConnection(){
            new Thread(this).start();
        @Override
        public void run(){
            connectToDatabase();
        private synchronized void connectToDatabase(){
            portNumber = 49352;
            try {
                hostname = InetAddress.getLocalHost();
            } catch (UnknownHostException ex) {
                threadMessage("Couldnt find local host");
            try {
                connection = new Socket(hostname, portNumber);
                connected = true;
                out = new BufferedWriter(new PrintWriter(connection.getOutputStream(),true));
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            catch (IOException e) {
                System.out.println(e);
                connected = false;
        public ArrayList<Customer> getCustomers(){
            //  Create XML
            Element root = new Element("request");
            Element subject = new Element("subject");
            subject.setText("getAllCustomers");
            root.addContent(subject);
            // Create document and set DocType
            Document doc = new Document();
            doc.setRootElement(root);
            DocType xmlDoctype = new DocType("request", "src/commands.dtd");
            doc.setDocType(xmlDoctype);
            // Send XML
            XMLOutputter outputter = new XMLOutputter();
            outputter.setFormat(Format.getRawFormat());
            try {
                outputter.output(doc, out);
                out.flush();
            } catch (Exception e) {
                System.err.println("Exception: " + e);
            ArrayList<Customer> customersList = new ArrayList();
            return customersList;
        public void threadMessage(String message){
            System.out.println(threadName  + ": " + message);
    Session (Receiver):
    import java.net.*;
    import java.io.*;
    import fsr.server.exceptions.SessionStoppedException;
    import org.jdom.Document;
    import org.jdom.JDOMException;
    import org.jdom.input.SAXBuilder;
    public class Session implements Runnable{
        private Socket socket;
        private int id;
        private TCPServer tcpServer;
        private boolean connected = true;
        private SAXBuilder documentBuilder;
        private String threadName = "Session";
        public Session(Socket socket, int id) {
            this.tcpServer = TCPServer.getInstance();
         this.socket = socket;
            this.id = id;
            new Thread(this).start();
        @Override
        public void run() {
         try {
                communicate();
            catch(SessionStoppedException e){
                threadMessage("Session stopped: " + e.getError());
            catch(Throwable t){
                threadMessage("Session stopped (2)");
        public void communicate() throws SessionStoppedException {
            InputStreamReader ins;
            try {
                threadMessage("Getting input Stream");
                ins = new InputStreamReader(socket.getInputStream());
            catch (IOException e) {
                throw new SessionStoppedException("No info");
            while(connected){
                try {
                    BufferedReader in = new BufferedReader(ins);
                    threadMessage("Creating sax builder");
                    documentBuilder = new SAXBuilder(true);
                    threadMessage("Building document");
                    Document doc = documentBuilder.build(in);
                    System.out.println("Received: " + doc.toString());
                    // If there are no well-formedness or validity errors,
                    // then no exception is thrown.
                    System.out.println(doc + " is valid.");
                    System.out.println(doc.getRootElement().getName());
                // indicates a well-formedness or validity error
                catch (JDOMException e) {
                    System.out.println( "is not valid.");
                    System.out.println(e.getMessage());
                catch (IOException e) {
                    System.out.println("Could not check " );
                    System.out.println(" because " + e.getMessage());
                catch(Exception e){
                    threadMessage("Error: " + e);
        public void threadMessage(String message){
            System.out.println(threadName + "(" + id + ")" + ": " + message);
    }Thanks in advance.
    Cheers,
    Jonas

    Jonas.Nielsen wrote:
    I've been instructed, that there is no way to send a end of file.
    What would probably help would be to send the size of the serialized document before sending the actual document. But how is that done?First, you should probably be using the stream directly, not wrapping it in a Writer, so you can write byte-oriented data. Then, if you knew the size of the document ahead of time, you could send the number of bytes as a long, followed by the document. If you don't know the number of bytes ahead of time, you could come up with some chunking protocol, where you would write the size of the chunk, followed by the chunk bytes. A chunk size of 0 could indicate EOF.
    The DataOutputStream/DataInputStream wrapper classes can be of assistance here.

  • Java Project

    Hi, My name is Francisco, I am new in Java and have this project due this week can someone really help me, I am really struggling with this project. I am using IDE (NETBEANS) for developing this application. I really appreciate if someone can help me. Below is the project requirements.
    Thank so much.
    This practical work is to write a media management software suite. It stores details of your photos, music and movies (at least these three).
    There is a need to standardise three names for software swapping. You should adhere to the following:
    * the front end package should be called frontend
    * the back end package should be called backend
    * the interfaces Storage and Storable to be declared in a separate package called utilities
    * the primary class implemented in the back end (the one that implements storage) should be called Database
    You should spell these identifiers exactly as above, otherwise your frontend/backend will not swap with other components.
    Detail
    The project must be written using two separate packages, a front end and a back end. The front end interfaces with the user, takes input requests and returns results. Typical commands would be:
    * add/photo
    * add/soundTrack
    * search all for titles containing "river"
    * seacrh all for artist containing "river"
    * delete a particvular item.
    Each entry in the system should have a title, date of entry and notes. Additionally, music should have an artist, and movies should have a length of movie entry.
    The back-end provides the storage, and will simply use a Vector, configured as a Vector<Entry> or similar. This separation of systems in to front and back end (user interface and the database) is a common feature of modern large-scale software.
    Interfacing
    The front end and the back end will "talk" to each other using an interface. This interface will be standard and is specified here. This interface will be extended during the next week, but will be fixed after the lecture on October 25th.
    Classes to be stored in the back-end will implement the Storable interface. It may be a tagging interface, but designers may extend it as required.
    interface Storable {
    // designers may add requirements here
    The main back-end class will implement the Storage interface. It must not be modified after the due date for setting it (you will find out why later).
    interface Storage {
    void add(Storable s);
    void delete(Storable s);
    void saveDatabase(String s); // saves database to file specified by String
    void loadDatabase (String s); // load the database
    // iterate through the database
    void reset(); // reset
    boolean hasMore(); // if there is another element available for the next() method
    Storable next(); // get the next item
    Input/output
    Output (display to the user) should be on-screen using JFrames, JPanels etc. You should mainly write text [g.drawChars("... ], but a bit of colour (a graphic in a separate JPanelto distinguish photos from music etc) is a requirement.
    Input should be using the Scanner class.
    You can improve the input & output by adding GUI components (buttons, textboxes etc) either by directly using Swing components or by using the Form generator in Netbeans. But if you do this, then it's up to you. In particular, event handling in Java -which you will need to understand if you use the Swing components directly - is fairly complex (but well covered in the tutorial). Note that the full GUI interaction - including event handling - is covered in HIT212.
    Options
    For small amount of extra marks:
    * Input using JOptionPane (see API and tutorial)
    * Input using a text box (see Using Text Components in the Java tutorial).
    * Using buttons etc (the full GUI)
    It will jazz your presentation up, but if you want to avoid a bit of extra research, or are having trouble with the concepts, avoid the last two options. The full GUI is taught in the next subject and - in particular - you will have to understand Java's model for event-handlers and event-listeners. It's all in the tutorial, but will not be discussed in class or tutorials.
    Saving the database
    Assuming the database is saved as a Vector of Storables, the whole Vector may be saved by defining an ObjectOutputStream:
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/..."));
    The Vector (assume it is called store) is then put to disc by the following code:
    oos.writeObject(store);
    oos.close();
    Reading the database back in is as simple. Just define an ObjectInputStream. See the API (ObjectOutputStream, ObjectInputStream) for details.
    [Hint: Not all Objects can be written to disc - for security, by default objects cannot be written to disc. If a designer intends objects to be written, they must implement the tagging interface Serializable. Look up Serializable in the API]
    Requirements
    * Storage must be implemented using a Vector.
    * There must be two distinct packages - backend and frontend. These must be implemented as Java packages.
    * All classes to be stored must implement the Storable interface (which may be modified)
    * The back end must implement the Storage interface (which cannot be modified).
    * Group size of one or two. Individuals can identify the code areas they primarily wrote.
    Marking criteria
    The following criteria will be used
    * Good coding style, methods short and clear, good variable naming, follows Java naming conventions
    * Interfaces used as specified. All front-end/back-end communication enforced through the storage class

    Don't sit on your thumbs waiting for magic to happen. Also, nobody here is going to do your homework for you. If you have some succinct, specific, java-related questions you might get somewhere. As it is right now, you're going nowhere in a hurry.

  • Is it good habit to use "Instanceof"

    Is good habit to use "Instanceof" for selection purpose. Below code will make it more clear.
    public boolean entryAdd(Object obj) throws SQLException
         String sSQL="";
         if (obj instanceof cT )
             cTeacher oT = (cT)obj;
             sSQL = "INSERT INTO tblT VALUES(";
             sSQL = sSQL + String.valueOf(getNextID("TID","tblT"));
             sSQL = sSQL + ",'";
             sSQL = sSQL + oT.Name + "','";
             sSQL = sSQL + oT.Qualification + "','";
             sSQL = sSQL + oT.Description + "')";
         }else if(obj instanceof cS)
             cS oS = (cS)obj;
             sSQL = "INSERT INTO tblS VALUES(";
             sSQL = sSQL + String.valueOf(getNextID("SID","tblS"));
             sSQL = sSQL + ",'";
             sSQL = sSQL + oS.Name + "','";
             sSQL = sSQL + oS.Code + "','";
             sSQL = sSQL + oS.Description + "')";
         }elseif(.){...
         else
             return false;
         Statement oStmt = getStatement(EnumDBType.UPDATEABLE);
         oStmt.execute(sSQL);
         oStmt.close();
         return true;
        }Well, in C++ we have enum. Which can be given as arg. when function is called. So,it is easy for caller and for us to get only values we want in arg. But, in java, we don't have this kind of feature(excluding J1.5).
    So, should I be using above method for identifying object and taking action. Or should I declare Interface with all the costants for all the classes which i expect and take int as an argument. and tell caller to send one of the constant declared in interface. And using switch statement I take action.one of the constant declared in interface.
    So, I am looking for good programming method of doing above task.

    But, don't
    you think "UlrikaJ" way is more straight forward.
    Please give your suggestion.Ulrika's method, simple having every SQLStorable is certainly a very good way in simple cases.
    The only complaint I would have is that SQL is a different domain of knowledge than whatever it is that the storable class is supposed to be doing. Suppose it changed. Suppose you decided to use a different persistence mechanism. Would you add XMLStorable and RMIStorable and whatever else to every class in you system?
    Double-dispatch addresses this problem, but at the cost of having one class with comprehensive knowledge of every other class in the system.
    A more general solution would be to have each class be able to describe itself (either by implementing a Storable interface, with method that could tell a SQLStorer, an XMLStorer, or whatever, how to store it, or by using Annotation to save the same information).
    Plus, although this is somewhat of topic, as a visitor from the Generics forum, I want to point out that using StringBuffers and string concatenation is distinctly old-hat. Going forward, you could writ:public String apply (CT ot) {
        return String.format("INSERT INTO tblT VALUES(%d, %s, %s, %s)",
                             getNextID("TID","tblT"),
                             ot.name,
                             ot.qualification,
                             ot.description);
    }which is quite a bit cooler.

  • Use of Externalizable Interface

    Hi All,
    can any of you please tell me that what is the exact use of Externalizable Interface and when do we need to use Externalizable instaed of Serializable.
    Thanks in advance.

    Use the Externalizable interface when you need complete control over your Bean's serialization.
    For example, you want to make a serialization process into a different file format ( file content structure)
    Regards,
    Alan Mehio
    London,UK

  • DataInputStream / DataOutputStream  - PS  How do i offer my duke dollars?

    I have written a client server program. The client program establishes a URL connection to a ServerSocket. I am using a DataOutputStream to pass a large amount of data back to the client. The problem is that it appears that every now and then a byte is skipped or lost. Here is the important part of the code. (psudo) This loss appears to happen when I read the bytes into the Buf Array.
    On the ServerSide :
    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
    while (notcomplete){
           dos.writeInt(acuiredInt);
           dos.writeLong(acuiredLong);
            byte[] acuiredBuf ;
            for(int i=0; i < acuiredBuf; i++)
                      dos.writeByte( acuiredBuf) ;
    On the Client Side
    DataInputStream dis = new DataInputStream(new BufferedInputStream(os));
    while (notcomplete){
           dis.readInt(acuiredInt);
           dis.readLong(acuiredLong);
            byte[] acuiredBuf  = new byte[1024];  //always the same size
            for(int i=0; i < acuiredBuf; i++)
                      dis.readByte( ) ;
    }I know that one byte is being lost because I tried to send the same int value acros constantly, and then instead of calling readInt, i called readByte four times (four bytes of an int) , and gradually everytime the mysterios 'loss' happend, the values would shift. See my example:
    1 => 0 , 0 , 0 , 10
    2 => 0 , 0 , 10 , 020
    3 => 0 , 10, 152, 102
    4 => 10 , 82, 152, 102 etc.
    1 <= This displays lets say 500 times and is the correct Representation of the int then...
    2 <= The "020" is not correct, it should be like the line above it. This means that the first 0 has disapeared. (But when i check the last entry in the Buf, the 0 is there) . Afer even some more time it becomes the 3rd line. and the first two zeros are the last two entries in the Buf array.
    So i dont' know if i'm losing information? Using the streams wrong, or how to fix it. All i want to do is pass a large amount of information from the server to the client.
    Any help would be greatly appreciated.

    I know it is not the real code, thats why i said it was psueudo code, because it. For a better explanation of the problem please could you check:
    http://forum.java.sun.com/thread.jspa?threadID=707296&tstart=0

  • What is the use of Externalizable interface?

    What is the use of Externalizable? and what is the diff b/w Serializable and Externalizable interfaces?

    What is the use of Externalizable?Read the API docs, they explain it.
    and what is the
    diff b/w Serializable and Externalizable interfaces?Well, read the API docs of Serializable, too, and then find the difference.

  • Why we need externalizable interface in java

    Hi friends,
    I know the Concept of serliazation and externalization, apart from this concept i have one doubt about externalization, I feel both are doing same work. Then what is the nedd of externalizable interface. Can anyone tell what is the difference of Serialization ans Externalization, if both are doing same work.

    Crosspost: http://forum.java.sun.com/thread.jspa?threadID=5226495&tstart=0
    Don't crosspost, it's rude and a waste of time and energy for all involved.
    People on the forum help others voluntarily, it's not their job.
    Help them help you.
    Learn how to ask questions first: http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
    (Yes I know it's on JavaRanch but I think it applies everywhere)
    ----------------------------------------------------------------

  • Difficulties with using DataInputStream and DataOutputStream

    Hello all,
    I need help for understanding what I'm doing wrong here:
    (pass and user are byte[] encrypted with RSA) the problem is that i can;t read what i wrote. :(
    f = new DataOutputStream (new FileOutputStream("file.txt"));
                        f.write(pass);
                        f.write(user);
                        f.flush();
                        f.close();
                        System.out.println ("write pass"+pass);
                        System.out.println ("write user"+user);
                         f2 = new DataInputStream (new FileInputStream("file.txt"));
                        System.out.println("Available bytes"+f2.available());
                        byte [] ru = new byte[64];
                        f2.read(ru,0,64);
                        byte [] rp = new byte[64];
                        f2.read(rp);
                        f2.close();
                        System.out.println( "read user"+ru);
                        System.out.println( "read pass"+rp);//output
    write pass[B@2a4983
    write user[B@406199
    Available bytes128
    read user[B@1b09468
    read pass[B@1df5a8f                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    So you didn't manage to figure it out for yourself - http://forum.java.sun.com/thread.jspa?threadID=5155256&messageID=9587510#9587510 !
    P.S. You need to think more about what you are trying to do and you need to read the Javadoc for DataInputStream and DataOutputStream .
    Message was edited by:
    sabre150

  • Is Externalizable is a marker interface???

    hey,
    What is a marker interface??? it should not have any methods, isn't it???then why is that the interface externalizable called as a marker ???
    can anybody tell me the reason??

    What is a marker interface??? An interface that marks objects that have a certain, usually non-enforcible behaviour. Like Serializable marks objects that are supposed to be defined in a way that they can be serielaized, i.e. no non-transient, non-serializable members.
    it should not have any
    methods, isn't it???It often doesn't, but I don't see why that's a necessity.
    then why is that the interface
    externalizable called as a marker ???
    can anybody tell me the reason??See above, who said it's not allowed to?

  • Is there best way to connect a dataInputStream with a dataOutputstream?

    I use a the next to put data on 'memory'
    ByteArrayOutputStream bytestream =new ByteArrayOutputStream();          
    DataOutputStream datastream =     new DataOutputStream(bytestream);     
    And the method to 'connect' de 'out' with the 'in' is by mean of pass an array :
    ByteArrayInputStream bytestream_in =new ByteArrayInputStream(bytestream.toByteArray());          
    DataInputStream datastream_in =new DataInputStream(bytestream_in);
    Is there any way to do this better ?

    use a the next to put data on 'memory' Jesus ! The data I have on a file now is in memory ....
    Better .... :
    bytestream is already in memory
    bytestream.toByteArray() creates a newly allocated byte array
    If you consider it , it is an additional cost. Is there any way to connect ByteArrayInputStream with ByteArrayOutputStream ??
    By other side, if my bytestream grows I must to 'reload ' ByteArrayInputStream and make a new bytestream.toByteArray() ....
    I hope now you understand me

  • Externalization and interface

    I would like to have a persistent class that holds interface field
    externalized via custom externalization methods.
    ex: I have a persistent class A.
    class A {
    private IFormat format;
    where IFormat is an interface. I want to store the format field via
    externalization to a string. IFormat implemnation must not be persistent
    object.
    The 'externalizer' extension is set to a method of the interface. The
    'factory' extension is set to a factory static method that instantiates an
    object implementing the IFormat interface.
    It seems externalization mechanism works fine if the field has a precise
    class declared type.
    How can i do ?
    Thanks for your help,
    Laurent

    Patrick, I finally managed to do what i wanted by setting the 'type'
    extension of my interface field to 'java.lang.Object'.
    thank you for your quick reply.
    Laurent
    Patrick Linskey wrote:
    Laurent,
    What error are you seeing when you run your test?
    -Patrick
    Czinczenheim wrote:
    I would like to have a persistent class that holds interface field
    externalized via custom externalization methods.
    ex: I have a persistent class A.
    class A {
    private IFormat format;
    where IFormat is an interface. I want to store the format field via
    externalization to a string. IFormat implemnation must not be persistent
    object.
    The 'externalizer' extension is set to a method of the interface. The
    'factory' extension is set to a factory static method that instantiates an
    object implementing the IFormat interface.
    It seems externalization mechanism works fine if the field has a precise
    class declared type.
    How can i do ?
    Thanks for your help,
    Laurent

  • Non-standard interfaces must be server-side before de-serializing?

    Classes which implement non-standard interfaces are a problem for de-serialization? In the below code SomeInterface is the problem. If the "SomeInterface.class" is not server-side when the de-serialization starts then the de-serialization can't happen? Please look at this test code:
    client
    public class Main {
      public static void main(String[] args) {
        try {
          Socket sok = new Socket("192.168.2.2", 1638);
          MyOOS moos = new MyOOS(sok.getOutputStream());
          moos.writeObject(new ClassA(222));
          try { Thread.sleep(3000); } catch(InterruptedException e) { }
          sok.close();
        } catch(Exception e) { e.printStackTrace() ; }
      private static byte[] getClassImage() throws Exception {
        InputStream in = new FileInputStream(new File("/dev/ClassA.class"));
        List<Byte> objClassImage = new ArrayList<Byte>();
        int b = in.read();
        while(b != -1) {
          objClassImage.add(Byte.valueOf((byte) b));
          b = in.read();
        byte[] classImage = new byte[objClassImage.size()];
        for(int i = 0; i < classImage.length; i++) {
          classImage[i] = ((Byte) objClassImage.get(i)).byteValue();
        in.close();
        return classImage;
            static class MyOOS extends ObjectOutputStream {
              MyOOS() throws Exception { super(); }
              MyOOS(OutputStream out) throws Exception { super(out); }
              protected void annotateClass(Class<?> cl) throws IOException {
                try {
                  byte[] classImage = getClassImage();
                  writeInt(classImage.length);
                  write(classImage);
                } catch(Exception e) { e.printStackTrace(); }
    // public class ClassA implements Serializable, SomeInterface  {  // <-- bad
    public class ClassA implements Serializable  { // <-- good
      int id;
      ClassA(int i) { id = i; }
      public void foo() {
        System.out.println("ClassA::foo--> id = " + id);
    public Interface SomeInterface { public void foo(); }
    server
    public class Hello {
      static MyClassLoader myLoader = new MyClassLoader();
      public static void main(String[] args) { new Hello().run(); }
      void run() {
        try {
          ServerSocket servSok = new ServerSocket(1638);
          Socket sok = servSok.accept();
          MyOIS mois = new MyOIS(sok.getInputStream());
          Object obj = (Object) mois.readObject();
          Method m = obj.getClass().getMethod("foo", null);
          m.invoke(obj, null);
        } catch (Exception e) { e.printStackTrace(); }
          static class MyClassLoader extends ClassLoader {
            byte[] classImage;
            // is this a normal way to program Java? Because I am unsure about how to handle the byte[] in
            // resolveClass(), I am jamming them in here. Would a good programmer do stuff like this?
            public Class<?> loadClass(String name, byte[] classImage) throws Exception {
              this.classImage = classImage;
              return loadClass(name);
            protected Class<?> findClass(String name) throws ClassNotFoundException {
              return defineClass(name, classImage, 0, classImage.length);
          static class MyOIS extends ObjectInputStream {
            private MyClassLoader myLoader = new MyClassLoader();
            MyOIS() throws IOException { super(); }
            MyOIS(InputStream in) throws IOException { super(in); }
            protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
              try {
                int classImageSize = readInt();
                byte[] classImage = new byte[classImageSize];
                read(classImage);
                return myLoader.loadClass(desc.getName(), classImage);
              } catch (Exception e) { e.printStackTrace(); }
              return null;
    }If a serialized object implements an interface that is not already on the de-serializing jvm end, then serialization is not possible? Am I suppose to put the SomeInterface object on the server (somehow) before de-serializing an object that actually implements SomeInterface .
    I have heard of object graphs. So, would not the implemented interfaces be part of an object's object graph? Thanks.

    ejp wrote:
    I have no idea what any of that means, if anything, but RMI comes with a dynamic codebase facility if that's what you're looking for.I successfully moved an object with a non-standard pure abstract class to a remote jvm:
    client
    public class Main {
      public static void main(String[] args) {
        try {
          Socket sok = new Socket("192.168.2.2", 1638);
          MyOOS moos = new MyOOS(sok.getOutputStream());
          DataOutputStream dos = new DataOutputStream(sok.getOutputStream());
          byte[] classImage = getClassImage("/dev/PureAbstractClass.class");
          dos.writeInt(classImage.length);
          dos.write(classImage, 0, classImage.length);
          moos.writeObject(new ClassA(5));
          try { Thread.sleep(3000); } catch(InterruptedException e) { }
          sok.close();
        } catch(Exception e) { e.printStackTrace() ; }
      private static byte[] getClassImage(String path) throws Exception {
        InputStream in = new FileInputStream(new File(path));
        List<Byte> objClassImage = new ArrayList<Byte>();
        int b = in.read();
        while(b != -1) {
          objClassImage.add(Byte.valueOf((byte) b));
          b = in.read();
        byte[] classImage = new byte[objClassImage.size()];
        for(int i = 0; i < classImage.length; i++) {
          classImage[i] = ((Byte) objClassImage.get(i)).byteValue();
        in.close();
        return classImage;
            static class MyOOS extends ObjectOutputStream {
              MyOOS() throws Exception { super(); }
              MyOOS(OutputStream out) throws Exception { super(out); }
              protected void annotateClass(Class<?> cl) throws IOException {
                try {
                  byte[] classImage = getClassImage("/dev/ClassA.class");
                  writeInt(classImage.length);
                  write(classImage);
                } catch(Exception e) { e.printStackTrace(); }
    public abstract class PureAbstractClass {
      public abstract void foo();
      public abstract void bar();
    public class ClassA extends PureAbstractClass implements Serializable {
      int id;
      ClassA(int i) { id = i; }
      public void foo() { System.out.println("PureAbstractClass::ClassA::foo id = " + id); }
      public void bar() { System.out.println("PureAbstractClass::ClassA::bar id = " + id); }
    server
    public class Hello {
      static MyClassLoader myLoader = new MyClassLoader();
      public static void main(String[] args) { new Hello().run(); }
      void run() {
        try {
          ServerSocket servSok = new ServerSocket(1638);
          Socket sok = servSok.accept();
          MyOIS mois = new MyOIS(sok.getInputStream());
          DataInputStream dis = new DataInputStream(sok.getInputStream());
          int classImageSize = dis.readInt();
          byte[] classImage = new byte[classImageSize];
          dis.read(classImage, 0, classImageSize);
          myLoader.myDefineClass("PureAbstractClass", classImage, 0, classImage.length);
          Object obj = (Object) mois.readObject();
          Method m = obj.getClass().getMethod("bar", null);
          m.invoke(obj, null);
        } catch (Exception e) { e.printStackTrace(); }
            static class MyClassLoader extends ClassLoader {
              byte[] classImage;
              public Class<?> loadClass(String name, byte[] classImage) throws Exception {
                this.classImage = classImage;
                return loadClass(name);
              protected Class<?> findClass(String name) throws ClassNotFoundException {
                return defineClass(name, classImage, 0, classImage.length);
              public Class<?> myDefineClass(String name, byte[] classImage, int x, int y) {
                return defineClass(name, classImage, x, y);
            static class MyOIS extends ObjectInputStream {
              MyOIS() throws IOException { super(); }
              MyOIS(InputStream in) throws IOException { super(in); }
              protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                try {
                  int classImageSize = readInt();
                  byte[] classImage = new byte[classImageSize];
                  read(classImage);
                  return myLoader.loadClass(desc.getName(), classImage);
                } catch (Exception e) { e.printStackTrace(); }
                return null;
    }I hope this relates to understanding RMI. Moving objects that extend non-standard classes and implementing non-standard interfaces is not easy. Or, maybe there is an easier way. Anyway, thanks ejp. Yesterday I was extremely confused. Now, I am just a little confused but think I have basic understanding. I feel big progress was made.

Maybe you are looking for

  • Mini-DVI to Video Adapter

    Well being a new mac users (and loving the change greatly) I decided to use my brand new black macbook to it's fullest extent and make my own Keynote presentation. Although the final result is great I need to know if I can actually get it projected u

  • I have $51.95 dollars in creidt, why cant I buy any music?? Whats going on

    What is going on?. I have $51.95 in credit ..Why cant I buy any music..And what about the money I have in credit. I only use this as my computer at home. I dont have a moblie!!.. I'm sick of this

  • DiskUtility unable to repair

    For a few months now, whenever I run "Verify Disk" on Disk Utility, it's given me a message saying something about BitMap having problems, and telling me to run Repair. Unfortunately, when I run repair, it tell me it is unable to repair the disk. Jus

  • Has anyone seen changing map ids corrupting an HTML project?

    I am working in RoboHelp8, and generating .chm help files to be attached to my company's software application. I built a map id file from numbers the programmer gave me. His calls have been able to use my generated files, but the "HH_HELP_CONTEXT cal

  • Organizing an AS Model - howto?

    Hi, I have a conceptional question regarding best practice to handle externally loaded XML within ActionScript 3.0 code. How do I organize the data in a useful way? Now I have looked though several books and videos on this topic but have only found s