]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.indexing/src/org/simantics/db/indexing/IndexedRelationsSearcher.java
ToggleFocusabilityHandler now updates UI state on active part change
[simantics/platform.git] / bundles / org.simantics.db.indexing / src / org / simantics / db / indexing / IndexedRelationsSearcher.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.db.indexing;
13
14 import java.io.IOException;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20
21 import org.apache.lucene.index.CorruptIndexException;
22 import org.apache.lucene.queryparser.classic.ParseException;
23 import org.eclipse.core.runtime.IProgressMonitor;
24 import org.simantics.db.RequestProcessor;
25 import org.simantics.db.Resource;
26 import org.simantics.db.Session;
27 import org.simantics.db.exception.DatabaseException;
28 import org.simantics.db.layer0.adapter.GenericRelation;
29 import org.simantics.utils.datastructures.Pair;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /**
34  * @author Tuukka Lehtonen
35  * @author Antti Villberg
36  */
37 public class IndexedRelationsSearcher extends IndexedRelationsSearcherBase {
38
39     private static final Logger LOGGER = LoggerFactory.getLogger(IndexedRelationsSearcher.class);
40
41     IndexedRelationsMemorySearcher cache;
42
43     IndexedRelationsSearcher(RequestProcessor session, Resource relation, Resource input, GenericRelation r) throws DatabaseException {
44         super(session, relation, input);
45         this.cache = new IndexedRelationsMemorySearcher(session, this, relation, input, r);
46     }
47
48     @Override
49     String getDescriptor() {
50         return "DISK: ";
51     }
52
53     @Override
54     public void setProblem(Throwable t) {
55         super.setProblem(t);
56         cache.setProblem(t);
57     }
58     
59     @Override
60     boolean startAccess(IProgressMonitor monitor, Session session, boolean forWriting) {
61         boolean success = super.startAccess(monitor, session, false);
62         if(!success) return false;
63         success = cache.startAccess(monitor, session, forWriting);
64         if(!success) {
65                 setProblem(cache.getException());
66                 return false;
67         } else return true;
68     }
69     
70     @Override
71     void insertIndex(IProgressMonitor monitor, GenericRelation r, int boundLength, Collection<Object[]> documentsData)
72             throws CorruptIndexException, IOException, DatabaseException {
73
74         Collection<Object> keyValues = new ArrayList<Object>();
75         for(Object[] data : documentsData) {
76             keyValues.add(data[1]);
77         }
78         
79         cache.replaceIndex(monitor, "Resource", keyValues, r, boundLength, documentsData);
80         //cache.commit();
81         
82     }
83     
84     @Override
85     void removeIndex(IProgressMonitor monitor, GenericRelation r, RequestProcessor processor, String key, Collection<Object> keyValues) throws DatabaseException,CorruptIndexException, IOException {
86         
87         Collection<Object[]> documentsData = new ArrayList<Object[]>();
88
89         Pair<String,String>[] fields = r.getFields(); 
90
91         for(Object keyValue : keyValues) {
92             Object[] data = new Object[fields.length-1];
93             int index = 0;
94             for(int i=1;i<fields.length;i++) {
95                 String fieldName = fields[i].first;
96                 if(key.equals(fieldName)) {
97                     data[index++] = keyValue;
98                 } else {
99                     String fieldClass = fields[i].second;
100                     if ("Long".equals(fieldClass)) {
101                         data[index++] = 0L;
102                     } else if ("String".equals(fieldClass) || "Text".equals(fieldClass)) {
103                         data[index++] = "";
104                     } else {
105                         throw new DatabaseException("Can only index Long and String fields, encountered class " + fieldClass);
106                     }
107                 }
108             }
109             documentsData.add(data);
110         }
111
112         cache.replaceIndex(monitor, key, keyValues, r, 1, documentsData);
113 //        cache.commit();
114         
115     }
116     
117     @Override
118     boolean replaceIndex(IProgressMonitor monitor, String key, Collection<Object> keyValues, GenericRelation r,
119             int boundLength, Collection<Object[]> documentsData) throws CorruptIndexException, IOException,
120             DatabaseException {
121
122         boolean result = cache.replaceIndex(monitor, key, keyValues, r, boundLength, documentsData);
123 //        cache.commit();
124         return result; 
125         
126     }
127     
128     List<Map<String, Object>> persistentCachedSearch(IProgressMonitor monitor, RequestProcessor processor, String search,
129             int maxResultCount) throws ParseException, IOException, DatabaseException {
130         
131         MemoryIndexing mem = MemoryIndexing.getInstance(session.getSession());
132         
133         String key = indexPath.toAbsolutePath().toString();
134         
135         Map<String,List<Map<String, Object>>> cache = mem.persistentCache.get(key);
136         if(cache != null) {
137             List<Map<String,Object>> result = cache.get(search);
138             if(result != null) return result;
139         }
140
141         startAccess(monitor, processor.getSession(), false);
142
143         List<Map<String, Object>> results = super.doSearch(monitor, processor, search, maxResultCount);
144         if(cache == null) {
145             cache = new HashMap<String,List<Map<String,Object>>>();
146             mem.persistentCache.put(key, cache);
147         }
148
149         if(results.size() < 500)
150             cache.put(search, results);
151         
152         return results;
153         
154     }
155
156     List<Resource> persistentCachedSearchResources(IProgressMonitor monitor, RequestProcessor processor, String search,
157             int maxResultCount) throws ParseException, IOException, DatabaseException {
158         
159         MemoryIndexing mem = MemoryIndexing.getInstance(session.getSession());
160         
161         String key = indexPath.toAbsolutePath().toString();
162         
163         Map<String,List<Resource>> cache = mem.persistentCacheResources.get(key);
164         if(cache != null) {
165             List<Resource> result = cache.get(search);
166             if(result != null) return result;
167         }
168
169         startAccess(monitor, processor.getSession(), false);
170
171         List<Resource> results = super.doSearchResources(monitor, processor, search, maxResultCount);
172         if(cache == null) {
173             cache = new HashMap<String,List<Resource>>();
174             mem.persistentCacheResources.put(key, cache);
175         }
176
177         if(results.size() < 500)
178             cache.put(search, results);
179         
180         return results;
181         
182     }
183     
184     List<Object> persistentCachedList(IProgressMonitor monitor, RequestProcessor processor) throws ParseException, IOException, DatabaseException {
185         
186         startAccess(monitor, processor.getSession(), false);
187
188         List<Object> results = super.doList(monitor, processor);
189         
190         return results;
191         
192     }
193     
194     @Override
195     List<Map<String, Object>> doSearch(IProgressMonitor monitor, RequestProcessor processor, String search,
196             int maxResultCount) throws ParseException, IOException, DatabaseException {
197         
198         List<Map<String,Object>> persistent = persistentCachedSearch(monitor, processor, search, maxResultCount);
199         List<Map<String,Object>> cached = cache.doSearch(monitor, processor, search, maxResultCount);
200
201         ArrayList<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
202
203         for(Map<String,Object> m : persistent) {
204             Resource r = (Resource)m.get("Resource");
205             if(!cache.changed.contains(r.getResourceId())) {
206                 result.add(m);
207             }
208         }
209         result.addAll(cached);
210         return result;
211         
212     }
213     
214     @Override
215     List<Resource> doSearchResources(IProgressMonitor monitor, RequestProcessor processor, String search,
216                 int maxResultCount) throws ParseException, IOException, DatabaseException {
217
218         List<Resource> persistent = persistentCachedSearchResources(monitor, processor, search, maxResultCount);
219         List<Resource> cached = cache.doSearchResources(monitor, processor, search, maxResultCount);
220
221         ArrayList<Resource> result = new ArrayList<Resource>();
222         for(Resource r : persistent) {
223             if(!cache.changed.contains(r.getResourceId())) {
224                 result.add(r);
225             }
226         }
227         result.addAll(cached);
228         return result;
229         
230     }
231     
232     List<Object> doList(IProgressMonitor monitor, RequestProcessor processor) throws ParseException, IOException, DatabaseException {
233
234         List<Object> persistent = persistentCachedList(monitor, processor);
235         
236         // TODO: check that caches have been properly flushed
237         //List<Object> cached = cache.doList(monitor, processor);
238         //if(!cached.isEmpty()) throw new DatabaseException("doList does not support caching");
239
240         return persistent;
241         
242     }
243
244     void applyChanges(IProgressMonitor monitor, Session session, GenericRelation r, Collection<Object[]> os) throws Exception {
245         
246         if(!os.isEmpty()) {
247         
248                 ArrayList<Object> replaceKeys = new ArrayList<Object>();
249                 ArrayList<Object[]> replaceValues = new ArrayList<Object[]>();
250                 ArrayList<Object> removeKeys = new ArrayList<Object>();
251                 for(Object[] o : os) {
252                     Long parent = (Long)o[0];
253                     Long key = (Long)o[1];
254                     if(parent != 0) {
255                         replaceKeys.add(key);
256                         replaceValues.add(o);
257                     } else {
258                         removeKeys.add(key);
259                     }
260                 }
261                 
262                 changeState(monitor, session, State.READY);
263                 
264                 super.startAccess(null, session, true);
265                 
266                 super.replaceIndex(null, "Resource", replaceKeys, r, 1, replaceValues);
267                 super.removeIndex(null, r, null, "Resource", removeKeys);
268                 
269         }
270         
271         changeState(monitor, session, State.READY);
272         
273     }
274     
275     @Override
276     Throwable bestEffortClear(IProgressMonitor monitor, Session session) {
277
278         // Free the index
279         changeState(monitor, session, State.NONE);
280         
281         Throwable t = clearDirectory(monitor, session);
282         if(t != null) return t;
283
284         t = cache.bestEffortClear(monitor, session);
285         if(t != null) return t;
286         
287         String key = indexPath.toAbsolutePath().toString();
288         MemoryIndexing mem = MemoryIndexing.getInstance(session);
289         mem.persistentCache.remove(key);
290         mem.persistentCacheResources.remove(key);
291         
292         return null;
293         
294     }
295
296     @Override
297     protected Logger getLogger() {
298         return LOGGER;
299     }
300     
301 }