Class: Cicada::Serialization

Inherits:
Object
  • Object
show all
Defined in:
lib/cicada/file_interaction.rb

Overview

Handles the serialization of the ImageObjects for storing them in a file.

The serialized output will consist of an XML file describing the objects in human-readable form and including a binary data sectiobn containing the serialized object. This binary section is the only thing read back in, so changing the XML human-readable portion of the file manually will not affect the data read back in.

Class Method Summary collapse

Class Method Details

.image_object_from_bytes(bin_data) ⇒ ImageObject

Restores an image object from a byte string.

Parameters:

  • bin_data (String)

    the bytes representing the image object. This should be a standard byte string. The XML files use base64 encoding, and the data should already be unencoded.

Returns:

  • (ImageObject)

    the encoded ImageObject



91
92
93
94
95
96
97
98
99
100
101
# File 'lib/cicada/file_interaction.rb', line 91

def self.image_object_from_bytes(bin_data)

  Marshal.load(bin_data)

  #j_bytes = bin_data.to_java_bytes

  #oi = Java::java.io.ObjectInputStream.new(Java::java.io.ByteArrayInputStream.new(j_bytes))

  #oi.readObject

end

.serialize_image_objects(image_objects) ⇒ String

Converts an array of ImageObjects to an XML-formatted string containing the serialized data.

Parameters:

  • image_objects (Enumerable<ImageObject>)

    an Enumerable list of image objects

Returns:

  • (String)

    a string containing formatted XML and binary representations of the image objects.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/cicada/file_interaction.rb', line 57

def self.serialize_image_objects(image_objects)

  doc = REXML::Document.new


  doc.add_element "root"

  image_objects.each do |iobj|

    in_doc = REXML::Document.new iobj.writeToXMLString

    in_doc.root.elements[1, "serialized_form"].text = Base64.encode64(Marshal.dump(iobj))

    doc.root.add in_doc.elements[1,"image_object"]

  end

  output = ""

  doc.write(output, 2)

  output

end

.unserialize_image_objects(data) ⇒ Array<ImageObject>

Restores image objects from an XML string containing their serialized representation. (This uses the base64 encoded binary information in the XML file, not the human readable portion.)

Parameters:

  • data (String)

    the XML string

Returns:

  • (Array<ImageObject>)

    the image objects encoded in the string



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/cicada/file_interaction.rb', line 111

def self.unserialize_image_objects(data)

  objs = []

  doc = REXML::Document.new data

  doc.elements.each("*/image_object/serialized_form") do |el|

    bin_data = Base64.decode64(el.text)

    objs << image_object_from_bytes(bin_data)

  end

  objs

end