Deserialization / readObject problem

Hi people
I am in the making of a simple 2D multiplayer game.
The server and clients are communicating through ObjectOutput/ Input streams (through Sockets).
The server contains all the game logic, and it sends a serialized GameData class to the clients
so they can draw the graphics accordingly to the events in the game.
The problem is, the client only reads data from its objectinputstream successfully once, then it just doesnt work.
It seems that after the first call of objectRead() it always just gets the same object with every call of objectRead.
It is SURE that it the objectRead gets it successfully at least ONCE, because the client draws the graphics of the game after joining, but it doesn't move,
it's like the client captures the state of the game in the moment of joining.
There are no exceptions thrown, there are no problems on the serverside(it always writes out different GameData instances by writeObject(GameData)).
I write the contents of the gd class every time on console after the call of GameData gd=(GameData) In. readObject();
and it's always the same and hence, the drawn graphics are the same.
I also write the contents of the sent GameData class every time on console after the call of out.writeObject( GameData instance); on the server side
and it's always updated accordingly to the logic of the game.
Please help, the deadline is close!
while (true) {
                    // Get the game data from the server
                    try {
                         System.out
                                   .println("client: dataupdater class : trying to read data from server");                    
                                        GameData gd = (GameData) In.readObject();               
//at this point i write out the contents of gd to the console, and it's always the same!!
//I spare you of that code.
                         setCurrentData(gd);
                         System.out.println("Data read .");
                    catch (SocketException s) {
                         System.out.println("Disconnected from server.");
                    catch (IOException ie) {
                         ie.printStackTrace();
                    catch (Exception e) {
                         System.out.println(e);
                    try {
                         Thread.sleep(15);
                    } catch (InterruptedException e)
                         e.printStackTrace();
          }Also the serverside code, because it cant hurt.
     GameData gd = logic.exportGameData();
          //WRITING OUT THE CONTENTS OF GD, SAME CODE AS IN THE CLIENT
                System.out.println("Number of entities: " + gd.entities.length);
          for (int i = 0; i < gd.entities.length; i++) {
               Entity entity = gd.entities;
               System.out.println(entity.getClass() + " PosX: " + entity.getX()
                         + " PosY: " + entity.getY());
          // synchronized (outputStreams) {
          // For each client ...
          for (Enumeration<ObjectOutputStream> e = getOutputStreams(); e
                    .hasMoreElements();) {
               // ... get the output stream ...
               ObjectOutputStream out = (ObjectOutputStream) e.nextElement();
               // ... and send the message
               try {
                    out.writeObject(gd);
                    out.flush();
               } catch (IOException ie) {
                    ie.printStackTrace();
          }Edited by: mostKeltem on Jun 2, 2010 9:47 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

mostKeltem wrote:
ok, writeShared with reset works well.
thank you very much, i owe you a beer.
if you happen to be in Budapest, Hungary any time, come at me for your share of etanol.bummer, would love to go, but can't see it happening any time soon.

Similar Messages

  • Deserialization order problem

    Hi,
    For a game i am making i am storing the map as a Serialized Object.
    The problem is when i try to paint an image (which should be loaded in the constructor) it is null and thus causing a nullpointer. This only happens after serializing and deserializing the Map. It appears to me that somehow the constructors are not called anymore.
    I am using the following (simplified) objects:
    public class Map implements java.io.Serializable
         //also included are some protected final static primitives
         protected MapModel model;
         //and some other protected primitives and objects     
         public Map()
              this(null);
         public Map(MapModel model)
              this.model=model;
    public class MapModel implements java.io.Serializable
         protected Terrain[][] data;
         private Size size;//simple serializable class
         public MapModel()
              this(new Size());
         public MapModel(Size s)
              data=new Terrain[s.width][s.height];
              size=s;
    public abstract class Terrain implements java.io.Serializable
         protected transient Image view;     
         //some more protected primitives     
         public Terrain()
              this(Allignment.SOUTHWEST);
         public Terrain(int allignment)
              System.out.println("Terrain constructor: "+getClass().getName());
              view=loadImage();
         protected abstract Image loadImage();
         //some more abstract methods
    public abstract class Tile extends Terrain
         //some public final static ints     
         //some protected ints
         public Tile()
              this(Allignment.SOUTHWEST);
         public Tile(int allignment)
              super(allignment);
              System.out.println("Tile constructor");
         //loadImage() is still not implemented
    public class GreyTile extends Tile
         public GreyTile()
              this(Allignment.SOUTHWEST);
         public GreyTile(int allignment)
              super(allignment);
              System.out.println("GreyTile constructor");
         protected java.awt.Image loadImage()
              System.out.println("GreyTile loadImage()");
              //load and return an image
    }The above object tree is created and serialized and produces the expected output:
    Terrain constructor: heroquest.terrain.tiles.GreyTile
    GreyTile loadImage()
    Tile constructor
    GreyTile constructor
    Deserialization however does not produce any output, so loadImage is never called and Terrain.view is null. Which explains the Nullpointer i am getting when trying to paint the GreyTile.
    However i do not understand why my constructors are never called.
    any thoughts?
    Thanks,
    Mr Mean

    This image is loaded in the constructor. And the
    problem is that after deserialization the constructor
    is never exectued.
    My Question is why.First of all, I apologize for not reading through your code thoroughly. Yes your Image object is transient.
    A Ctor is called only when a new instance is created. When deserializing, we are not creating a new instance , we are only restoring a persisted object.
    The deserialization process does not use the Ctor because it is not needed. The only time it needs a Ctor is when deserializing the state of the first non-serializable superclass of a serializable one (deserialization needs to reconstruct the entire object state, which includes the state of any superclasses. If the superclass is not itself serializable, then deserialization needs to instantiate that superclass from scratch ).That superclass won't be restored from the stream, but by invoking that class' no-argument constructor.
    If the default behavior of this process does not suit your purposes, the solution would be to provide your own writeObject/readObject methods to do what you need to do.

  • Byte[] serialization/deserialization BLOB problem

    I want to store an image in DB.
    I choose to store a byte[], like a BLOB (i use MySql).
    But when byte[] is serialized in DB in front of the array are inserted 27
    bytes.
    What should i do to store exact the given byte array ?
    (Or off course an ImageIcon object : for which on deserialization an
    ClassCastException is thrown).
    And which is the reason that those 27 (!?!) bytes are inserted.
    thank you in advance for your help.
    (please excuse my english)
    BytesTest.jdo
    <?xml version="1.0"?>
    <!DOCTYPE jdo SYSTEM "http://www.solarmetric.com/dtds/jdo.dtd">
    <!-- This JDO Metadata file was auto-generated on 7/2/02 3:18 PM.
    See http://www.solarmetric.com for Kodo JDO Documentation and examples. -->
    <jdo>
    <package name="jdoproject">
    <class name="BytesTest" requires-extent="true">
    <field name="bytesArray" null-value="none" primary-key="false">
    <extension key="blob" value="true" vendor-name="kodo"/>
    </field>
    </class>
    </package>
    </jdo>
    BytesTest.java
    package jdoproject;
    public class BytesTest {
    private byte[] bytesArray = null;
    public BytesTest () {
    bytesArray = new byte[30];
    for (int i = 0; i < 30; i++)
    bytesArray[i] = (byte)(65 + i);
    public String toString () {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < bytesArray.length; i++)
    sb.append(" " + (bytesArray[i] & 0xFF) + "[" +
    (char)(bytesArray[i] & 0xFF)
    + "]");
    return sb.toString();
    this must be run twice (first , to make an insertion , second to view what
    is previos inserted)
    BytesTestMain.java
    public class BytesTestMain {
    public static void main (String[] args) {
    BytesTest test = null;
    try {
    JDBCConfiguration jc = new JDBCPropertiesConfiguration();
    PersistenceManagerFactory pmf = new
    JDBCPersistenceManagerFactory(
    new FileInputStream("config/kodo.properties"));
    PersistenceManager pm = pmf.getPersistenceManager();
    Extent people = pm.getExtent(BytesTest.class, false);
    Query query = pm.newQuery(BytesTest.class, people);
    Collection result = (Collection)query.execute();
    Iterator iter = result.iterator();
    System.out.println("Found items: ");
    while (iter.hasNext()) {
    test = (BytesTest)iter.next();
    System.out.println("test= " + test);
    test = new BytesTest();
    System.out.println("Inserting item: "+test);
    Transaction t = pm.currentTransaction();
    t.begin();
    pm.makePersistent(test);
    t.commit();
    } catch (Exception e) {
    e.printStackTrace();
    System.out.println("ALL DONE---------------------");

    cross-post:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=323525

  • StreamCorruptedException: does not contain a serialized object?

    Can someone tell me why am I getting this exception:
    C:\javapr>java FetchObject
    Couldn't retrieve binary data: java.io.StreamCorruptedException: InputStream
    does not contain a serialized object
    java.io.StreamCorruptedException: InputStream does
    not contain a serialized object
    at java.io.ObjectInputStream.readStreamHeader
    (ObjectInputStream.java:849)
    at java.io.ObjectInputStream.<init>
    (ObjectInputStream.java:168)
    at FetchObject.main(FetchObject.java:23)
    import java.sql.*;
    import java.util.*;
    import java.io.*;
    class FetchObject implements Serializable {
        public static void main (String[] args) {
            try {
                String driver = "oracle.jdbc.driver.OracleDriver";
                Class.forName(driver);
                String url = "jdbc:oracle:thin:@mymachine:1521:homedeva";
                Connection conn = DriverManager.getConnection(url,"cnn","cnn");
                FetchObject i = new FetchObject();
                    // Select related
                    try
                         byte[] recdBlob = i.selectBlob( 1 , conn ); 
                         ByteArrayInputStream bytes = new ByteArrayInputStream(recdBlob);
                         ObjectInputStream deserialize = new ObjectInputStream( bytes );
              Employee x = (Employee)deserialize.readObject();
                    catch( Exception ex )
                  System.err.println("Couldn't retrieve binary data: " + ex);
                  ex.printStackTrace();
         catch( Exception ex )
              ex.printStackTrace();
        public byte[] selectBlob( int id, Connection conn )
         byte[] returndata = null;
         try
              Statement stmt = conn.createStatement();
              String sql = "SELECT id, rowdata FROM blobs WHERE id = " + id;
              ResultSet rs = stmt.executeQuery(sql);
              if ( rs.next() )
                           try
                               ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
                               BufferedInputStream bis = new BufferedInputStream( rs.getBinaryStream("rowdata") );
                             byte[] bindata = new byte[4096];
                               int bytesread = 0;
                               if ( !rs.wasNull() )
                                       if ( (bytesread = bis.read(bindata,0,bindata.length)) != -1 )
                                          baos.write(bindata,0,bytesread);
                                returndata = baos.toByteArray();
                             baos.flush();
                                bis.close();
                       catch ( Exception ex )
                            System.err.println("Problem retrieving binary data: " + ex);
                        rs.close();
                         stmt.close();  
               catch ( Exception ex )
                    System.err.println("Couldn't retrieve binary data: " + ex);
            return returndata;
    import java.io.*;
    class Employee implements Serializable
         private String lastName;
         private String firstName;
         public Employee(String lastName, String firstName)
              this.lastName = lastName; 
              this.firstName = firstName;
    }

    To clarify I have stored an Employee Object as a Blob in the Oracle database and am attempting to retreive the
    Employee Object from this Blob.
    Thanks

  • StreamCorruptedException while using JWS

    Hello,
    I'm wanting to deploy the client of a client/server networked app in JWS, but for some reason I'm getting StreamCorruptedExceptions when I try to deserialize Objects contained in network messages. This doesn't happen when I run the app outside of JWS, so it appears to be some weird interaction with JMS. Here are all the details I can think of:
    The app is being distributed as one jar, including all libraries, by using the Fatjar plugin for Eclipse.
    I'm using Apache Tomcat v5.5.12 as the application server so that I can click a link in a browser to start the JWS app.
    I'm using ActiveMQ v4.0M3 as a JMS provider to handle passing messages across the network. (The same thing happens with ActiveMQ v3.2.1)
    This is the error print out:
    Caught: javax.jms.JMSException: Failed to build body from bytes. Reason: java.io.StreamCorruptedException
    javax.jms.JMSException: Failed to build body from bytes. Reason: java.io.StreamCorruptedException
         at org.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:34)
         at org.activemq.command.ActiveMQObjectMessage.getObject(ActiveMQObjectMessage.java:173)
         at com.shai.ogma.networking.JMSLink.onMessage(JMSLink.java:115)
         at org.activemq.ActiveMQMessageConsumer.dispatch(ActiveMQMessageConsumer.java:703)
         at org.activemq.ActiveMQSessionExecutor.dispatch(ActiveMQSessionExecutor.java:95)
         at org.activemq.ActiveMQSessionExecutor.iterate(ActiveMQSessionExecutor.java:148)
         at org.activemq.thread.SimpleTaskRunner.runTask(SimpleTaskRunner.java:129)
         at org.activemq.thread.SimpleTaskRunner.access$100(SimpleTaskRunner.java:44)
         at org.activemq.thread.SimpleTaskRunner$1.run(SimpleTaskRunner.java:62)
         at edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:643)
         at edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:668)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.io.StreamCorruptedException
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at java.util.HashMap.readObject(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at java.util.HashMap.readObject(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at java.util.HashMap.readObject(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at com.shai.ogma.messaging.OgmaMessage.readExternal(OgmaMessage.java:245)
         at java.io.ObjectInputStream.readExternalData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at org.activemq.command.ActiveMQObjectMessage.getObject(ActiveMQObjectMessage.java:167)
         ... 10 more
    Notes about the error message:
    The thing it is getting stuck on while trying to deserialize is one of my own classes with readObject() and writeObject() defined.
    It can serialize/deserialize without problems outside of JWS.
    All the classes I'm serializing are in synch between the server and the client. I.e. there shouldn't be any problems with serialversionUID caused by code being at different versions.
    The code at org.activemq.command.ActiveMQObjectMessage.getObject(ActiveMQObjectMessage.java:167) doesn't appear to be doing anything funny.
    Does anyone have any clues what might be causing this behavior and how to fix it?
    Thanks!

    Here is my guess. The browser VM has some subtle interractions with the browser. An SSL connection usually starts with the server sending a certificate and the client 'accepting it'. The acceptance or rejection is based on the root certificates configured in the client. The browser has such a 'database' of root certificates. I bet the browser VM is using the same database as the browser.
    When you run the application stand-alone, the database is somewhere in the JRE. Somehow the root certificate of your server certificate is not there.

  • Non-blocking SocketChannels

    I'm trying to learn how to use non-blocking socket channles, but I haven't found much info (nor luck) so far.
    To learn, I'm building a server and a client. The server accepts input from the clients and process it in only one thread. The clients should send Objects to the server, and the server process them and return the result also as an Object. For this, I'm trying to use ObjectOutputStream and ObjectInputStream.
    The problem I don't know how to solve is that the SocketChannel is in non-bolcking mode, so I can't use their input/output streams (I get a IllegalBlockingModeException). In the server process loop I can reconfigure the SocketChannel to blocking mode to be able to read the Object, but I can't configure it to non-blocking mode again because I get a CancelledKeyException.
    Does anyone know how to work with InputStreams and non-blocking channels? Or where to find more info about it?
    Here are the relevant part of the server code:
    Set ready = selector.selectedKeys();
    Iterator i = ready.iterator();
    while (i.hasNext()) {
       try {
          SelectionKey sk = i.next();
          i.remove();
          if (sk.isAcceptable()) {
             ServerSocketChannel ssc = (ServerSocketChannel)sk.channel();
             SocketChannel sc = ssc.accept();
             sc.configureBlocking(false);
             sc.register(selector, SelectionKey.OP_READ);
          } else if (sk.isReadable()) {
             SocketChannel sc = (SocketChannel)sk.channel();
             // PROBLEM: If the channel is in non-blocking mode
             // I cannot use InputStreams
             sk.cancel();
             sc.configureBlocking(true);
             // Read the object sent by the client
             ObjectInputStream in = new ObjectInputStream(Channels.newInputStream(sc));
             Object o = in.readObject();
             // PROBLEM: Can't put the channel back to non-blocking mode
             sc.configureBlocking(false);
             sc.register(selector, SelectionKey.OP_READ); // CancelledKeyException
       } catch (...){
    }

    In my client, this is working fine:
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    for (int i = 0; i < 30000; i++) {
       oos = new ObjectOutputStream(sc.socket().getOutputStream());
       oos.writeObject(object);
       oos.flush();
       ois = new ObjectInputStream(sc.socket().getInputStream());
       Object o = ois.readObject();
    }But trying to do it like this throws a StreamCorruptedException at the server side.
    ObjectOutputStream oos = new ObjectOutputStream(sc.socket().getOutputStream());
    ObjectInputStream ois = new ObjectInputStream(sc.socket().getInputStream());
    for (int i = 0; i < 30000; i++) {
       oos.writeObject(object);
       oos.flush();
       Object o = ois.readObject();
    }Do you know why?

  • Object location manager

    Hello !
    Context :
    You can register for an instance with a name in the object location
    manager.
    Later, you can obtain a proxy on it with the bind method of the
    objLocMgr.
    You need the name of the instance you want to bind.
    The name is structured with / (like directory on hard disk).
    Inside an application it is OK.
    Problem & questions :
    Bind an instance from another application. How is the syntax of the
    name ?
    If an application A provide an soA. How can I bind it from an
    application B ?
    How to bind an instance of an application A inside an application B ?

    Jeanne,
    I liked your approach to getting around the
    deserialization error problem. Please clarify if this is
    what you had in mind :
    1) Every Client does a 'bind' on start-up.
    2) Every Client does a de-register when they log-off.
    If the answers to the points above are 'yes', I'm not
    sure what the implications are from a performance
    standpoint on a environment with a large number of
    users, including mobile ones.
    There was a design pattern presented at the Forum (I
    can't remember which one) which talked about having a
    remote SO do the bind to various SO's and Clients get a
    reference to the <<realSO>> proxy via this remote SO.
    Somewhere in the pattern was a way to get around
    deserialization errors, but I just can't remember how !
    Thanks.
    Eric
    Sorry to be late jumping into this thread - I've been chasing other
    issues the last couple days.
    I did not get to see <bigger>Fabrizio Genesio's presentation at Forum,
    although I certainly wanted to, because his topic was somewhat similar to
    mine. And Ravi's comments about de-coupling and making plug and play
    components almost sound like they came out of my abstract.
    Yes, Geoff, you can remove the supplier plan, bind to a distributed
    service dynamically at run time, and not get a deserialization error.
    There are a couple of tricks, but the code attached illustrates that it
    works.
    When you create your interface, also create a "dummy" or generic class
    that implements that interface. I like to put the dummyClass and the
    interface in the same library, because when you need one, you usually
    need the other. The dummyClass should have no "real" code, and no
    supplier dependencies. Just put in do-nothing methods that implement all
    of the interface methods, and return nil or zero where needed, so you
    don't get compiler warnings.
    Then create the real implementation in a separate project, which has the
    interface library as a dependency. The realClass must be a subclass of
    the dummyClass that is in the interface library. This is essential to
    make the dynamic binding work without the supplier dependencies. This
    service project does NOT need to be a supplier to the client. All the
    client needs is the interface library.
    When you instantiate the service, you will instantiate and register the
    realClass. When your client does the BindObject, it can bind to the
    dummyClass, because the realClass "IsA" dummyClass. And you can cast the
    returned object to the interface, because the dummyClass does implement
    the interface.
    The reason you do not get deserialization errors is fairly simple. You
    have essentially created your own proxy using the dummyClass, which
    exists on the client. It does not matter that the proxy has no code,
    because it will never get called.
    The realClass is anchored on the server, and does not need to be
    recreated on the client for any reason. Serialization and
    deserialization do not even occur with the realClass, therefore you get
    no errors. However, if you try to send the client a reference to the
    realClass, other than by way of the BindObject, then you most certainly
    will get the dreaded deserialization error.
    Hope this helps,
    Jeanne
    </bigger>At 07:23 PM 5/20/99 -0500, you wrote:
    >
    >
    -----Original Message-----
    From: [email protected]
    [mailto:[email protected]]
    On Behalf Of Geoff Puterbaugh
    Sent: Thursday, May 20, 1999 2:03 PM
    To: Kalidindi, Ravi CWT-MSP
    Cc: 'Jean-Baptiste BRIAUD'; '[email protected]'
    Subject: Re: Object location manager
    When I tried this, it didn't work. Aside from the
    fact that you can't dynamically load interfaces,
    to the best of my knowledge (but you can dynamically
    load classes which implement interfaces), the
    suggested scheme simply fails.
    But you have to be careful about what you're doing.
    You have to really REMOVE the supplier plan for
    the service object you're trying to reference,
    and you have to create real applications which
    are running outside of the repository. At least
    two separate applications which are running from
    distributions, not the repos.
    If you do that, you'll find that BindObject
    works just fine, but assigning the object
    returned by BindObject to the interface will
    produce a run-time error: 'This class does
    not implement this interface.'
    I can send or publish some code which demonstrates
    this failure if you like. I'd be delighted to
    learn that I've made a mistake somewhere.
    But my theory is that once you remove supplier
    plan A from the application, Forte no longer
    includes plan A in the application distribution,
    and so your application at run-time just has
    no information about class A or SO A.
    All my best,
    Geoff
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive<<URL:http://pinehurst.sageit.com/listarchive/>
    >
    >
    >
    =========================================
    Jeanne Hesler <<[email protected]>
    MSF&W Software, Product Development
    (217) 698-3535 ext 207
    http://www.msfw.com
    =========================================
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>

  • Problem in deserialization with different versions of JDK

    I have problem related to serialization, pls suggest the most appropriate solution, the problem is that I have a class AAAA.java which extends AbstractListModel.java class of JDK, and it is serializable. When i saw the serialVersionUID of AbstractListModel.java using the java tool serialver in jdk 1.3.1 from the command line it gives 2622425607724314306 (Unique ID of class) but when i saw it in JDK 1.4.1 then it given -3285184064379168730. As the UID is changed from JDK1.3.1 to 1.4.1, Now the problem is that i serialized a file which uses AAAA.java using the 1.3.1 and now i want to open that file in my project using 1.4.1 it gives exception.
    java.io.InvalidClassException: javax.swing.AbstractListModel; local class incompatible: stream classdesc serialVersionUID = 2622425607724314306, local class serialVersionUID = -3285184064379168730
    at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:459)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1521)
    Can u suggest me appropriate solution as this file must be desirialized (Compatibility issue) as it is generated from project.
    U may also try using this command in jdk 1.3.1 & 1.4.1
    on command prompt
    serialver javax.swing.AbstractListModel.

    From the API (you already know this, though through experience...)
    Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. A future release of Swing will provide support for long term persistence.
    So there seems to be no easy solution (in 1.4 you would use XMLEncoder for persistence with future versions, no possible in 1.3.1). You will probably have to study the serialized code and figure out how to deserialize manually... like find what the header size and format is, how objects' classes and values are labeled etc, then rebuild the object on the receiving end using a datainput stream or something...

  • Apache axis deserialization problem

    Can anybody help?
    We are using Apache's Axis web service framework for consuming web services. One of the web services has "nested" or complex types in the response, and the Axis framework is not processing it properly.
    Is there something that we need to configure to get this to work? Any suggestions are much appreciated.
    It gives the following message:
    org.xml.sax.SAXException: Invalid element in com.chase.egw._GWProfile - Product
    at org.apache.axis.encoding.ser.BeanDeserializer.onStartChild(BeanDeserializer.java:260)
    at org.apache.axis.encoding.DeserializationContextImpl.startElement(DeserializationContextImpl.java:963)
    at org.apache.axis.message.SAX2EventRecorder.replay(SAX2EventRecorder.java:198)
    at org.apache.axis.message.MessageElement.publishToHandler(MessageElement.java:722)
    at org.apache.axis.message.RPCElement.deserialize(RPCElement.java:323)
    at org.apache.axis.message.RPCElement.getParams(RPCElement.java:347)
    at org.apache.axis.client.Call.invoke(Call.java:2272)
    at org.apache.axis.client.Call.invoke(Call.java:2171)
    at org.apache.axis.client.Call.invoke(Call.java:1691)
    at com.chase.egw.GWProfilePortTypeSoapBindingStub.getProfile(GWProfilePortTypeSoapBindingStub.java:185)
    at com.echase.common.mf.sso.SSOGatewayServiceDelegate.getGWProfile(SSOGatewayServiceDelegate.java:178)

    I am having the same problem as you describe.
    Checkout out this link:
    http://dev-forums.ebay.com/thread.jsp?forum=1002&thread=100000782
    It talks about adding the following to the complex type defintion in the WSDL
    <xsd:any processContents = "lax"/>
    The good news is this solved the exception problem.
    The bad news is that my complex objects are not being deserialed. I've posted to the AXIS users mailing list.
    Here is what I posted:
    Hi,
    I need a little help getting started with AXIS.
    I've done some SOAP web services development a few years back using SUN JAXM, but I will be using AXIS for a webservice project in the near term.
    In order to get familiar with AXIS I did the GOOGLE thing and aquired a sample WDSL to try out.
    I am using 1.2RC3 version of AXIS with Tomcat 5.0.28.
    Here is the WSDL I first used:
    <wsdl:definitions
    name="PhotoCatalogService"
    targetNamespace="http://examples.com/PhotoCatalog"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:types="http://examples.com/PhotoCatalog/types"
    xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
    xmlns:tns="http://examples.com/PhotoCatalog">
    <wsdl:types>
    <xsd:schema targetNamespace="http://examples.com/PhotoCatalog/types"
    xmlns:wsi="http://ws-i.org/profiles/basic/1.1/xsd"
    xmlns:types="http://examples.com/PhotoCatalog/types">
    <xsd:import namespace="http://ws-i.org/profiles/basic/1.1/xsd" schemaLocation="WS-ISwA.xsd"/>
    <!-- Status contains the references the old photo available as attachment. -->
    <xsd:element name="Status" type="wsi:swaRef" />
    <!-- passed in as parameter of replacePhoto operation, contains the order. -->
    <xsd:element name="PhotoInfo">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="customerName" type="xsd:string"/>
    <xsd:element name="photoID" type="xsd:int"/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:schema>
    </wsdl:types>
    <wsdl:message name="addPhotoRequest">
    <wsdl:part name="oldPhoto" element="types:PhotoInfo"/>
    <wsdl:part name="photo" type="xsd:hexBinary"/>
    </wsdl:message>
    <wsdl:message name="addPhotoResponse">
    <wsdl:part name="status" type="xsd:string"/>
    </wsdl:message>
    <wsdl:message name="replacePhotoRequest">
    <wsdl:part name="oldPhoto" element="types:PhotoInfo"/>
    <wsdl:part name="newPhoto" type="xsd:hexBinary"/>
    </wsdl:message>
    <wsdl:message name="replacePhotoResponse">
    <wsdl:part name="status" element="types:Status"/>
    </wsdl:message>
    <wsdl:portType name="PhotoCatalog">
    <wsdl:operation name="addPhoto">
    <wsdl:input message="tns:addPhotoRequest"/>
    <wsdl:output message="tns:addPhotoResponse"/>
    </wsdl:operation>
    <wsdl:operation name="replacePhoto">
    <wsdl:input message="tns:replacePhotoRequest"/>
    <wsdl:output message="tns:replacePhotoResponse"/>
    </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="PhotoCatalogBinding" type="tns:PhotoCatalog">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="addPhoto">
    <wsdl:input>
    <mime:multipartRelated>
    <mime:part>
    <soap:body parts="oldPhoto" use="literal"/>
    </mime:part>
    <mime:part>
    <mime:content part="photo" type="image/jpeg"/>
    </mime:part>
    </mime:multipartRelated>
    </wsdl:input>
    <wsdl:output>
    <mime:multipartRelated>
    <mime:part>
    <soap:body use="literal"/>
    </mime:part>
    <mime:part>
    <mime:content part="status" type="text/plain"/>
    <mime:content part="status" type="text/xml"/>
    </mime:part>
    </mime:multipartRelated>
    </wsdl:output>
    </wsdl:operation>
    <wsdl:operation name="replacePhoto">
    <wsdl:input>
    <mime:multipartRelated>
    <mime:part>
    <soap:body parts="oldPhoto" use="literal"/>
    </mime:part>
    <mime:part>
    <mime:content part="newPhoto" type="image/jpeg"/>
    </mime:part>
    </mime:multipartRelated>
    </wsdl:input>
    <wsdl:output>
    <mime:multipartRelated>
    <mime:part>
    <soap:body parts="status" use="literal"/>
    </mime:part>
    </mime:multipartRelated>
    </wsdl:output>
    </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="PhotoCatalogService">
    <wsdl:port name="PhotoCatalogPort" binding="tns:PhotoCatalogBinding">
    <soap:address location="http://localhost:8080/jaxrpc-AttachmentsSample/photocatalog"/>
    </wsdl:port>
    </wsdl:service>
    </wsdl:definitions>
    When I used the previous WSDL to generate a service and then a client I got the following error on the client side when trying the "addPhoto" service:
    AxisFault
    faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
    faultSubcode:
    faultString: org.xml.sax.SAXException: Invalid element in com.examples.PhotoCatalog.types.PhotoInfo - PhotoInfo
    faultActor:
    faultNode:
    faultDetail:
    {http://xml.apache.org/axis/}hostname:tislaptop
    org.xml.sax.SAXException: Invalid element in com.examples.PhotoCatalog.types.PhotoInfo - PhotoInfo
    at org.apache.axis.message.SOAPFaultBuilder.createFault(SOAPFaultBuilder.java:221)
    at org.apache.axis.message.SOAPFaultBuilder.endElement(SOAPFaultBuilder.java:128)
    at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)
    at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
    at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanEndElement(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(SAXParser.java:345)
    at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
    at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
    at org.apache.axis.Message.getSOAPEnvelope(Message.java:424)
    at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:745)
    at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:141)
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
    at org.apache.axis.client.Call.invokeEngine(Call.java:2754)
    at org.apache.axis.client.Call.invoke(Call.java:2737)
    at org.apache.axis.client.Call.invoke(Call.java:2413)
    at org.apache.axis.client.Call.invoke(Call.java:2336)
    at org.apache.axis.client.Call.invoke(Call.java:1793)
    at com.examples.PhotoCatalog.PhotoCatalogBindingStub.addPhoto(PhotoCatalogBindingStub.java:190)
    at com.examples.PhotoCatalog.PhotoCatalogProxy.addPhoto(PhotoCatalogProxy.java:45)
    at com.examples.PhotoCatalog.TestPhotoService.main(TestPhotoService.java:41)
    Here is an abridged network trace of the SOAP request sent from client to server...
    POST /axis/services/PhotoCatalogPort HTTP/ 1.0
    Content-Type: multipart/related;type="text/xml";start="<DBB2B5537065926A4CBC8F8ED8D88F15>";boundary="----=_Part_0_20983130.1113483759295"
    Accept: application/soap+xml, application/dime, multipart/related, text/*
    User-Agent:Axis/1.2RC3
    Host: xxx.xxx.xxx.xxx:8080
    Cache-Control: no-cache
    Pragma: no-cache
    SOAPAction: ""
    Content-Length: 8466
    ------=_Part_0_209831301113483759295
    Content-Type: text/xml; charset=UTF-8
    Content-Transfer-Encoding: binary
    Content-Id: <DBB2B5537065926A4CBC8F8ED8D88F15>
    <?xml version="1.0" encoding="UTF-8" ?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XML Schema-instance">
    <soapenv:Body>
    <addPhoto xmlns="">
    <ns1:PhotoInfo xmlns:ns1="http://examples.com/PhotoCatalog/types">
    <customerName>karl</customerName>
    <photoID>100</photoID>
    </ns1:PhotoInfo>
    <photo href="cid:9AD6390B491EF0EE0B0FCEA7AA945655" xsi:type="ns2:Image" xmlns:ns2="http://xml.apache.org/xml-soap"/>
    </addPhoto>
    </soapenv:Body>
    </soapenv:Envelope>
    ------=_ Part_0_20983130.1113483759295
    Content-Type:image/jpeg
    Content -Transfer-Encoding:binary
    Content-Id: <F2369DA809C4B1B0ADBA8538372E6F23>
    ...QE..QE.......
    ------=_Part_0_20983130.1113483759295
    After a little searching I found some info that led me to change the WSDL a little. I redefined the "PhotoInfo" type as follows
    <xsd:element name="PhotoInfo">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="customerName" type="xsd:string"/>
    <xsd:element name="photoID" type="xsd:int"/>
    <xsd:any processContents = "lax"/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    Now there is no exception thrown, but the PhotoInfo and photo objects are not deserialized. I get null values passed to the PhotoCatalogBindingImpl class.
    I noticed that an org.apache.axis.message.MessageElement[] object and associated methods was added to the PhotoInfo class, which I assume is due to adding the <xsd:any processContents = "lax"/> line to the WSDL.
    Here is the PhotoInfo and PhotoCatalogBindingImpl class source for reference:
    * PhotoCatalogBindingImpl.java
    * This file was auto-generated from WSDL
    * by the Apache Axis 1.2RC3 Feb 28, 2005 (10:15:14 EST) WSDL2Java emitter.
    package com.examples.PhotoCatalog;
    import javax.xml.transform.Source;
    public class PhotoCatalogBindingImpl implements com.examples.PhotoCatalog.PhotoCatalog{
    public javax.xml.transform.Source
    addPhoto(com.examples.PhotoCatalog.types.PhotoInfo oldPhoto, java.awt.Image photo) throws java.rmi.RemoteException {
    return null;
    public org.apache.axis.types.URI replacePhoto(com.examples.PhotoCatalog.types.PhotoInfo oldPhoto, java.awt.Image newPhoto) throws java.rmi.RemoteException {
    return null;
    * PhotoInfo.java
    * This file was auto-generated from WSDL
    * by the Apache Axis 1.2RC3 Feb 28, 2005 (10:15:14 EST) WSDL2Java emitter.
    package com.examples.PhotoCatalog.types;
    public class PhotoInfo implements java.io.Serializable, org.apache.axis.encoding.AnyContentType {
    private java.lang.String customerName;
    private int photoID;
    private org.apache.axis.message.MessageElement [] _any;
    public PhotoInfo() {
    public PhotoInfo(
    org.apache.axis.message.MessageElement [] _any,
    java.lang.String customerName,
    int photoID) {
    this.customerName = customerName;
    this.photoID = photoID;
    this._any = _any;
    * Gets the customerName value for this PhotoInfo.
    * @return customerName
    public java.lang.String getCustomerName() {
    return customerName;
    * Sets the customerName value for this PhotoInfo.
    * @param customerName
    public void setCustomerName(java.lang.String customerName) {
    this.customerName = customerName;
    * Gets the photoID value for this PhotoInfo.
    * @return photoID
    public int getPhotoID() {
    return photoID;
    * Sets the photoID value for this PhotoInfo.
    * @param photoID
    public void setPhotoID(int photoID) {
    this.photoID = photoID;
    * Gets the _any value for this PhotoInfo.
    * @return _any
    public org.apache.axis.message.MessageElement [] get_any() {
    return _any;
    * Sets the _any value for this PhotoInfo.
    * @param _any
    public void set_any(org.apache.axis.message.MessageElement [] _any) {
    this._any = _any;
    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
    if (!(obj instanceof PhotoInfo)) return false;
    PhotoInfo other = (PhotoInfo) obj;
    if (obj == null) return false;
    if (this == obj) return true;
    if (__equalsCalc != null) {
    return (__equalsCalc == obj);
    __equalsCalc = obj;
    boolean _equals;
    _equals = true &&
    ((this.customerName==null && other.getCustomerName()==null) ||
    (this.customerName!=null &&
    this.customerName.equals(other.getCustomerName()))) &&
    this.photoID == other.getPhotoID() &&
    ((this._any==null && other.get_any()==null) ||
    (this._any!=null &&
    java.util.Arrays.equals(this._any, other.get_any())));
    __equalsCalc = null;
    return _equals;
    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
    if (__hashCodeCalc) {
    return 0;
    __hashCodeCalc = true;
    int _hashCode = 1;
    if (getCustomerName() != null) {
    _hashCode += getCustomerName().hashCode();
    _hashCode += getPhotoID();
    if (get_any() != null) {
    for (int i=0;
    i<java.lang.reflect.Array.getLength(get_any());
    i++) {
    java.lang.Object obj = java.lang.reflect.Array.get(get_any(), i);
    if (obj != null &&
    !obj.getClass().isArray()) {
    _hashCode += obj.hashCode();
    __hashCodeCalc = false;
    return _hashCode;
    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
    new org.apache.axis.description.TypeDesc(PhotoInfo.class, true);
    static {
    typeDesc.setXmlType(new javax.xml.namespace.QName("http://examples.com/PhotoCatalog/types", ">PhotoInfo"));
    org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
    elemField.setFieldName("customerName");
    elemField.setXmlName(new javax.xml.namespace.QName("", "customerName"));
    elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
    typeDesc.addFieldDesc(elemField);
    elemField = new org.apache.axis.description.ElementDesc();
    elemField.setFieldName("photoID");
    elemField.setXmlName(new javax.xml.namespace.QName("", "photoID"));
    elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
    typeDesc.addFieldDesc(elemField);
    * Return type metadata object
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
    return typeDesc;
    * Get Custom Serializer
    public static org.apache.axis.encoding.Serializer getSerializer(
    java.lang.String mechType,
    java.lang.Class _javaType, 
    javax.xml.namespace.QName _xmlType) {
    return
    new org.apache.axis.encoding.ser.BeanSerializer(
    javaType, xmlType, typeDesc);
    * Get Custom Deserializer
    public static org.apache.axis.encoding.Deserializer getDeserializer(
    java.lang.String mechType,
    java.lang.Class _javaType, 
    javax.xml.namespace.QName _xmlType) {
    return
    new org.apache.axis.encoding.ser.BeanDeserializer(
    javaType, xmlType, typeDesc);
    I guess my questions are as follows:
    1. Why is exception thrown in the first scenario? Is there something wrong with the WSDL? I guess there is, but I can't figure it out.
    2. When the change is made to the WDSL(adding <xsd:any processContents = "lax"/>) is there something that I need to add to the PhotoInfo class
    to process the org.apache.axis.message.MessageElement[] object. Do I need to "manually" parse that object in the PhotoCatalogBindingImpl class to get
    the values of customerName and photoID?
    Any other help would be appreciated..
    thanks,
    Karl Schwarz
    System Architect
    Northrop Grumman

  • Strange problem with readObject :(

    I have a classic list-type object, nothing special. I save it in a file with the writeObject method and then i read it with readObject. All works fine, but i recently discovered that if the list has too many elements (i.e. it's too big) and the file I write becomes consequently bigger (over 100Kb) I can't read it because at running time tje JVM throws a StackOverflowError.
    So my question is: how to solve this? Maybe it's a bug of the readObject() method????
    Thanks a lot!!!!

    How many elements? Homogeneous or hetrogeneous list contents?
    Have you implemented your own readObject (or any other of the various serialization hooks) anywhere? Stack overflow is normally a caused by infinite recursion through a set of methods. You would need a very deeply nested tree structure to legitimately generate such an exception during deserialization, not a linear list.
    The stack trace will be very long but the origin will show where the overflow starts. Can you post it?

  • Webservice Client deserialization problem with Vectors!

    Hello!
    I'm generating a Java Proxy Client with Eclipse WTP.
    The Client works fine with normal datatypes and own Beans. But whe the return type is a Collection with own beans an exception is thrown:
    exception: org.xml.sax.SAXException: SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize.
    So whats wrong?
    In teh Webservice Explorer everything seems to be fine, my vector is serialized in item-tags:
    - <getAktionenResponse xmlns="http://commonservice">
    - <getAktionenReturn>
    - <item xmlns="">
    <aktn_nr>a12345</aktn_nr>
    <claim>222</claim>
    <geschaeftsjahr>2005</geschaeftsjahr>
    <son>333</son>
    <special_operation_code>soc12345</special_operation_code>
    <status>ready</status>
    <vin>t123</vin>
    </item>
    - <item xmlns="">
    <aktn_nr>a6789</aktn_nr>
    <claim>567</claim>
    <geschaeftsjahr>2006</geschaeftsjahr>
    <son>555</son>
    <special_operation_code>soc6789</special_operation_code>
    <status>false</status>
    <vin>t123</vin>
    </item>
    </getAktionenReturn>
    </getAktionenResponse>
    how can i solve this problem?
    the background is that I return a vector with Java Objects. I thought apache axis deserielizes automatically the vector and the bean inside??
    I'm pretty new to webservices...
    Pleas help!
    Thanks!

    As per the below link, I assumed its better to avoid collections and go with plain array of objects.
    Please let us know if I am wrong.
    http://www-128.ibm.com/developerworks/webservices/library/ws-tip-coding.html
    Regards,
    Venkat S

  • Problem to calling readObject(java.io.ObjectInputStream) using reflection

    Hi,
    I am facing the following problem
    I have an Employee class its overridden the following below methods
    private void readObject(java.io.ObjectInputStream inStream) {
         inStream.defaultReadObject();
    I am trying to call this method using reflection.
    my code is like this
         Class fis= Class.forName("java.io.FileInputStream");
         Constructor fcons = fis.getConstructor(new Class[]{String.class});
         Object fisObj = fcons.newInstance(new Object[]{"C:\\NewEmployee.ser"});
         Class ois= Class.forName("java.io.ObjectInputStream");     
         Constructor ocons = ois.getDeclaredConstructor(new Class[]{InputStream.class});
         Object oisObj = ocons.newInstance(new Object[] {fisObj});
         Method readObj = aClass.getDeclaredMethod("readObject", new Class[]{ois});
         readObj.setAccessible(true);
         Object mapObj = readObj.invoke(employeeObj,new Object[]{oisObj});
    The above code is call the readObject method, but it is failing while executing inStream.defaultReadObject() statement
    I am getting the following exception
    java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at HackEmployee.reflect(HackEmployee.java:49)
    at HackEmployee.main(HackEmployee.java:131)
    Caused by: java.io.NotActiveException: not in call to readObject
    at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:474)
    at Employee.readObject(Employee.java:77)
    ... 6 more
    can anybody help me?
    ~ murali

    Hi,
    Here is the simple example.
    public class Employee implements Serializable {
    static final long serialVersionUID = 1L;
    static final int _VERSION = 2;
    private int eno;
    private String empName;
         private String paaword;
         private void readObject(java.io.ObjectInputStream inStream)
    throws IOException, ClassNotFoundException {
         int version = 0;
         BufferedInputStream bis = new BufferedInputStream(inStream);
         bis.mark(256);
         DataInputStream dis = new DataInputStream(bis);
         try {
              version = dis.readInt();
              Debug.println(Debug.INFO, _TAG, "Loading version=" + version);
         } catch(Exception e) {
              dis.reset();
         switch(version) {
              case 0:
              case 1:
                   inStream.defaultReadObject();
                   migrateDefaultEmployeeToEncryptionPassword();
                   break;
              case _VERSION:
                   inStream.defaultReadObject();
                   break;
              default:
                   throw new IOException("Unknown Version :" + version);
         private void writeObject(ObjectOutputStream aOutputStream)
    throws IOException {
         aOutputStream.writeInt(_VERSION);
         aOutputStream.defaultWriteObject();
    Now I am writing a tool that need to read data and print all the field and values in a file.
    So I am trying the same with reflecton by calling readObject(ObjectInputStream inStream).
    But here I am facing the problem, it is geving java.lang.reflect.InvocationTargetException while calling migrateDefaultEmployeeToEncryptionPassword(.
    Hope you got my exact scenerio.
    Thanks for your replay
    ~ Murali

  • XML deserialize and decrypting encoding problem. Please help me

    This is my first topic here, so at first I'd like to say "Hi" everyone and apologise for my bad english ;)
    I have just finished my new application about signing/checking and encrypting/decrypting XML files. I use Apache XML Security packages to do this.
    Everything works fine, instead of one...
    I'm Polish and sometimes I have to encrypt or decrypt XML which includes polish letters like: '&#261;' , '&#281;', '&#322;' and some others... If I encrypt such file, it succeeds. The problem is when I try to decrypt such an encrypted file. I recieve an error like :
    "[Fatal Error] :2:7: An invalid XML character (Unicode: 0x19) was found in the element content o
    f the document.
    gov.mf.common.exceptions.SenderException: E_SENDER_DECRYPTION
    at gov.mf.common.xml.encryption.EncryptTool.decrypt(Unknown Source)
    at gov.mf.CERBER.TestCBR.main(Unknown Source)
    Caused by: org.apache.xml.security.encryption.XMLEncryptionException: An invalid XML character
    (Unicode: 0x19) was found in the element content of the document.
    Original Exception was org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0x19)
    was found in the element content of the document.
    at org.apache.xml.security.encryption.XMLCipher$Serializer.deserialize(Unknown Source)
    at org.apache.xml.security.encryption.XMLCipher.decryptElement(Unknown Source)
    at org.apache.xml.security.encryption.XMLCipher.doFinal(Unknown Source)
    ... 2 more
    What's wrong? My XML document is UTF-8 encoded, with or without BOM. I wrote in in Notepad++ or any other editior which has UTF-8 encoding.
    I'm parsing my XML with DOM. There is an interesting line in an error above like: " at org.apache.xml.security.encryption.XMLCipher$Serializer.deserialize(Unknown Source)" , do you know that?
    Everything is fine when I try to encrypt/decrypt '�' or '&#324;', but things go wrong with '&#261;', '&#281;', '&#322;' and others... I also managed to encrypt and decrypt '&#322;' but unfortunately, after decryption '&#322;' turns into 'B'. It obviously an encoding problem, but how to fix it?
    I would be really thankfull if some of You guys would help me.
    Looking forward fo any answers.
    Matthew
    Message was edited by:
    matthew_pl

    Hi once again.
    I still don't havy any solution to my problem. I used Apache XML Security examples to encrypt/decrypt my XML document with Polish charaters but I also recieve the same error. What's wrong?
    Here is some code:
    ----- Parsing XML do Document ------
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         //Bardzo wazna linijka - bless TEK ;)
         factory.setNamespaceAware(true);
         DocumentBuilder builder;
         builder = factory.newDocumentBuilder();
         File f = new File(Const.FILE_IN_PATH + File.separator + Const.FILE_IN);     
         org.w3c.dom.Document doc = builder.parse(f);
    ---------- Encrypting & Decrypting XML document (whole class) -------------
    import java.io.*;
    import java.security.*;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESedeKeySpec;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.apache.xml.security.keys.KeyInfo;
    import org.apache.xml.security.utils.EncryptionConstants;
    import org.apache.xml.security.encryption.XMLCipher;
    import org.apache.xml.security.encryption.EncryptedData;
    import org.apache.xml.security.encryption.EncryptedKey;
    public class EncryptTool
    private PublicKey publicKey;     
    private PrivateKey privateKey;
    static
    org.apache.xml.security.Init.init();
    public EncryptTool()
         publicKey = KeyStores.getCerberPublicKey();
         privateKey = KeyStores.getCerberPrivateKey();
    public Document encrypt(Document doc, String sufix)
    try
         byte[] passPhrase = "24 Bytes per DESede key!".getBytes("UTF-8");
         DESedeKeySpec keySpec = new DESedeKeySpec(passPhrase);
         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
         SecretKey secretKey = keyFactory.generateSecret(keySpec);
         XMLCipher keyCipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
         keyCipher.init(XMLCipher.WRAP_MODE, publicKey);
         EncryptedKey encryptedKey = keyCipher.encryptKey(doc, secretKey);
              Element elementToEncrypt = (Element) doc.getDocumentElement();
              System.out.println("Szyrfuj&#281;: " + elementToEncrypt.getTextContent());
              XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
              xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
              EncryptedData encryptedDataElement = xmlCipher.getEncryptedData();
              KeyInfo keyInfo = new KeyInfo(doc);
              keyInfo.add(encryptedKey);
              encryptedDataElement.setKeyInfo(keyInfo);
              boolean encryptContentsOnly = true;
              xmlCipher.doFinal(doc, elementToEncrypt, encryptContentsOnly);
              // output the resulting document
              String [] parts = Const.FILE_IN.split("\\.");
              String saveAs = Const.FILE_OUT_PATH + File.separator + parts[0] + sufix + "." + parts[1];
              OutputStream os = new FileOutputStream(saveAs);
              XMLUtil.sameXMLtoFile(doc, os);
    } catch (Exception ex)
         throw new TestCBRException("E_CERBER_ENCRYPTION", ex);
    return doc;
    public void decrypt(Document doc, String sufix) throws SenderException
    try
              String namespaceURI = EncryptionConstants.EncryptionSpecNS;
         String localName = EncryptionConstants._TAG_ENCRYPTEDDATA;
         int ile = doc.getElementsByTagNameNS(namespaceURI, localName).getLength();
         if (ile == 0) throw new SenderException("E_SENDER_DECRYPTION_NEEDED");
         for(int i=0; i < ile; i++)
         Element encryptedDataElement = (Element) doc.getElementsByTagNameNS(namespaceURI, localName).item(0);
         XMLCipher xmlCipher = XMLCipher.getInstance();
         xmlCipher.init(XMLCipher.DECRYPT_MODE, null);
         xmlCipher.setKEK(privateKey);
         xmlCipher.doFinal(doc, encryptedDataElement);
                   String [] parts = Const.FILE_IN.split("\\.");
                   String saveAs = Const.FILE_OUT_PATH + parts[0] + sufix + "." + parts[1];
                   OutputStream os = new FileOutputStream(saveAs);
                        XMLUtil.saveXMLtoFile(doc, os);
    } catch (SenderException ex) {
         throw ex;
    } catch (Exception ex) {
         throw new SenderException("E_SENDER_DECRYPTION", ex);
    Please help me. I'm going into madness what's wrong with it...

  • ReadObject() / refreshObject() / mergeClone() problems / questions...

    Long story as short as I can make it...
    We want to make changes to an object outside a unit of work (it's a longer story)...
    and then when we're done making changes, get a clean copy of the object from the
    database in a unitOfWork, apply our changes to this, and then commit...
    I've got an object:
    (1) Customer changedCustomer = getCustomerToChange();
    (2)changedCustomer.setCode("123");
    I was hoping to do something like the following:
    (3) UnitOfWork uow = clientSession.getUnitOfWork();
    (4) Customer existingCustom = new Customer();
    (5) existingCustomer.setId(changedCustomer.getId());
    (6) existingCustomer = uow.readObject(existingCustomer); // Get a clean copy of the customer
    (7) existingCustomer = (CustomerBO)uow.registerObject(existingCustomer);
    (8) existingCustomer = uow.mergeClone(changedCustomer); // Apply our changes...
    (9) uow.commit(); // commit...
    The problem is that after line (6), existingCustomer.getCode() returns "123",
    rather than the value that is stored in the database... So existingCustomer
    is coming from out cache(?) rather than being loaded clean from the database, and
    TOPLink doesn't see that the code has changed in lines 8/9...
    I tried a call to refreshObject() to ensure I'm getting a clean copy from the database:
    (6.5) existingCustomer = uow.refreshObject(existingCustomer);
    After this, getCode() returns the value from the database, as expected... BUT(!)
    changedCustomer.getCode now also returns the value from the database... changedCustomer
    and existing customer have different hashCode() values...
    Am I missing something? Is what I am trying possible?
    Chris

    Chris
    You're probably trying to do changes on the original object.
    I suppose your method getCustomerToChange() returns an object read through a "session.readObject(...)" or something like that.
    Then you modify it in (2).
    At step (6) you try to read the original, but you get a clone of the one you modified at step (2)!
    And when you try to do a refresh (6.5) you replace the original object you modifed in step (2) with the database value.
    You souldn't modify an object read through the session.
    Use the uow to read it or do the modifications on a copy instead.
    Ivan

  • Problem with deserialization

    Hi All
    I am stuck in a problem for which I need your help.
    I have used VitalCategoryEnum.java and provided a typemapping in the wsdd as follows
    <typeMapping
    xmlns:ns="http://localhost/hth/services/Equipment?wsdl"
    qname="ns:VitalCategoryEnum"
    type="java:com.march.hth.client.VitalCategoryEnum"
    serializer="org.apache.axis.encoding.ser.BeanSerializerFactory"
    deserializer="org.apache.axis.encoding.ser.BeanDeserializerFactory"
    encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
    />
    The code for VitalCategoryEnum.java class is not generating in the WSDL file.
    When I run my client which I have written for a business method.i get the following exception.
    - Exception:
    org.xml.sax.SAXException: No deserializer for {http://localhost/hth/services/Equipment?wsdl}VitalCategoryEnum
    I have provided the typemapping that is needed but still I am getting this error.
    I am not able to figure out whats wrong here. The same thing works in other session beans .
    Please let me know what should be done in this case
    Regards
    Vikram K

    Are you sure that your object gets serialized in the first place? You could use the writeObject method (explained in Javadoc for java.io.Serializable) to snoop the process.
    I am actually surprised you can serialize a DOM document.
    /Sebastian

Maybe you are looking for