Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2010
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1. // Writing
  2. AddressBookProtos.Person.Builder personBuilder = AddressBookProtos.Person.newBuilder();
  3. personBuilder.setId(1);
  4. personBuilder.setName("Galder Zamarreño");
  5. personBuilder.setEmail("galder@galder.com");
  6. AddressBookProtos.Person person = personBuilder.build();
  7. hotRodClient.put("me", person);
  8.  
  9. // Writing marshaller
  10. public byte[] objectToByteBuffer(Object o) throws Exception {
  11.   ByteArrayOutputStream baos = new ByteArrayOutputStream();
  12.   Message message = (Message) o;
  13.   byte[] name = message.getDescriptorForType().getFullName().getBytes("UTF-8");
  14.   baos.write(name.length); // TODO: Send length as int and not byte
  15.   baos.write(name);
  16.   byte[] messageBytes = message.toByteArray();
  17.   baos.write(messageBytes.length); // TODO: Send length as int and not byte
  18.   baos.write(messageBytes);
  19.   return baos.toByteArray();
  20. }
  21.  
  22. // Reading marshaller
  23. public Object objectFromByteBuffer(byte[] buffer) throws Exception {
  24.    ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
  25.    byte[] name = new byte[bais.read()];
  26.    bais.read(name); // TODO: Read fully??
  27.    String className = mapping.get(new String(name, "UTF-8"));
  28.    Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
  29.    Method parseFromMethod = clazz.getMethod("parseFrom", byte[].class);
  30.    byte[] message = new byte[bais.read()];
  31.    bais.read(message); // TODO: Read fully??
  32.    return parseFromMethod.invoke(null, message);
  33. }
  34.  
  35. // Mapping of proto language descriptor name and class name shown below:
  36. FileDescriptorSet descriptorSet = FileDescriptorSet.parseFrom(new FileInputStream("src/main/desc/addressbook.desc"));
  37. for (FileDescriptorProto fdp: descriptorSet.getFileList()) {
  38.    FileDescriptor fd = FileDescriptor.buildFrom(fdp, new FileDescriptor[]{});
  39.    for(Descriptor descriptor : fd.getMessageTypes()) {
  40.       String className = fdp.getOptions().getJavaPackage() + "." + fdp.getOptions().getJavaOuterClassname() + "$" + descriptor.getName();
  41.       mapping.put(descriptor.getFullName(), className);
  42.     }
  43. }
  44.  
  45. // Reading
  46. AddressBookProtos.Person person = hotRodClient.get("me");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement