1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.commons.settings;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.ByteArrayOutputStream;
24 import java.io.IOException;
25 import java.io.ObjectInputStream;
26 import java.io.ObjectOutputStream;
27 import java.io.Serializable;
28
29 /***
30 *
31 */
32 public class SerializableSetting<T extends Serializable> extends AbstractSetting<T> {
33
34 public SerializableSetting(SettingResource backend, String key, T defaultValue, Validator validator)
35 {
36 super(backend, key, defaultValue, validator);
37 }
38
39 public SerializableSetting(SettingResource backend, String key, T defaultValue)
40 {
41 super(backend, key, defaultValue, null);
42 }
43
44 @SuppressWarnings("unchecked")
45 protected T fromString(String value)
46 {
47
48 ByteArrayInputStream buffer = new ByteArrayInputStream(toByteArray(value));
49
50 ObjectInputStream in;
51 try {
52 in = new ObjectInputStream(buffer);
53 return (T)in.readObject();
54 }
55 catch (IOException e) {
56 return null;
57 }
58 catch (ClassNotFoundException e) {
59 return null;
60 }
61 }
62
63 protected String toString(T value)
64 {
65 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
66 ObjectOutputStream out = null;
67 try {
68 out = new ObjectOutputStream(buffer);
69 out.writeObject(value);
70
71 return toString(buffer.toByteArray());
72 }
73 catch (IOException e) {
74 throw new IllegalArgumentException("Could not serialize value");
75 }
76 finally {
77 if (out != null) {
78 try {
79 out.close();
80 }
81 catch (IOException e1) {}
82 }
83 }
84 }
85
86 private String toString(byte[] array)
87 {
88 char[] chars = new char[array.length];
89 for (int i = 0; i < chars.length; i++) {
90 chars[i] = (char)array[i];
91 }
92 return new String(chars);
93 }
94
95 private byte[] toByteArray(String s)
96 {
97 char[] chars = s.toCharArray();
98 byte[] bytes = new byte[chars.length];
99 for (int i = 0; i < bytes.length; i++) {
100 bytes[i] = (byte)chars[i];
101 }
102 return bytes;
103 }
104
105 }