object serialization/deserialization

Internet resources

Implementation

  • Serialize the object using ‘ObjectOutputStream’
  • the object can be transformed in string or byte[]
  • Republish the application
  • Objective: use the new dataexoprter feature

Implementation example

 public byte[] serializeEntity( Webuser entity_arg ) {
        try {
            //serialization
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream( bos );

            oos.writeObject( entity_arg );
            oos.flush();
            oos.close();
            bos.close();

            byte[] data = bos.toByteArray();
            logger.trace( "Object serialized(Byte)(" + data.toString().getBytes() + ")" );
            logger.trace( "Object serialized(String)(" + bos.toString() + ")" );
            
            //Deserialization
            ByteArrayInputStream bis = new ByteArrayInputStream( data );
            ObjectInputStream sis = new ObjectInputStream( bis );
            Webuser obj = (Webuser) sis.readObject();
            // the properties of the object have been 
            logger.trace( "Object deserialized(id)(" + obj.getId() + ")" );
            logger.trace( "Object deserialized(name)(" + obj.getName() + ")" );

            return data;
        } catch ( Exception e ) {
            System.out.println( e.getMessage() );
            System.out.println( e.toString() );
            e.printStackTrace();
            FacesMessage msg = new FacesMessage( "Entity cannot be serialized" );
            FacesContext.getCurrentInstance().addMessage( null, msg );
            return null;
        }
    }

Tips

  • see code example
  • the serialized object can be stored in any database table as ‘string’ or ‘byte[]’

Next steps

  • none