Class: Divine::JavaHelperMethods
- Inherits:
-
BabelHelperMethods
- Object
- BabelHelperMethods
- Divine::JavaHelperMethods
- Defined in:
- lib/divine/code_generators/java.rb
Overview
-
Java Helper :
Support base function needed to build Divine enviroment and classes corresponding to DSL structs
Direct Known Subclasses
Instance Method Summary collapse
-
#get_header_comment ⇒ Object
Return the header comment.
-
#java_base_class_template_str ⇒ Object
Generate the base Divine Java Class that contains the main methods: * serialize * serialize Internal * deserialize * Read Methods * Write Methods.
-
#java_class_template(sh) ⇒ Object
Generate Java Class that corresponding to the struct definition * Args : -
sh
-> Struct Name. -
#java_deserialize_internal(var, types) ⇒ Object
Generate the way of deserializing different DSL types * Args : -
var
-> variable name -types
-> variable type. -
#java_get_empty_declaration(types, is_reference_type = false) ⇒ Object
Generate default java data types declaration values corresponding to each DSL types: * DSL Type –> Corresponding Default Java Value * dint63 –> 0 range -> [0 - 9,223,372,036,854,775,807] * 1 byte: range -> [0 - 127] * 2 bytes: range -> [0 - 16,383] * 3 bytes: range -> [0 - 2,097,151] * 4 bytes: range -> [0 - 268,435,455] * 5 bytes: range -> [0 - 34,359,738,367] * 6 bytes: range -> [0 - 4,398,046,511,103] * 7 bytes: range -> [0 - 562,949,953,421,311] * 8 bytes: range -> [0 - 72,057,594,037,927,935] * 9 bytes: range -> [0 - 9,223,372,036,854,775,807] * int8 –> 0 Range -> [0 - 255] * int16 –> 0 Range -> [0 - 65535] * int32 –> 0L Range -> [0 - 4.294.967.295] * sint32 –> 0 Range -> [-2.147.483.648 - 2.147.483.647] * sint64 –> 0L Range -> [-9.223.372.036.854.775.808, 9.223.372.036.854.775.807] * string –> “” * ip_number–> “” * binary –> new Byte * short_binary –> new Byte * list –> new ArrayList<type>() * map –> new HashMap<keyType, valueType>().
-
#java_get_type_declaration(types, is_reference_type = false) ⇒ Object
Generate java data types declaration corresponding to each DSL type * DSL Type –> Corresponding Java Type * int8 –> int * int16 –> int * sint32 –> int * int32 –> long * sint64 –> long * dint63 –> long * string –> String * ip_number–> String * binary –> Byte[] * short_binary –> Byte[] * list –> ArrayList<type> * map –> HashMap<keyType, valueType>.
-
#java_serialize_internal(var, types) ⇒ Object
Generate the way of serializing different DSL types * Args : -
var
-> variable name -types
-> variable type.
Methods inherited from BabelHelperMethods
#camelize, #format_src, #get_fresh_variable_name, #get_header_comment_text, #sanity_check
Instance Method Details
#get_header_comment ⇒ Object
Return the header comment
12 13 14 15 16 |
# File 'lib/divine/code_generators/java.rb', line 12 def get_header_comment get_header_comment_text.map do |s| "// #{s}" end.join("\n") end |
#java_base_class_template_str ⇒ Object
Generate the base Divine Java Class that contains the main methods:
-
serialize
-
serialize Internal
-
deserialize
-
Read Methods
-
Write Methods
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
# File 'lib/divine/code_generators/java.rb', line 27 def java_base_class_template_str <<EOS abstract class Divine <%= toplevel_class %> { private static final Charset UTF8 = Charset.forName("UTF-8"); public byte[] serialize() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializeInternal(baos); baos.close(); return baos.toByteArray(); } abstract void serializeInternal(ByteArrayOutputStream baos) throws IOException; abstract void deserialize(ByteArrayInputStream baos) throws IOException; protected int readInt8(ByteArrayInputStream data) { return data.read() & 0xff; } protected int readInt16(ByteArrayInputStream data) { return (data.read() << 8) | readInt8(data); } protected int readInt24(ByteArrayInputStream data) { return (data.read() << 16) | readInt16(data); } protected long readInt32(ByteArrayInputStream data) { return (data.read() << 24) | readInt24(data); } protected int readSint32(ByteArrayInputStream data) { return (data.read() << 24) | readInt24(data); } protected long readSint64(ByteArrayInputStream data) { return (readInt32(data) << 32) | (readInt32(data) & 0xFFFFFFFFL); } protected long readDint63(ByteArrayInputStream data) { int b = readInt8(data); long val = b & 0x7F; while((b >> 7) == 1){ b = readInt8(data); val = val << 7; val = val | b & 0x7F; } return val; } protected boolean readBool(ByteArrayInputStream data) { return readInt8(data) == 1; } protected String readString(ByteArrayInputStream data) throws IOException { // Force utf8 return new String(readBytes(readInt16(data), data), UTF8); } private byte[] readBytes(int size, ByteArrayInputStream data) throws IOException { byte[] bs = new byte[size]; data.read(bs); return bs; } protected byte[] readBinary(ByteArrayInputStream data) throws IOException { long c = readInt32(data); if (c > Integer.MAX_VALUE) { throw new IndexOutOfBoundsException("Binary data to big for java"); } return readBytes((int) c, data); } protected byte[] readShortBinary(ByteArrayInputStream data) throws IOException { return readBytes(readInt8(data), data); } protected String readIpNumber(ByteArrayInputStream data) throws IOException { byte[] ips = readShortBinary(data); if(ips.length == 4){ return readIpv4Number(ips); } else{ return readIpv6Number(ips); } } protected String readIpv4Number(byte[] ips){ String ip = ""; for (byte b : ips) { if (ip.length() > 0) { ip += "."; } ip += (b & 0xFF); } return ip; } protected String readIpv6Number(byte[] ips) throws IOException { String ip = ""; int part1, part2; for (int i = 0; i < ips.length; i+=2) { part1 = ips[i] & 0xFF; part2 = ips[i+1] & 0xFF; ip += part1 == 0? "" : Integer.toHexString(part1); ip += (part1 == 0 && part2 == 0)? "" : (part2 < 10 && part1 != 0? "0" + Integer.toHexString(part2): Integer.toHexString(part2)); if (i < ips.length-2) { ip += ":"; } } ip = ip.replaceAll(":{3,}", "::"); return ip; } protected void writeInt8(int v, ByteArrayOutputStream out) { if (v > 0xFF) { // Max 255 raiseError("Too large int8 number: " + v); }else if(v < 0){ raiseError("a negative number passed to int8 number: " + v); } out.write(v); } protected void writeInt16(int v, ByteArrayOutputStream out) { if (v > 0xFFFF) { // Max 65.535 raiseError("Too large int16 number: " + v); }else if(v < 0){ raiseError("a negative number passed to int16 number: " + v); } writeInt8(v >> 8 & 0xFF, out); writeInt8(v & 0xFF, out); } protected void writeInt24(int v, ByteArrayOutputStream out) { if (v > 0xFFFFFF) { // Max 16.777.215 raiseError("Too large int24 number: " + v); }else if(v < 0){ // In Case added to Java declaration raiseError("a negative number passed to int24 number: " + v); } writeInt8(v >> 16 & 0xFF, out); writeInt16(v & 0xFFFF, out); } protected void writeInt32(long v, ByteArrayOutputStream out) { if (v > 0xFFFFFFFFL) { // Max 4.294.967.295 raiseError("Too large int32 number: " + v); }else if(v < 0){ raiseError("a negative number passed to int32 number: " + v); } writeInt8((int) ((v >> 24) & 0xFF), out); writeInt24((int) (v & 0xFFFFFF), out); } protected void writeSint32(int v, ByteArrayOutputStream out) { if (v > Integer.MAX_VALUE) { // Max 2.147.483.647 raiseError("Too large sInt32 number: " + v + ", Max = " + Integer.MAX_VALUE); }else if(v < Integer.MIN_VALUE){ // Min -2.147.483.648 raiseError("Too small sInt32 number: " + v + ", Min = " + Integer.MIN_VALUE); } writeInt8((int) ((v >> 24) & 0xFF), out); writeInt24((int) (v & 0xFFFFFF), out); } protected void writeSint64(long v, ByteArrayOutputStream out) { if (v > Long.MAX_VALUE) { // Max 9,223,372,036,854,775,807 raiseError("Too large sInt64 number: " + v + ", Max = " + Long.MAX_VALUE); }else if(v < Long.MIN_VALUE){ // Min -9,223,372,036,854,775,808 raiseError("Too small sInt64 number: " + v + ", Min = " + Long.MIN_VALUE); } writeInt32(((v >> 32) & 0xFFFFFFFFL), out); writeInt32( (v & 0xFFFFFFFFL) , out); } protected void writeDint63(long v, ByteArrayOutputStream out) { if (v > Long.MAX_VALUE) { // Max 9,223,372,036,854,775,807 raiseError("Too large Dynamic Int64 number: " + v + ", Max = " + Long.MAX_VALUE); }else if(v < 0){ // Min 0 raiseError("Too small Dynamic Int64 number: " + v + ", Min = " + 0); } String[] bytes = new StringBuffer(Long.toBinaryString(v)).reverse().toString().split("(?<=\\\\G.......)"); for (int i = bytes.length - 1; i >= 0; i--){ String s = bytes[i]; s += new String(new char[7 - s.length()]).replace("\\\\0", "0") + Math.min(i, 1); int t = Integer.parseInt(new StringBuffer(s).reverse().toString(), 2); this.writeInt8(t, out); } } protected void writeBool(boolean v, ByteArrayOutputStream out) { writeInt8(v ? 1 : 0, out); } protected void writeString(String v, ByteArrayOutputStream out) throws IOException { byte[] bs = v.getBytes(UTF8); if (bs.length > 0xFFFF) { raiseError("Too large string: " + bs.length + " bytes"); } writeInt16(bs.length, out); out.write(bs); } protected void writeBinary(byte[] v, ByteArrayOutputStream out) throws IOException { if (v.length > 0xFFFFFFFFL) { raiseError("Too large binary: " + v.length + " bytes"); } writeInt32(v.length, out); out.write(v); } protected void write16Binary(int[] v, ByteArrayOutputStream out) throws IOException { if (v.length > 0xFF) { raiseError("Too large 16_binary: " + (v.length*2) + " bytes"); } writeInt8(v.length*2, out); for(int i = 0; i < v.length; i++){ this.writeInt16(v[i], out); } } protected void writeShortBinary(byte[] v, ByteArrayOutputStream out) throws IOException { if (v.length > 0xFF) { raiseError("Too large short_binary: " + v.length + " bytes"); } writeInt8(v.length, out); out.write(v); } protected void writeIpNumber(String v, ByteArrayOutputStream out) throws IOException { if(v.contains(":")){ writeIpv6Number( v, out); }else{ writeIpv4Number( v, out); } } protected void writeIpv4Number(String v, ByteArrayOutputStream out) throws IOException { byte[] ss = new byte[0]; if(!v.isEmpty()){ String[] bs = v.split("\\\\."); ss = new byte[bs.length]; for (int i = 0; i < bs.length; i++) { ss[i] = (byte) (Integer.parseInt(bs[i]) & 0xFF); } } if (ss.length == 0 || ss.length == 4) { writeShortBinary(ss, out); } else { raiseError("Unknown IP v4 number " + v); // Only IPv4 for now } } protected void writeIpv6Number(String v, ByteArrayOutputStream out) throws IOException { v = v.replaceAll(" ", "") + " "; // Temporary: To avoid the split problem when we have : at the // end of "v" int[] ss = new int[0]; boolean contains_ipv6_letters = Pattern.compile("[0-9a-f]+").matcher( v.trim().toLowerCase()).find(); boolean contains_other_letters = Pattern.compile("[^:0-9a-f]+") .matcher(v.trim().toLowerCase()).find(); // make sure of v must have only one "::" and no more than two of ":". // e.g. 1::1::1 & 1:::1:205 if (!v.trim().isEmpty() && v.split(":{3,}").length == 1 && v.split(":{2}").length <= 2 && !contains_other_letters && contains_ipv6_letters) { String[] bs = v.split(":"); ss = new int[bs.length]; for (int i = 0; i < bs.length; i++) { String s = bs[i].trim(); if (s.length() <= 4) // to avoid such number 0125f ss[i] = Integer.parseInt( (s.isEmpty() ? "0" : bs[i].trim()), 16); else raiseError("Unknown IPv6 Group " + i + " which is " + s); } } // Check for make sure of the size of the IP groups in case "::" is used // [> 2 & < 8]or not [must == 8] if (!contains_other_letters && (!v.contains("::") && ss.length == 0 || ss.length == 8) || (v.contains("::") && ss.length > 2 && ss.length < 8)) { write16Binary(ss, out); } else { raiseError("Unknown IP v6 number " + v); } } protected void raiseError(String msg) { throw new IllegalArgumentException("[" + this.getClass().getCanonicalName() + "] " + msg); } } EOS end |
#java_class_template(sh) ⇒ Object
Generate Java Class that corresponding to the struct definition
* *Args* :
- +sh+ -> Struct Name
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
# File 'lib/divine/code_generators/java.rb', line 327 def java_class_template(sh) code = [ "class #{sh.name} extends Divine {", :indent, "", # PROPERTIES "public int struct_version = #{sh.latest_version};", sh.field_names.map do |fn| f = sh.field(fn).last "public #{java_get_type_declaration(f)} #{fn} = #{java_get_empty_declaration(f)};" end, "", # SERiALIZE INTERNAL "@Override", "void serializeInternal(ByteArrayOutputStream baos) throws IOException {", :indent, "writeInt8(this.struct_version, baos);", sh.structs.map do |s| [ "if(this.struct_version == #{s.version}) {", :indent, s.simple_fields.map do |f| "#{camelize("write", f.type)}(this.#{f.name}, baos);" end, s.complex_fields.map do |f| [ "", "// Serialize #{f.type} '#{f.name}'", java_serialize_internal("this.#{f.name}", f.referenced_types) ] end, "return;", :deindent, "}", "" ] end, "", "throw new UnsupportedOperationException(\"Unsupported version \" + this.struct_version + \" for type '#{sh.name}'\");", :deindent, "}", "", # DESERIALIZE "@Override", "public void deserialize(ByteArrayInputStream bais) throws IOException {", :indent, "this.struct_version = readInt8(bais);", sh.structs.map do |s| [ "if(this.struct_version == #{s.version}) {", :indent, s.simple_fields.map do |f| "this.#{f.name} = #{camelize("read", f.type)}(bais);" end, s.complex_fields.map do |f| [ "", "// Read #{f.type} '#{f.name}'", java_deserialize_internal("this.#{f.name}", f.referenced_types) ] end, "return;", :deindent, "}" ] end, "", "throw new UnsupportedOperationException(\"Unsupported version \" + this.struct_version + \" for type '#{sh.name}'\");", :deindent, "}", "", # END OF CLASS :deindent, "}" ] format_src(3, 3, code) end |
#java_deserialize_internal(var, types) ⇒ Object
Generate the way of deserializing different DSL types
* *Args* :
- +var+ -> variable name
- +types+ -> variable type
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 |
# File 'lib/divine/code_generators/java.rb', line 577 def java_deserialize_internal(var, types) if types.respond_to? :first case types.first when :list count = get_fresh_variable_name nv = get_fresh_variable_name iter = get_fresh_variable_name return [ "#{"#{java_get_type_declaration(types)} " unless var.include? "this."}#{var} = #{java_get_empty_declaration(types)};", "int #{count} = (int)this.readInt32(bais);", "for(int #{iter}=0; #{iter}<#{count}; #{iter}++) {", :indent, java_deserialize_internal(nv, types[1]), "#{var}.add(#{nv});", :deindent, "}" ] when :map count = get_fresh_variable_name nv1 = get_fresh_variable_name nv2 = get_fresh_variable_name iter = get_fresh_variable_name return ["#{"#{java_get_type_declaration(types)} " unless var.include? "this."}#{var} = #{java_get_empty_declaration(types)};", "int #{count} = (int)readInt32(bais);", "for(int #{iter}=0; #{iter}<#{count}; #{iter}++) {", :indent, java_deserialize_internal(nv1, types[1]), java_deserialize_internal(nv2, types[2]), "#{var}.put(#{nv1}, #{nv2});", :deindent, "}" ] else raise "Missing serialization for #{var}" end else # case types # when :map # "#{var} = #{java_get_empty_declaration(types)}" # when :list # "#{var} = #{java_get_empty_declaration(types)}" # else if $all_structs.key? types [ "#{types} #{var} = new #{types}();", "#{var}.deserialize(bais);" ] else "#{"#{java_get_type_declaration(types)} " unless var.include? "this."}#{var} = #{self.camelize("read", types)}(bais);" end # end end end |
#java_get_empty_declaration(types, is_reference_type = false) ⇒ Object
Generate default java data types declaration values corresponding to each DSL types:
* DSL Type --> Corresponding Default Java Value
* dint63 --> 0 range -> [0 - 9,223,372,036,854,775,807]
* 1 byte: range -> [0 - 127]
* 2 bytes: range -> [0 - 16,383]
* 3 bytes: range -> [0 - 2,097,151]
* 4 bytes: range -> [0 - 268,435,455]
* 5 bytes: range -> [0 - 34,359,738,367]
* 6 bytes: range -> [0 - 4,398,046,511,103]
* 7 bytes: range -> [0 - 562,949,953,421,311]
* 8 bytes: range -> [0 - 72,057,594,037,927,935]
* 9 bytes: range -> [0 - 9,223,372,036,854,775,807]
* int8 --> 0 Range -> [0 - 255]
* int16 --> 0 Range -> [0 - 65535]
* int32 --> 0L Range -> [0 - 4.294.967.295]
* sint32 --> 0 Range -> [-2.147.483.648 - 2.147.483.647]
* sint64 --> 0L Range -> [-9.223.372.036.854.775.808, 9.223.372.036.854.775.807]
* string --> ""
* ip_number--> ""
* binary --> new Byte[0]
* short_binary --> new Byte[0]
* list --> new ArrayList<type>()
* map --> new HashMap<keyType, valueType>()
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 |
# File 'lib/divine/code_generators/java.rb', line 430 def java_get_empty_declaration(types, is_reference_type = false) if types.respond_to? :referenced_types java_get_empty_declaration(types.referenced_types) elsif types.respond_to?(:first) && types.size > 1 case types.first when :list "new #{java_get_type_declaration(types, true)}()" when :map "new #{java_get_type_declaration(types, true)}()" else raise "Missing empty declaration for #{types}" end elsif types.respond_to?(:first) && types.size == 1 java_get_empty_declaration(types.first, is_reference_type) else case types when :binary, :short_binary is_reference_type ? "new Byte[0]" : "new byte[0]" when :int8, :int16, :sint32 "0" when :int32, :sint64, :dint63 "0L" when :string, :ip_number "\"\"" else if $all_structs[types] types else raise "Unkown field type #{types}" end end end end |
#java_get_type_declaration(types, is_reference_type = false) ⇒ Object
Generate java data types declaration corresponding to each DSL type
* DSL Type --> Corresponding Java Type
* int8 --> int
* int16 --> int
* sint32 --> int
* int32 --> long
* sint64 --> long
* dint63 --> long
* string --> String
* ip_number--> String
* binary --> Byte[]
* short_binary --> Byte[]
* list --> ArrayList<type>
* map --> HashMap<keyType, valueType>
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
# File 'lib/divine/code_generators/java.rb', line 483 def java_get_type_declaration(types, is_reference_type = false) if types.respond_to? :referenced_types java_get_type_declaration(types.referenced_types, is_reference_type) elsif types.respond_to?(:first) && types.size > 1 case types.first when :list subtypes = java_get_type_declaration(types[1], true) return "ArrayList<#{subtypes}>" when :map key_type = java_get_type_declaration(types[1], true) value_type = java_get_type_declaration(types[2], true) return "HashMap<#{key_type}, #{value_type}>" else raise "Missing serialization for #{types}" end elsif types.respond_to?(:first) && types.size == 1 java_get_type_declaration(types.first, is_reference_type) else case types when :binary, :short_binary is_reference_type ? "Byte[]" : "byte[]" when :int8, :int16, :sint32 is_reference_type ? "Integer" : "int" when :int32, :sint64, :dint63 is_reference_type ? "Long" : "long" when :string, :ip_number "String" else if $all_structs[types] types else raise "Unkown field type #{types}" end end end end |
#java_serialize_internal(var, types) ⇒ Object
Generate the way of serializing different DSL types
* *Args* :
- +var+ -> variable name
- +types+ -> variable type
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 |
# File 'lib/divine/code_generators/java.rb', line 528 def java_serialize_internal(var, types) if types.respond_to? :first case types.first when :list nv = get_fresh_variable_name idx = get_fresh_variable_name return [ "writeInt32(#{var}.size(), baos);", "for(int #{idx}=0; #{idx}<#{var}.size(); #{idx}++) {", :indent, "#{java_get_type_declaration types[1]} #{nv} = #{var}.get(#{idx});", java_serialize_internal(nv, types[1]), :deindent, "}" ] when :map nv1 = get_fresh_variable_name nv2 = get_fresh_variable_name return [ "writeInt32(#{var}.size(), baos);", "for(#{java_get_type_declaration types[1]} #{nv1} : #{var}.keySet()) {", :indent, "#{java_get_type_declaration types[2]} #{nv2} = #{var}.get(#{nv1});", java_serialize_internal(nv1, types[1]), java_serialize_internal(nv2, types[2]), :deindent, "}" ] else raise "Missing serialization for #{var}" end else if $all_structs[types] "#{var}.serializeInternal(baos);" elsif $available_types[types] && $available_types[types].ancestors.include?(SimpleDefinition) "#{self.camelize "write", types}(#{var}, baos);" else raise "Missing code generation case #{types}" end end end |