Packet.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package de.tudarmstadt.informatik.hostage.wrapper;
  2. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  3. /**
  4. * Wrapper class for IO content.
  5. * @author Wulf Pfeiffer
  6. */
  7. public class Packet {
  8. private byte[] message = null;
  9. private boolean isStringMsg = false;
  10. private boolean isByteMsg = false;
  11. /**
  12. * Constructor.
  13. */
  14. public Packet() {
  15. message = null;
  16. }
  17. /**
  18. * Constructor.
  19. * If Packet is created with a String value, it is marked with a boolean.
  20. * @param message
  21. */
  22. public Packet(String message) {
  23. this.message = message.getBytes();
  24. isStringMsg = true;
  25. }
  26. /**
  27. * Constructor.
  28. * If Packet is created with a byte[] value, it is marked with a boolean.
  29. * @param message
  30. */
  31. public Packet(byte[] message) {
  32. this.message = message;
  33. isByteMsg = true;
  34. }
  35. /**
  36. * Returns the message value as byte[].
  37. * @return message value
  38. */
  39. public byte[] getMessage() {
  40. return message;
  41. }
  42. /**
  43. * Returns the class which the Packet was created with.
  44. * If the string constructor was used it returns String.class.
  45. * If the byte[] constructor was used it returns byte[].class.
  46. * Else it returns null.
  47. * @return class which the Packet was created with.
  48. */
  49. public Class<? extends Object> getType() {
  50. if (isStringMsg) {
  51. return String.class;
  52. } else if (isByteMsg){
  53. return byte[].class;
  54. } else {
  55. return null;
  56. }
  57. }
  58. /**
  59. * Checks whether the Packet was created with the given class or not.
  60. * @param type to be checked.
  61. * @return true if the packet was created with the given class, else false.
  62. */
  63. public boolean isOfType(Class<? extends Object> type) {
  64. return getType().equals(type);
  65. }
  66. /**
  67. * If the Packet was created with a byte[] it returns the hexadecimal byte value as a String,
  68. * else it returns a new String created by the byte[].
  69. */
  70. @Override
  71. public String toString() {
  72. if (isStringMsg) {
  73. return new String((byte[]) message);
  74. } else if (isByteMsg) {
  75. return HelperUtils.bytesToHexString((byte[]) message);
  76. } else {
  77. return null;
  78. }
  79. }
  80. }