1 | package nl.powercraft.tagtracker;
|
---|
2 |
|
---|
3 | import java.io.ByteArrayInputStream;
|
---|
4 | import java.io.ByteArrayOutputStream;
|
---|
5 | import java.io.ObjectInputStream;
|
---|
6 | import java.io.ObjectOutputStream;
|
---|
7 | import java.io.Serializable;
|
---|
8 |
|
---|
9 | import android.util.Log;
|
---|
10 |
|
---|
11 | public class ObjectSerializer {
|
---|
12 |
|
---|
13 |
|
---|
14 | public static String serialize(Serializable obj) {
|
---|
15 | if (obj == null) return "";
|
---|
16 | try {
|
---|
17 | ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
|
---|
18 | ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
|
---|
19 | objStream.writeObject(obj);
|
---|
20 | objStream.close();
|
---|
21 | return encodeBytes(serialObj.toByteArray());
|
---|
22 | } catch (Exception e) {
|
---|
23 | Log.e("TagTracker","Serialization error: " + e.getMessage(), e);
|
---|
24 | }
|
---|
25 | return "";
|
---|
26 | }
|
---|
27 |
|
---|
28 | public static Object deserialize(String str) {
|
---|
29 | if (str == null || str.length() == 0) return null;
|
---|
30 | try {
|
---|
31 | ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
|
---|
32 | ObjectInputStream objStream = new ObjectInputStream(serialObj);
|
---|
33 | return objStream.readObject();
|
---|
34 | } catch (Exception e) {
|
---|
35 | Log.e("TagTracker","Deserialization error: " + e.getMessage(), e);
|
---|
36 | }
|
---|
37 | return null;
|
---|
38 | }
|
---|
39 |
|
---|
40 | public static String encodeBytes(byte[] bytes) {
|
---|
41 | StringBuffer strBuf = new StringBuffer();
|
---|
42 |
|
---|
43 | for (int i = 0; i < bytes.length; i++) {
|
---|
44 | strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
|
---|
45 | strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
|
---|
46 | }
|
---|
47 |
|
---|
48 | return strBuf.toString();
|
---|
49 | }
|
---|
50 |
|
---|
51 | public static byte[] decodeBytes(String str) {
|
---|
52 | byte[] bytes = new byte[str.length() / 2];
|
---|
53 | for (int i = 0; i < str.length(); i+=2) {
|
---|
54 | char c = str.charAt(i);
|
---|
55 | bytes[i/2] = (byte) ((c - 'a') << 4);
|
---|
56 | c = str.charAt(i+1);
|
---|
57 | bytes[i/2] += (c - 'a');
|
---|
58 | }
|
---|
59 | return bytes;
|
---|
60 | }
|
---|
61 |
|
---|
62 | }
|
---|