OSDN Git Service

uni-gramで日本語全文検索できるように変更。ノートコンテンツとタイトルが対象。日本語全文検索時に日本語がハイライトされない問題を修正。
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / sql / REnSearch.java
1 /*\r
2  * This file is part of NixNote/NeighborNote \r
3  * Copyright 2009 Randy Baumgarte\r
4  * \r
5  * This file may be licensed under the terms of of the\r
6  * GNU General Public License Version 2 (the ``GPL'').\r
7  *\r
8  * Software distributed under the License is distributed\r
9  * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either\r
10  * express or implied. See the GPL for the specific language\r
11  * governing rights and limitations.\r
12  *\r
13  * You should have received a copy of the GPL along with this\r
14  * program. If not, go to http://www.gnu.org/licenses/gpl.html\r
15  * or write to the Free Software Foundation, Inc.,\r
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r
17  *\r
18 */\r
19 \r
20 \r
21 package cx.fbn.nevernote.sql;\r
22 \r
23 import java.text.SimpleDateFormat;\r
24 import java.util.ArrayList;\r
25 import java.util.Calendar;\r
26 import java.util.GregorianCalendar;\r
27 import java.util.List;\r
28 import java.util.regex.Pattern;\r
29 \r
30 import org.apache.commons.lang3.StringEscapeUtils;\r
31 \r
32 import com.evernote.edam.type.Note;\r
33 import com.evernote.edam.type.Notebook;\r
34 import com.evernote.edam.type.Tag;\r
35 \r
36 import cx.fbn.nevernote.Global;\r
37 import cx.fbn.nevernote.sql.driver.NSqlQuery;\r
38 import cx.fbn.nevernote.utilities.ApplicationLogger;\r
39 \r
40 public class REnSearch {\r
41         \r
42         private final List<String>      searchWords;\r
43         private final List<String>  searchPhrases;\r
44         private final List<String>      notebooks;\r
45         private final List<String>      tags;\r
46         private final List<String>      intitle;\r
47         private final List<String>      created;\r
48         private final List<String>      updated;\r
49         private final List<String>      resource;\r
50         private final List<String>      subjectDate;\r
51         private final List<String>      longitude;\r
52         private final List<String>      latitude;\r
53         private final List<String>      altitude;\r
54         private final List<String>      author;\r
55         private final List<String>      source;\r
56         private final List<String>      sourceApplication;\r
57         private final List<String>      recoType;\r
58         private final List<String>      todo;\r
59         private final List<String>  stack;\r
60         private final List<Tag>         tagIndex;\r
61         private final ApplicationLogger logger;\r
62 //      private final DatabaseConnection db;\r
63         private boolean any;\r
64         private int minimumRecognitionWeight = 80;\r
65         private final DatabaseConnection conn;\r
66         \r
67         public REnSearch(DatabaseConnection c, ApplicationLogger l, String s, List<Tag> t, int r) {\r
68                 logger = l;\r
69                 conn = c;\r
70                 tagIndex = t;\r
71                 minimumRecognitionWeight = r;\r
72                 searchWords = new ArrayList<String>();\r
73                 searchPhrases = new ArrayList<String>();\r
74                 notebooks = new ArrayList<String>();\r
75                 tags = new ArrayList<String>();\r
76                 intitle = new ArrayList<String>();\r
77                 created = new  ArrayList<String>();\r
78                 updated = new ArrayList<String>();\r
79                 resource = new ArrayList<String>();\r
80                 subjectDate = new ArrayList<String>();\r
81                 longitude = new ArrayList<String>();\r
82                 latitude = new ArrayList<String>();\r
83                 altitude = new ArrayList<String>();\r
84                 author = new ArrayList<String>();\r
85                 source = new ArrayList<String>();\r
86                 sourceApplication = new ArrayList<String>();\r
87                 recoType = new ArrayList<String>();\r
88                 todo = new ArrayList<String>();\r
89                 any = false;\r
90                 stack = new ArrayList<String>();\r
91                 \r
92                 if (s == null) \r
93                         return;\r
94                 if (s.trim().equals(""))\r
95                         return;\r
96                 \r
97                 resolveSearch(s);\r
98         }\r
99                 \r
100         public List<String> getWords() { return searchWords; }\r
101         public List<String> getNotebooks() { return notebooks; }\r
102         public List<String> getIntitle() {      return intitle; }\r
103         public List<String> getTags() { return tags; }\r
104         public List<String> getResource() {     return resource; }\r
105         public List<String> getAuthor() { return author; }      \r
106         public List<String> getSource() { return source; }      \r
107         public List<String> getSourceApplication() { return sourceApplication; }        \r
108         public List<String> getRecoType() {     return recoType; }      \r
109         public List<String> getToDo() { return todo; }\r
110         public List<String> getLongitude() { return longitude; }\r
111         public List<String> getLatitude() { return latitude; }\r
112         public List<String> getAltitude() { return altitude; }\r
113         public List<String> getCreated() { return created; }\r
114         public List<String> getUpdated() { return updated; }\r
115         public List<String> getSubjectDate() { return subjectDate; }\r
116         public List<String> getStack() { return stack; }\r
117 \r
118         // match tag names\r
119         private boolean matchTagsAll(List<String> tagNames, List<String> list) {\r
120                                 \r
121                 for (int j=0; j<list.size(); j++) {\r
122                         boolean negative = false;\r
123                         negative = false;\r
124                         if (list.get(j).startsWith("-"))\r
125                                 negative = true;\r
126                         int pos = list.get(j).indexOf(":");\r
127                         String filterName = cleanupWord(list.get(j).substring(pos+1));\r
128                         filterName = filterName.replace("*", ".*");   // setup for regular expression pattern match\r
129                         \r
130                         if (tagNames.size() == 0 && !negative)\r
131                                 return false;\r
132                         \r
133                         boolean matchFound = false;\r
134                         for (int i=0; i<tagNames.size(); i++) { \r
135                                 boolean matches = Pattern.matches(filterName.toLowerCase(),tagNames.get(i).toLowerCase());\r
136                                 if (matches)\r
137                                         matchFound = true;\r
138                         }\r
139                         if (negative) \r
140                                 matchFound = !matchFound;\r
141                         if (!matchFound) \r
142                                 return false;\r
143                 }\r
144                 return true;\r
145         }\r
146         \r
147         // match tag names\r
148         private boolean matchTagsAny(List<String> tagNames, List<String> list) {\r
149                 if (list.size() == 0)\r
150                         return true;\r
151                 \r
152                 boolean negative = false;               \r
153 \r
154                 for (int j=0; j<list.size(); j++) {\r
155                         negative = false;\r
156                         if (list.get(j).startsWith("-"))\r
157                                 negative = true;\r
158                         int pos = list.get(j).indexOf(":");\r
159                         String filterName = cleanupWord(list.get(j).substring(pos+1));\r
160                         filterName = filterName.replace("*", ".*");   // setup for regular expression pattern match\r
161                         \r
162                         if (tagNames.size() == 0 && !negative)\r
163                                 return false;\r
164 \r
165                         for (int i=0; i<tagNames.size(); i++) {         \r
166                                 boolean matches = Pattern.matches(filterName.toLowerCase(),tagNames.get(i).toLowerCase());\r
167                                 if (!matches && !negative)\r
168                                         return false;\r
169                         }\r
170                 }\r
171                 return true;\r
172         }\r
173         \r
174         \r
175         // Match notebooks in search terms against notes\r
176         private boolean matchNotebook(String guid) {\r
177                 if (getNotebooks().size() == 0)\r
178                         return true;\r
179                 NotebookTable bookTable = new NotebookTable(logger, conn);\r
180                 List<Notebook> books = bookTable.getAll();\r
181 \r
182                 String name = new String("");\r
183                 for (int i=0; i<books.size(); i++) {\r
184                         if (guid.equalsIgnoreCase(books.get(i).getGuid())) {\r
185                                 name = books.get(i).getName();\r
186                                 i=books.size();\r
187                         }\r
188                 }\r
189                 if (any)\r
190                         return matchListAny(getNotebooks(), name);\r
191                 else\r
192                         return matchListAll(getNotebooks(), name);\r
193         }\r
194         // Match notebooks in search terms against notes\r
195         private boolean matchNotebookStack(String guid) {\r
196                 if (getStack().size() == 0)\r
197                         return true;\r
198                 NotebookTable bookTable = new NotebookTable(logger, conn);\r
199                 List<Notebook> books = bookTable.getAll();\r
200 \r
201                 String name = new String("");\r
202                 for (int i=0; i<books.size(); i++) {\r
203                         if (guid.equalsIgnoreCase(books.get(i).getGuid())) {\r
204                                 name = books.get(i).getStack();\r
205                                 i=books.size();\r
206                         }\r
207                 }\r
208                 if (name == null)\r
209                         name = "";\r
210                 if (any)\r
211                         return matchListAny(getStack(), name);\r
212                 else\r
213                         return matchListAll(getStack(), name);\r
214         }\r
215 \r
216         // Match notebooks in search terms against notes\r
217         private boolean matchListAny(List<String> list, String title) {\r
218                 if (list.size() == 0)\r
219                         return true;\r
220                 boolean negative = false;\r
221                 boolean found = false;\r
222                 for (int i=0; i<list.size(); i++) {\r
223                         int pos = list.get(i).indexOf(":");\r
224                         negative = false;\r
225                         if (list.get(i).startsWith("-"))\r
226                                 negative = true;\r
227                         String filterName = cleanupWord(list.get(i).substring(pos+1));\r
228                         filterName = filterName.replace("*", ".*");   // setup for regular expression pattern match\r
229                         boolean matches = Pattern.matches(filterName.toLowerCase(),title.toLowerCase());\r
230                         if (matches)\r
231                                 found = true;\r
232                 }\r
233                 if (negative)\r
234                         return !found;\r
235                 else\r
236                         return found;\r
237         }\r
238         // Match notebooks in search terms against notes\r
239         private boolean matchContentAny(Note n) {\r
240                 if (todo.size() == 0 && resource.size() == 0 && searchPhrases.size() == 0)\r
241                         return true;\r
242 \r
243                 // pull back the record\r
244                 n = conn.getNoteTable().getNote(n.getGuid(), true, true, false, false, false);\r
245 \r
246                 // Check for search phrases\r
247                 String text = StringEscapeUtils.unescapeHtml4(n.getContent().replaceAll("\\<.*?\\>", "")).toLowerCase();\r
248                 boolean negative = false;\r
249                 for (int i=0; i<searchPhrases.size(); i++) {\r
250                         String phrase = searchPhrases.get(i);\r
251                         if (phrase.startsWith("-")) {\r
252                                 negative = true;\r
253                                 phrase = phrase.substring(1);\r
254                         } else\r
255                                 negative = false;\r
256                         phrase = phrase.substring(1);\r
257                         phrase = phrase.substring(0,phrase.length()-1);\r
258                         if (text.indexOf(phrase)>=0) {\r
259                                 if (negative)\r
260                                         return false;\r
261                                 else\r
262                                         return true;\r
263                         }\r
264                         if (text.indexOf(phrase)<0 && negative)\r
265                                 return true;\r
266                 }\r
267                 \r
268                 for (int i=0; i<todo.size(); i++) {\r
269                         String value = todo.get(i);\r
270                         value = value.replace("\"", "");\r
271                         boolean desiredState;\r
272                         if (!value.endsWith(":false") && !value.endsWith(":true") && !value.endsWith(":*") && !value.endsWith("*"))\r
273                                 return false;\r
274                         if (value.endsWith(":false"))\r
275                                 desiredState = false;\r
276                         else\r
277                                 desiredState = true;\r
278                         if (value.startsWith("-"))\r
279                                 desiredState = !desiredState;\r
280                         int pos = n.getContent().indexOf("<en-todo");\r
281                         if (pos == -1 && value.startsWith("-") && (value.endsWith("*") || value.endsWith(":")))\r
282                                 return true;\r
283                         if (value.endsWith("*"))\r
284                                 return true;\r
285                         while (pos > -1) {\r
286                                 int endPos = n.getContent().indexOf("/>", pos);\r
287                                 String segment = n.getContent().substring(pos, endPos);\r
288                                 boolean currentState;\r
289                                 if (segment.toLowerCase().indexOf("checked=\"true\"") == -1)\r
290                                         currentState = false;\r
291                                 else\r
292                                         currentState = true;\r
293                                 if (desiredState == currentState)\r
294                                         return true;\r
295                                 \r
296                                 pos = n.getContent().indexOf("<en-todo", pos+1);\r
297                         }\r
298                 }\r
299                 \r
300                 // Check resources\r
301                 for (int i=0; i<resource.size(); i++) {\r
302                         String resourceString = resource.get(i);\r
303                         resourceString = resourceString.replace("\"", "");\r
304                         if (resourceString.startsWith("-"))\r
305                                 negative = true;\r
306                         resourceString = resourceString.substring(resourceString.indexOf(":")+1);\r
307                         for (int j=0; j<n.getResourcesSize(); j++) {\r
308                                 boolean match = stringMatch(n.getResources().get(j).getMime(), resourceString, negative);\r
309                                 if (match)\r
310                                         return true;\r
311                         }\r
312                 }\r
313                 return false;\r
314         }\r
315         \r
316         \r
317         // Take the initial search & split it apart\r
318         private void resolveSearch(String search) {\r
319                 List<String> words = new ArrayList<String>();\r
320                 StringBuffer b = new StringBuffer(search);\r
321                 \r
322                 int len = search.length();\r
323                 char nextChar = ' ';\r
324                 boolean quote = false;\r
325                 for (int i=0, j=0; i<len; i++, j++) {\r
326                         if (search.charAt(i)==nextChar && !quote) {\r
327                                 b.setCharAt(j,'\0');\r
328                                 nextChar = ' ';\r
329                         } else {\r
330                                 if (search.charAt(i)=='\"') {\r
331                                         if (!quote) {\r
332                                                 quote=true;\r
333                                         } else {\r
334                                                 quote=false;\r
335                                                 j++;\r
336                                                 b.insert(j, "\0");\r
337                                         }\r
338                                 }\r
339                         }\r
340                         if (((i+2)<len) && search.charAt(i) == '\\') {\r
341                                 i=i+2;\r
342                         }\r
343                 }\r
344                 \r
345                 search = b.toString();\r
346                 int pos = 0;\r
347                 for (int i=0; i<search.length(); i++) {\r
348                         if (search.charAt(i) == '\0') {\r
349                                 search = search.substring(1);\r
350                                 i=0;\r
351                         } else {\r
352                                 pos = search.indexOf('\0');\r
353                                 if (pos > 0) {\r
354                                         words.add(search.substring(0,pos).toLowerCase());\r
355                                         search = search.substring(pos);\r
356                                         i=0;\r
357                                 }\r
358                         }\r
359                 }\r
360                 if (search.charAt(0)=='\0')     \r
361                         words.add(search.substring(1).toLowerCase());\r
362                 else\r
363                         words.add(search.toLowerCase());\r
364                 parseTerms(words);\r
365         }\r
366 \r
367         \r
368         // Parse out individual words into separate lists\r
369         // Supported options\r
370         // Tags\r
371         // Notebooks\r
372         // Intitle\r
373         // author\r
374         // source\r
375         // source application\r
376         // created\r
377         // updated\r
378         // subject date\r
379 \r
380         private void parseTerms(List<String> words) {\r
381                 for (int i=0; i<words.size(); i++) {\r
382                         String word = words.get(i);\r
383                         System.out.println("word = " + word);\r
384                         int pos = word.indexOf(":");\r
385                         if (word.startsWith("any:")) {\r
386                                 any = true;\r
387                                 word = word.substring(4).trim();\r
388                                 pos = word.indexOf(":");\r
389                         }\r
390                         boolean searchPhrase = false;\r
391                         if (pos < 0 && word.indexOf(" ") > 0) {\r
392                                 searchPhrase=true;\r
393                                 searchPhrases.add(word.toLowerCase());\r
394                         }\r
395                         if (!searchPhrase && pos < 0) {\r
396                                 if (word != null && word.length() > 0 && !Global.automaticWildcardSearches())\r
397                                         getWords().add(word); \r
398                                 if (word != null && word.length() > 0 && Global.automaticWildcardSearches()) {\r
399                                         String wildcardWord = word;\r
400                                         if (!wildcardWord.startsWith("*"))\r
401                                                 wildcardWord = "*"+wildcardWord;\r
402                                         if (!wildcardWord.endsWith("*"))\r
403                                                 wildcardWord = wildcardWord+"*";\r
404                                         getWords().add(wildcardWord); \r
405                                 }\r
406 //                              getWords().add("*"+word+"*");           //// WILDCARD\r
407                         }\r
408                         if (word.startsWith("intitle:")) \r
409                                 intitle.add("*"+word+"*");\r
410                         if (word.startsWith("-intitle:")) \r
411                                 intitle.add("*"+word+"*");\r
412                         if (word.startsWith("notebook:")) \r
413                                 notebooks.add(word);\r
414                         if (word.startsWith("-notebook:")) \r
415                                 notebooks.add(word);\r
416                         if (word.startsWith("tag:")) \r
417                                 tags.add(word);\r
418                         if (word.startsWith("-tag:")) \r
419                                 tags.add(word);\r
420                         if (word.startsWith("resource:")) \r
421                                 resource.add(word);\r
422                         if (word.startsWith("-resource:")) \r
423                                 resource.add(word);\r
424                         if (word.startsWith("author:")) \r
425                                 author.add(word);\r
426                         if (word.startsWith("-author:")) \r
427                                 author.add(word);\r
428                         if (word.startsWith("source:")) \r
429                                 source.add(word);\r
430                         if (word.startsWith("-source:")) \r
431                                 source.add(word);\r
432                         if (word.startsWith("sourceapplication:")) \r
433                                 sourceApplication.add(word);\r
434                         if (word.startsWith("-sourceapplication:")) \r
435                                 sourceApplication.add(word);\r
436                         if (word.startsWith("recotype:")) \r
437                                 recoType.add(word);\r
438                         if (word.startsWith("-recotype:")) \r
439                                 recoType.add(word);\r
440                         if (word.startsWith("todo:")) \r
441                                 todo.add(word);\r
442                         if (word.startsWith("-todo:")) \r
443                                 todo.add(word);\r
444                         if (word.startsWith("stack:"))\r
445                                 stack.add(word);\r
446                         if (word.startsWith("-stack:"))\r
447                                 stack.add(word);\r
448 \r
449                         if (word.startsWith("latitude:")) \r
450                                 latitude.add(word);\r
451                         if (word.startsWith("-latitude:")) \r
452                                 latitude.add(word);\r
453                         if (word.startsWith("longitude:")) \r
454                                 longitude.add(word);\r
455                         if (word.startsWith("-longitude:")) \r
456                                 longitude.add(word);\r
457                         if (word.startsWith("altitude:")) \r
458                                 altitude.add(word);\r
459                         if (word.startsWith("-altitude:")) \r
460                                 altitude.add(word);\r
461 \r
462                         if (word.startsWith("created:")) \r
463                                 created.add(word);\r
464                         if (word.startsWith("-created:")) \r
465                                 created.add(word);\r
466                         if (word.startsWith("updated:")) \r
467                                 updated.add(word);\r
468                         if (word.startsWith("-updated:")) \r
469                                 updated.add(word);\r
470                         if (word.startsWith("subjectdate:")) \r
471                                 created.add(word);\r
472                         if (word.startsWith("-subjectdate:")) \r
473                                 created.add(word);\r
474 \r
475                 }\r
476         }\r
477         // Match notebooks in search terms against notes\r
478         private boolean matchListAll(List<String> list, String title) {\r
479                 if (list.size() == 0)\r
480                         return true;\r
481                 boolean negative = false;\r
482                 for (int i=0; i<list.size(); i++) {\r
483                         int pos = list.get(i).indexOf(":");\r
484                         negative = false;\r
485                         if (list.get(i).startsWith("-"))\r
486                                 negative = true;\r
487                         String filterName = cleanupWord(list.get(i).substring(pos+1));\r
488                         filterName = filterName.replace("*", ".*");   // setup for regular expression pattern match\r
489                         boolean matches = Pattern.matches(filterName.toLowerCase(),title.toLowerCase());\r
490                         if (matches && negative)\r
491                                 return false;\r
492                         if (matches && !negative)\r
493                                 return true;\r
494                 }\r
495                 if (negative)\r
496                         return true;\r
497                 else\r
498                         return false;\r
499         }\r
500         // Match notebooks in search terms against notes\r
501         private boolean matchContentAll(Note n) {\r
502                 if (todo.size() == 0 && resource.size() == 0 && searchPhrases.size() == 0)\r
503                         return true;\r
504                 \r
505                 n = conn.getNoteTable().getNote(n.getGuid(), true, true, false, false, false);\r
506                 \r
507                 // Check for search phrases\r
508                 String text = StringEscapeUtils.unescapeHtml4(n.getContent().replaceAll("\\<.*?\\>", "")).toLowerCase();\r
509                 boolean negative = false;\r
510                 for (int i=0; i<searchPhrases.size(); i++) {\r
511                         String phrase = searchPhrases.get(i);\r
512                         if (phrase.startsWith("-")) {\r
513                                 negative = true;\r
514                                 phrase = phrase.substring(1);\r
515                         } else\r
516                                 negative = false;\r
517                         phrase = phrase.substring(1);\r
518                         phrase = phrase.substring(0,phrase.length()-1);\r
519                         if (text.indexOf(phrase)>=0 && negative) {\r
520                                 return false;\r
521                         } \r
522                         if (text.indexOf(phrase) < 0 && !negative)\r
523                                 return false;\r
524                 }\r
525 \r
526                 \r
527                 for (int i=0; i<todo.size(); i++) {\r
528                         String value = todo.get(i);\r
529                         value = value.replace("\"", "");\r
530                         boolean desiredState;\r
531                         if (!value.endsWith(":false") && !value.endsWith(":true") && !value.endsWith(":*") && !value.endsWith("*"))\r
532                                 return false;\r
533                         if (value.endsWith(":false"))\r
534                                 desiredState = false;\r
535                         else\r
536                                 desiredState = true;\r
537                         if (value.startsWith("-"))\r
538                                 desiredState = !desiredState;\r
539                         int pos = n.getContent().indexOf("<en-todo");\r
540                         if (pos == -1 && !value.startsWith("-"))\r
541                                 return false;\r
542                         if (pos > -1 && value.startsWith("-") && (value.endsWith("*") || value.endsWith(":")))\r
543                                 return false;\r
544                         if (pos == -1 && !value.startsWith("-")) \r
545                                 return false;\r
546                         boolean returnTodo = false;\r
547                         while (pos > -1) {\r
548                                 int endPos = n.getContent().indexOf(">", pos);\r
549                                 String segment = n.getContent().substring(pos, endPos);\r
550                                 boolean currentState;\r
551                                 if (segment.toLowerCase().indexOf("checked=\"true\"") == -1)\r
552                                         currentState = false;\r
553                                 else\r
554                                         currentState = true;\r
555                                 if (desiredState == currentState) \r
556                                         returnTodo = true;\r
557                                 if (value.endsWith("*") || value.endsWith(":"))\r
558                                         returnTodo = true;\r
559                                 \r
560                                 pos = n.getContent().indexOf("<en-todo", pos+1);\r
561                         }\r
562                         if (!returnTodo)\r
563                                 return false;\r
564                 }\r
565                 \r
566                 // Check resources\r
567                 for (int i=0; i<resource.size(); i++) {\r
568                         String resourceString = resource.get(i);\r
569                         resourceString = resourceString.replace("\"", "");\r
570                         negative = false;\r
571                         if (resourceString.startsWith("-"))\r
572                                 negative = true;\r
573                         resourceString = resourceString.substring(resourceString.indexOf(":")+1);\r
574                         if (resourceString.equals(""))\r
575                                 return false;\r
576                         for (int j=0; j<n.getResourcesSize(); j++) {\r
577                                 boolean match = stringMatch(n.getResources().get(j).getMime(), resourceString, negative);\r
578                                 if (!match && !negative)\r
579                                         return false;\r
580                                 if (match && negative) \r
581                                         return false;\r
582                         }\r
583                 }\r
584                 \r
585                 return true;\r
586         }\r
587         \r
588         private boolean stringMatch(String content, String text, boolean negative) {\r
589                 String regex;\r
590                 if (content == null && !negative)\r
591                         return false;\r
592                 if (content == null && negative)\r
593                         return true;\r
594                 \r
595                 if (text.endsWith("*")) {\r
596                         text = text.substring(0,text.length()-1);\r
597                         regex = text;\r
598                 } else {\r
599                         regex = text;\r
600                 }\r
601                 content = content.toLowerCase();\r
602                 regex = regex.toLowerCase();\r
603                 boolean matches = content.startsWith(regex);\r
604                 if (negative)\r
605                         return !matches;\r
606                 return matches;\r
607         }\r
608         \r
609         // Remove odd strings from search terms\r
610         private String cleanupWord(String word) {\r
611                 if (word.startsWith("\""))\r
612                         word = word.substring(1);\r
613                 if (word.endsWith("\""))\r
614             word = word.substring(0,word.length()-1);\r
615                 word = word.replace("\\\"","\"");\r
616                 word = word.replace("\\\\","\\");\r
617                 \r
618                 return word;\r
619         }\r
620 \r
621         \r
622         // Match dates\r
623         private boolean matchDatesAll(List<String> dates, long noteDate) {\r
624                 if (dates.size()== 0) \r
625                         return true;\r
626                 \r
627                 boolean negative = false;\r
628                 for (int i=0; i<dates.size(); i++) {\r
629                         String requiredDate = dates.get(i);\r
630                         if (requiredDate.startsWith("-"))\r
631                                 negative = true;\r
632                         \r
633                         int response = 0;\r
634                         requiredDate = requiredDate.substring(requiredDate.indexOf(":")+1);\r
635                         try {\r
636                                 response = dateCheck(requiredDate, noteDate);\r
637                         } catch (java.lang.NumberFormatException e) {return false;}  {\r
638                                 if (negative && response < 0)\r
639                                         return false;\r
640                                 if (!negative && response > 0)\r
641                                         return false;\r
642                         }\r
643                 }\r
644                 return true;\r
645         }\r
646         private boolean matchDatesAny(List<String> dates, long noteDate) {\r
647                 if (dates.size()== 0) \r
648                         return true;\r
649                 \r
650                 boolean negative = false;\r
651                 for (int i=0; i<dates.size(); i++) {\r
652                         String requiredDate = dates.get(i);\r
653                         if (requiredDate.startsWith("-"))\r
654                                 negative = true;\r
655                         \r
656                         int response = 0;\r
657                         requiredDate = requiredDate.substring(requiredDate.indexOf(":")+1);\r
658                         try {\r
659                                 response = dateCheck(requiredDate, noteDate);\r
660                         } catch (java.lang.NumberFormatException e) {return false;}  {\r
661                                 if (negative && response > 0)\r
662                                         return true;\r
663                                 if (!negative && response < 0)\r
664                                         return true;\r
665                         }\r
666                 }\r
667                 return false;\r
668         }\r
669         \r
670         @SuppressWarnings("unused")\r
671         private void printCalendar(Calendar calendar) {\r
672                 // define output format and print\r
673                 SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy hh:mm:ss aaa");\r
674                 String date = sdf.format(calendar.getTime());\r
675                 System.err.print(date);\r
676                 calendar = new GregorianCalendar();\r
677         }\r
678         \r
679         \r
680         //****************************************\r
681         //****************************************\r
682         // Match search terms against notes\r
683         //****************************************\r
684         //****************************************\r
685         public List<Note> matchWords() {\r
686                 logger.log(logger.EXTREME, "Inside EnSearch.matchWords()");\r
687                 boolean subSelect = false;\r
688                 \r
689                 NoteTable noteTable = new NoteTable(logger, conn);  \r
690                 List<String> validGuids = new ArrayList<String>();\r
691                 \r
692                 if (searchWords.size() > 0) \r
693                         subSelect = true;\r
694 \r
695                 NSqlQuery query = new NSqlQuery(conn.getConnection());\r
696                 // Build a temp table for GUID results\r
697                 if (!conn.dbTableExists("SEARCH_RESULTS")) {\r
698                         query.exec("create temporary table SEARCH_RESULTS (guid varchar)");\r
699                         query.exec("create temporary table SEARCH_RESULTS_MERGE (guid varchar)");\r
700                 } else {\r
701                         query. exec("Delete from SEARCH_RESULTS");\r
702                         query. exec("Delete from SEARCH_RESULTS_MERGE");\r
703                 }\r
704 \r
705                 NSqlQuery insertQuery = new NSqlQuery(conn.getConnection());\r
706 //              NSqlQuery indexQuery = new NSqlQuery(conn.getIndexConnection());\r
707                 NSqlQuery mergeQuery = new NSqlQuery(conn.getConnection());\r
708                 NSqlQuery deleteQuery = new NSqlQuery(conn.getConnection());\r
709                 NSqlQuery ftlQuery = new NSqlQuery(conn.getConnection());\r
710                 ftlQuery.prepare("SELECT N.GUID AS GUID FROM FTL_SEARCH_DATA(:text, 0, 0) FT, NOTE N WHERE FT.TABLE='NOTE' AND N.GUID=FT.KEYS[0]");\r
711                 \r
712                 insertQuery.prepare("Insert into SEARCH_RESULTS (guid) values (:guid)");\r
713                 mergeQuery.prepare("Insert into SEARCH_RESULTS_MERGE (guid) values (:guid)");\r
714                 \r
715                 if (subSelect) {\r
716                         for (int i=0; i<getWords().size(); i++) {\r
717 //                              if (getWords().get(i).indexOf("*") == -1) {\r
718 //                                      indexQuery.prepare("Select distinct guid from words where weight >= " +minimumRecognitionWeight +\r
719 //                                                      " and word=:word");\r
720 //                                      indexQuery.bindValue(":word", getWords().get(i));\r
721 //                              } else {\r
722 //                                      indexQuery.prepare("Select distinct guid from words where weight >= " +minimumRecognitionWeight +\r
723 //                                              " and word like :word");\r
724 //                                      indexQuery.bindValue(":word", getWords().get(i).replace("*", "%"));\r
725 //                              }\r
726                                 \r
727                                 ftlQuery.bindValue(":text", getWords().get(i));\r
728                                 ftlQuery.exec();\r
729                                 \r
730                                 String guid = null;\r
731                                 while(ftlQuery.next()) {\r
732                                         guid = ftlQuery.valueString(0);\r
733                                         if (i==0 || any) {\r
734                                                 insertQuery.bindValue(":guid", guid);\r
735                                                 insertQuery.exec();\r
736                                         } else {\r
737                                                 mergeQuery.bindValue(":guid", guid);\r
738                                                 mergeQuery.exec();\r
739                                         }\r
740                                 }\r
741                                 if (i>0 && !any) {\r
742                                         deleteQuery.exec("Delete from SEARCH_RESULTS where guid not in (select guid from SEARCH_RESULTS_MERGE)");\r
743                                         deleteQuery.exec("Delete from SEARCH_RESULTS_MERGE");\r
744                                 }\r
745                         }\r
746 \r
747                         query.prepare("Select distinct guid from Note where guid in (Select guid from SEARCH_RESULTS)");\r
748                         if (!query.exec()) \r
749                                 logger.log(logger.LOW, "Error merging search results:" + query.lastError());\r
750                 \r
751                         while (query.next()) {\r
752                                 validGuids.add(query.valueString(0));\r
753                         }\r
754                 }\r
755                 \r
756                 List<Note> noteIndex = noteTable.getAllNotes();\r
757                 List<Note> guids = new ArrayList<Note>();\r
758                 for (int i=0; i<noteIndex.size(); i++) {\r
759                         Note n = noteIndex.get(i);\r
760                         boolean good = true;\r
761                         \r
762                         if (!validGuids.contains(n.getGuid()) && subSelect)\r
763                                 good = false;\r
764                                                 \r
765                         // Start matching special stuff, like tags & notebooks\r
766                         if (any) {\r
767                                 if (good && !matchTagsAny(n.getTagNames(), getTags()))\r
768                                         good = false;\r
769                                 if (good && !matchNotebook(n.getNotebookGuid()))\r
770                                         good = false;\r
771                                 if (good && !matchNotebookStack(n.getNotebookGuid()))\r
772                                         good = false;\r
773                                 if (good && !matchListAny(getIntitle(), n.getTitle()))\r
774                                         good = false;\r
775                                 if (good && !matchListAny(getAuthor(), n.getAttributes().getAuthor()))\r
776                                         good = false;\r
777                                 if (good && !matchListAny(getSource(), n.getAttributes().getSource()))\r
778                                         good = false;\r
779                                 if (good && !matchListAny(getSourceApplication(), n.getAttributes().getSourceApplication()))\r
780                                         good = false;\r
781                                 if (good && !matchContentAny(n))\r
782                                         good = false;\r
783                                 if (good && !matchDatesAny(getCreated(), n.getCreated()))\r
784                                         good = false;\r
785                                 if (good && !matchDatesAny(getUpdated(), n.getUpdated()))\r
786                                         good = false;\r
787                                 if (good && n.getAttributes() != null && !matchDatesAny(getSubjectDate(), n.getAttributes().getSubjectDate()))\r
788                                         good = false;\r
789                         } else {\r
790                                 if (good && !matchTagsAll(n.getTagNames(), getTags()))\r
791                                         good = false;\r
792                                 if (good && !matchNotebook(n.getNotebookGuid()))\r
793                                         good = false;\r
794                                 if (good && !matchNotebookStack(n.getNotebookGuid()))\r
795                                         good = false;\r
796                                 if (good && !matchListAll(getIntitle(), n.getTitle()))\r
797                                         good = false;\r
798                                 if (good && !matchListAll(getAuthor(), n.getAttributes().getAuthor()))\r
799                                         good = false;\r
800                                 if (good && !matchListAll(getSource(), n.getAttributes().getSource()))\r
801                                         good = false;\r
802                                 if (good && !matchListAll(getSourceApplication(), n.getAttributes().getSourceApplication()))\r
803                                         good = false;\r
804                                 if (good && !matchContentAll(n))\r
805                                         good = false;\r
806                                 if (good && !matchDatesAll(getCreated(), n.getCreated()))\r
807                                         good = false;\r
808                                 if (good && !matchDatesAll(getUpdated(), n.getUpdated()))\r
809                                         good = false;\r
810                                 if (good && n.getAttributes() != null && !matchDatesAll(getSubjectDate(), n.getAttributes().getSubjectDate()))\r
811                                         good = false;\r
812                         }\r
813                         if (good) {\r
814                                 guids.add(n);\r
815                         }\r
816                 }\r
817                 \r
818                 // For performance reasons, we didn't get the tags for every note individually.  We now need to \r
819                 // get them\r
820                 List<NoteTagsRecord> noteTags = noteTable.noteTagsTable.getAllNoteTags();\r
821                 for (int i=0; i<guids.size(); i++) {\r
822                         List<String> tags = new ArrayList<String>();\r
823                         List<String> names = new ArrayList<String>();\r
824                         for (int j=0; j<noteTags.size(); j++) {\r
825                                 if (guids.get(i).getGuid().equals(noteTags.get(j).noteGuid)) {\r
826                                         tags.add(noteTags.get(j).tagGuid);\r
827                                         names.add(getTagNameByGuid(noteTags.get(j).tagGuid));\r
828                                 }\r
829                         }\r
830                         \r
831                         guids.get(i).setTagGuids(tags);\r
832                         guids.get(i).setTagNames(names);\r
833                 };\r
834                 logger.log(logger.EXTREME, "Leaving EnSearch.matchWords()");\r
835                 return guids;\r
836         }\r
837         \r
838         \r
839         \r
840         private String getTagNameByGuid(String guid) {\r
841                 for (int i=0; i<tagIndex.size(); i++) {\r
842                         if (tagIndex.get(i).getGuid().equals(guid)) \r
843                                         return tagIndex.get(i).getName();\r
844                 }               \r
845                 return "";\r
846         }\r
847 \r
848         // Compare dates\r
849         public int dateCheck(String date, long noteDate)  throws java.lang.NumberFormatException  {\r
850                 int offset = 0;\r
851                 boolean found = false;\r
852                 GregorianCalendar calendar = new GregorianCalendar();\r
853                 \r
854                 if (date.contains("-")) {\r
855                         String modifier = date.substring(date.indexOf("-")+1);\r
856                         offset = new Integer(modifier);\r
857                         offset = 0-offset;\r
858                         date = date.substring(0,date.indexOf("-"));\r
859                 }\r
860                 \r
861                 if (date.contains("+")) {\r
862                         String modifier = date.substring(date.indexOf("+")+1);\r
863                         offset = new Integer(modifier);\r
864                         date = date.substring(0,date.indexOf("+"));\r
865                 }\r
866                 \r
867                 if (date.equalsIgnoreCase("today")) {\r
868                         calendar.add(Calendar.DATE, offset);\r
869                         calendar.set(Calendar.HOUR, 0);\r
870                         calendar.set(Calendar.MINUTE, 0);\r
871                         calendar.set(Calendar.SECOND, 1);\r
872                         found = true;\r
873                 }\r
874                 \r
875                 if (date.equalsIgnoreCase("month")) {\r
876                         calendar.add(Calendar.MONTH, offset);\r
877                         calendar.set(Calendar.DAY_OF_MONTH, 1);\r
878                         calendar.set(Calendar.HOUR, 0);\r
879                         calendar.set(Calendar.MINUTE, 0);\r
880                         calendar.set(Calendar.SECOND, 1);\r
881                         found = true;\r
882                 }\r
883 \r
884                 if (date.equalsIgnoreCase("year")) {\r
885                         calendar.add(Calendar.YEAR, offset);\r
886                         calendar.set(Calendar.MONTH, Calendar.JANUARY);\r
887                         calendar.set(Calendar.DAY_OF_MONTH, 1);\r
888                         calendar.set(Calendar.HOUR, 0);\r
889                         calendar.set(Calendar.MINUTE, 0);\r
890                         calendar.set(Calendar.SECOND, 1);\r
891                         found = true;\r
892                 }\r
893 \r
894                 if (date.equalsIgnoreCase("week")) {\r
895                         calendar.add(Calendar.DATE, 0-calendar.get(Calendar.DAY_OF_WEEK)+1);\r
896                         calendar.add(Calendar.DATE,(offset*7));\r
897                         calendar.set(Calendar.HOUR, 0);\r
898                         calendar.set(Calendar.MINUTE, 0);\r
899                         calendar.set(Calendar.SECOND, 1);\r
900 \r
901                         found = true;\r
902                 }\r
903                 \r
904                 // If nothing was found, then we have a date number\r
905                 if (!found) {\r
906                         calendar = stringToGregorianCalendar(date);\r
907                 }\r
908                 \r
909                 \r
910                 String dateTimeFormat = new String("yyyyMMdd-HHmmss");\r
911                 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);\r
912                 StringBuilder creationDate = new StringBuilder(simple.format(noteDate));\r
913                 GregorianCalendar nCalendar = stringToGregorianCalendar(creationDate.toString().replace("-", "T"));\r
914                 if (calendar == null || nCalendar == null)  // If we have something invalid, it automatically fails\r
915                         return 1;\r
916                 return calendar.compareTo(nCalendar);\r
917         }\r
918         private GregorianCalendar stringToGregorianCalendar(String date) {\r
919                 String datePart = date;\r
920                 GregorianCalendar calendar = new GregorianCalendar();\r
921                 boolean GMT = false;\r
922                 String timePart = "";\r
923                 if (date.contains("T")) {\r
924                         datePart = date.substring(0,date.indexOf("T"));\r
925                         timePart = date.substring(date.indexOf("T")+1);\r
926                 } else {\r
927                         timePart = "000001";\r
928                 }\r
929                 if (datePart.length() != 8)\r
930                         return null;\r
931                 calendar.set(Calendar.YEAR, new Integer(datePart.substring(0,4)));\r
932                 calendar.set(Calendar.MONTH, new Integer(datePart.substring(4,6))-1);\r
933                 calendar.set(Calendar.DAY_OF_MONTH, new Integer(datePart.substring(6)));\r
934                 if (timePart.endsWith("Z")) {\r
935                         GMT = true;\r
936                         timePart = timePart.substring(0,timePart.length()-1);\r
937                 }\r
938                 timePart = timePart.concat("000000");\r
939                 timePart = timePart.substring(0,6);\r
940                 calendar.set(Calendar.HOUR, new Integer(timePart.substring(0,2)));\r
941                 calendar.set(Calendar.MINUTE, new Integer(timePart.substring(2,4)));\r
942                 calendar.set(Calendar.SECOND, new Integer(timePart.substring(4)));\r
943                 if (GMT)\r
944                         calendar.set(Calendar.ZONE_OFFSET, -1*(calendar.get(Calendar.ZONE_OFFSET)/(1000*60*60)));\r
945                 return calendar;\r
946 \r
947         }\r
948                 \r
949 }\r