1 | package de.uka.ipd.sdq.sensorframework.dao.file.entities; |
2 | |
3 | import java.util.HashMap; |
4 | |
5 | import de.uka.ipd.sdq.sensorframework.entities.State; |
6 | import de.uka.ipd.sdq.sensorframework.entities.StateSensor; |
7 | import de.uka.ipd.sdq.sensorframework.storage.lists.ISerialiser; |
8 | |
9 | /** |
10 | * @author Henning Groenda |
11 | * @author Steffen Becker |
12 | */ |
13 | public class StateSerializer |
14 | implements ISerialiser<State> { |
15 | |
16 | HashMap<Long, State> hashMap = new HashMap<Long, State>(); |
17 | |
18 | StateSensor mySensor = null; |
19 | |
20 | public StateSerializer(StateSensor stateSensor){ |
21 | this.mySensor = stateSensor; |
22 | initSensorStateHash(); |
23 | } |
24 | |
25 | private void initSensorStateHash() { |
26 | hashMap.clear(); |
27 | for (State s : mySensor.getSensorStates()) { |
28 | hashMap.put(s.getStateID(),s); |
29 | } |
30 | } |
31 | |
32 | public State[] deserialise(byte[] bytes) { |
33 | initSensorStateHash(); |
34 | |
35 | State[] states = new State[(int)(bytes.length / getElementLength())]; |
36 | int blockPos = 0; |
37 | for (int j = 0; j<states.length; j++){ |
38 | long l = 0; |
39 | for (int i = 7; i >=0; i--) { |
40 | l = l << 8; |
41 | l |= bytes[blockPos+i] < 0 ? 256 + bytes[blockPos+i] : bytes[blockPos+i]; |
42 | } |
43 | blockPos += 8; |
44 | states[j] = hashMap.get(l); |
45 | if (states[j] == null) |
46 | throw new RuntimeException("State could not be deserialized " + |
47 | "as it returned null values for state "+j+"."); |
48 | } |
49 | return states; |
50 | } |
51 | |
52 | public long getElementLength() { |
53 | return 8; |
54 | } |
55 | |
56 | public byte[] serialise(Object[] objects, int count) { |
57 | byte[] block = new byte[(int)(count*getElementLength())]; |
58 | int blockPos = 0; |
59 | for (int j = 0; j < count; j++){ |
60 | long l = ((State)objects[j]).getStateID(); |
61 | for (int i = 0; i < 8; i++) { |
62 | block[blockPos++] = (byte)(l & 0xff); |
63 | l = l >> 8; |
64 | } |
65 | } |
66 | return block; |
67 | } |
68 | |
69 | } |