1 package org.simantics.db.impl.query;
3 import java.util.HashMap;
5 import java.util.Map.Entry;
7 import org.simantics.db.impl.ClusterTraitsBase;
9 import gnu.trove.list.array.TByteArrayList;
10 import gnu.trove.map.hash.TLongIntHashMap;
11 import gnu.trove.procedure.TLongIntProcedure;
13 public class QuerySerializer {
15 private QueryProcessor processor;
16 private QuerySupport querySupport;
17 private TByteArrayList bytes = new TByteArrayList();
18 private TLongIntHashMap clusterKeys = new TLongIntHashMap();
19 private Map<String,Integer> ids = new HashMap<String,Integer>();
21 public QuerySerializer(QueryProcessor processor) {
22 this.processor = processor;
23 this.querySupport = processor.querySupport;
26 public int writeUnknownSize() {
27 int pos = bytes.size();
35 public void setUnknownSize(int pos, int value) {
36 bytes.set(pos, (byte) (value & 0xFF));
37 bytes.set(pos+1, (byte) ((value >>> 8) & 0xFF));
38 bytes.set(pos+2, (byte) ((value >>> 16) & 0xFF));
39 bytes.set(pos+3, (byte) ((value >>> 24) & 0xFF));
42 public void serializeId(String classId) {
43 Integer id = ids.get(classId);
51 public void addResource(int r) {
55 long clusterId = querySupport.getClusterId(r);
56 int clusterKey = clusterKeys.get(clusterId);
58 clusterKey = clusterKeys.size() + 1;
59 clusterKeys.put(clusterId, clusterKey);
61 int i = ClusterTraitsBase.createResourceKeyNoThrow(clusterKey, ClusterTraitsBase.getResourceIndexFromResourceKeyNoThrow(r));
66 public void addString(String s) {
67 byte[] b = s.getBytes();
72 public void add(byte b) {
76 public void add(byte[] bs) {
80 public byte[] bytes() {
81 TByteArrayList header = new TByteArrayList();
82 writeLE(header, ids.size());
83 for(Entry<String,Integer> entry : ids.entrySet()) {
84 String id = entry.getKey();
85 writeLE(header, id.length());
86 header.add(id.getBytes());
87 writeLE(header, entry.getValue());
90 writeLE(header, clusterKeys.size());
91 clusterKeys.forEachEntry(new TLongIntProcedure() {
94 public boolean execute(long a, int b) {
102 header.add(bytes.toArray());
103 return header.toArray();
106 public void writeLE(int value) {
107 writeLE(bytes, value);
110 public static void writeLE(TByteArrayList bytes, int value) {
111 bytes.add((byte) (value & 0xFF));
112 bytes.add((byte) ((value >>> 8) & 0xFF));
113 bytes.add((byte) ((value >>> 16) & 0xFF));
114 bytes.add((byte) ((value >>> 24) & 0xFF));
117 public void writeLE(long value) {
118 writeLE(bytes, value);
121 public static void writeLE(TByteArrayList bytes, long value) {
122 bytes.add((byte) (value & 0xFF));
123 bytes.add((byte) ((value >>> 8) & 0xFF));
124 bytes.add((byte) ((value >>> 16) & 0xFF));
125 bytes.add((byte) ((value >>> 24) & 0xFF));
126 bytes.add((byte) ((value >>> 32) & 0xFF));
127 bytes.add((byte) ((value >>> 40) & 0xFF));
128 bytes.add((byte) ((value >>> 48) & 0xFF));
129 bytes.add((byte) ((value >>> 56) & 0xFF));
132 public QueryProcessor getQueryProcessor() {