1 24 package org.ofbiz.base.util; 25 26 import java.io.ByteArrayInputStream ; 27 import java.io.ByteArrayOutputStream ; 28 import java.io.IOException ; 29 import java.io.ObjectOutputStream ; 30 31 38 public class UtilObject { 39 40 public static final String module = UtilObject.class.getName(); 41 42 43 public static byte[] getBytes(Object obj) { 44 ByteArrayOutputStream bos = null; 45 ObjectOutputStream oos = null; 46 byte[] data = null; 47 try { 48 bos = new ByteArrayOutputStream (); 49 oos = new ObjectOutputStream (bos); 50 oos.writeObject(obj); 51 data = bos.toByteArray(); 52 } catch (IOException e) { 53 Debug.logError(e, module); 54 } finally { 55 try { 56 if (oos != null) { 57 oos.flush(); 58 oos.close(); 59 } 60 if (bos != null) { 61 bos.close(); 62 } 63 } catch (IOException e) { 64 Debug.logError(e, module); 65 } 66 } 67 68 return data; 69 } 70 71 public static long getByteCount(Object obj) { 72 OutputStreamByteCount osbc = null; 73 ObjectOutputStream oos = null; 74 try { 75 osbc = new OutputStreamByteCount(); 76 oos = new ObjectOutputStream (osbc); 77 oos.writeObject(obj); 78 } catch (IOException e) { 79 Debug.logError(e, module); 80 } finally { 81 try { 82 if (oos != null) { 83 oos.flush(); 84 oos.close(); 85 } 86 if (osbc != null) { 87 osbc.close(); 88 } 89 } catch (IOException e) { 90 Debug.logError(e, module); 91 } 92 } 93 if (osbc != null) { 94 return osbc.getByteCount(); 95 } else { 96 return 0; 97 } 98 } 99 100 101 public static Object getObject(byte[] bytes) { 102 ByteArrayInputStream bis = null; 103 ObjectInputStream ois = null; 104 Object obj = null; 105 106 try { 107 bis = new ByteArrayInputStream (bytes); 108 ois = new ObjectInputStream(bis, Thread.currentThread().getContextClassLoader()); 109 obj = ois.readObject(); 110 } catch (ClassNotFoundException e) { 111 Debug.logError(e, module); 112 } catch (IOException e) { 113 Debug.logError(e, module); 114 } finally { 115 try { 116 if (ois != null) { 117 ois.close(); 118 } 119 if (bis != null) { 120 bis.close(); 121 } 122 } catch (IOException e) { 123 Debug.logError(e, module); 124 } 125 } 126 127 return obj; 128 } 129 130 public static boolean equalsHelper(Object o1, Object o2) { 131 if (o1 == o2) { 132 return true; 134 } else if (o1 == null || o2 == null) { 135 return false; 137 } else { 138 return o1.equals(o2); 139 } 140 } 141 142 public static int compareToHelper(Comparable o1, Object o2) { 143 if (o1 == o2) { 144 return 0; 146 } else if (o1 == null) { 147 return -1; 148 } else if (o2 == null) { 149 return 1; 151 } else { 152 return o1.compareTo(o2); 153 } 154 } 155 156 public static int doHashCode(Object o1) { 157 if (o1 == null) return 0; 158 return o1.hashCode(); 159 } 160 } 161 | Popular Tags |