OSDN Git Service

Correct issues with importing notes that contain resources.
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / sql / NoteTable.java
1 /*\r
2  * This file is part of NixNote \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.DateFormat;\r
24 import java.text.ParseException;\r
25 import java.text.SimpleDateFormat;\r
26 import java.util.ArrayList;\r
27 import java.util.HashMap;\r
28 import java.util.List;\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.NoteAttributes;\r
34 import com.evernote.edam.type.Resource;\r
35 import com.evernote.edam.type.Tag;\r
36 import com.trolltech.qt.core.QByteArray;\r
37 import com.trolltech.qt.core.QDateTime;\r
38 import com.trolltech.qt.core.QTextCodec;\r
39 import com.trolltech.qt.gui.QPixmap;\r
40 \r
41 import cx.fbn.nevernote.Global;\r
42 import cx.fbn.nevernote.evernote.EnmlConverter;\r
43 import cx.fbn.nevernote.evernote.NoteMetadata;\r
44 import cx.fbn.nevernote.sql.driver.NSqlQuery;\r
45 import cx.fbn.nevernote.utilities.ApplicationLogger;\r
46 import cx.fbn.nevernote.utilities.Pair;\r
47 \r
48 public class NoteTable {\r
49         private final ApplicationLogger                 logger;\r
50         public final NoteTagsTable                              noteTagsTable;\r
51         public NoteResourceTable                                noteResourceTable;\r
52         private final DatabaseConnection                db;\r
53         int id;\r
54 \r
55         // Prepared Queries to improve speed\r
56         private NSqlQuery                                               getQueryWithContent;\r
57         private NSqlQuery                                               getQueryWithoutContent;\r
58         private NSqlQuery                                               getAllQueryWithoutContent;\r
59         \r
60         // Constructor\r
61         public NoteTable(ApplicationLogger l, DatabaseConnection d) {\r
62                 logger = l;\r
63                 db = d;\r
64                 id = 0;\r
65                 noteResourceTable = new NoteResourceTable(logger, db);\r
66                 noteTagsTable = new NoteTagsTable(logger, db);\r
67                 getQueryWithContent = null;\r
68                 getQueryWithoutContent = null;\r
69         }\r
70         // Create the table\r
71         public void createTable() {\r
72                 //getQueryWithContent = new NSqlQuery(db.getConnection());\r
73                 //getQueryWithoutContent = new NSqlQuery(db.getConnection());\r
74                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
75         logger.log(logger.HIGH, "Creating table Note...");\r
76         if (!query.exec("Create table Note (guid varchar primary key, " +\r
77                         "updateSequenceNumber integer, title varchar, content varchar, contentHash varchar, "+\r
78                         "contentLength integer, created timestamp, updated timestamp, deleted timestamp, " \r
79                         +"active integer, notebookGuid varchar, attributeSubjectDate timestamp, "+\r
80                         "attributeLatitude double, attributeLongitude double, attributeAltitude double,"+\r
81                         "attributeAuthor varchar, attributeSource varchar, attributeSourceUrl varchar, "+\r
82                         "attributeSourceApplication varchar, indexNeeded boolean, isExpunged boolean, " +\r
83                         "isDirty boolean)"))                    \r
84                 logger.log(logger.HIGH, "Table Note creation FAILED!!!");    \r
85         if (!query.exec("CREATE INDEX unindexed_notess on note (indexneeded desc, guid);"))\r
86                 logger.log(logger.HIGH, "Note unindexed_notes index creation FAILED!!!");\r
87         if (!query.exec("CREATE INDEX unsynchronized_notes on note (isDirty desc, guid);"))\r
88                 logger.log(logger.HIGH, "note unsynchronized_notes index creation FAILED!!!");  \r
89         noteTagsTable.createTable();\r
90 //        noteResourceTable.createTable();     \r
91         }\r
92         // Drop the table\r
93         public void dropTable() {\r
94                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
95                 query.exec("Drop table Note");\r
96                 noteTagsTable.dropTable();\r
97                 noteResourceTable.dropTable();\r
98         }\r
99         // Save Note List from Evernote \r
100         public void addNote(Note n, boolean isDirty) {\r
101                 logger.log(logger.EXTREME, "Inside addNote");\r
102                 if (n == null)\r
103                         return;\r
104                 \r
105                 SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");\r
106 \r
107                 NSqlQuery query = new NSqlQuery(db.getConnection());                    \r
108                 query.prepare("Insert Into Note ("\r
109                                 +"guid, updateSequenceNumber, title, content, "\r
110                                 +"contentHash, contentLength, created, updated, deleted, active, notebookGuid, "\r
111                                 +"attributeSubjectDate, attributeLatitude, attributeLongitude, attributeAltitude, "\r
112                                 +"attributeAuthor, attributeSource, attributeSourceUrl, attributeSourceApplication, "\r
113                                 +"indexNeeded, isExpunged, isDirty, titlecolor, thumbnailneeded" \r
114                                 +") Values("\r
115                                 +":guid, :updateSequenceNumber, :title, :content, "\r
116                                 +":contentHash, :contentLength, :created, :updated, :deleted, :active, :notebookGuid, "\r
117                                 +":attributeSubjectDate, :attributeLatitude, :attributeLongitude, :attributeAltitude, "\r
118                                 +":attributeAuthor, :attributeSource, :attributeSourceUrl, :attributeSourceApplication, "\r
119                                 +":indexNeeded, :isExpunged, :isDirty, -1, true) ");\r
120 \r
121                 StringBuilder created = new StringBuilder(simple.format(n.getCreated()));                       \r
122                 StringBuilder updated = new StringBuilder(simple.format(n.getUpdated()));                       \r
123                 StringBuilder deleted = new StringBuilder(simple.format(n.getDeleted()));\r
124 \r
125                 \r
126                 \r
127                 query.bindValue(":guid", n.getGuid());\r
128                 query.bindValue(":updateSequenceNumber", n.getUpdateSequenceNum());\r
129                 query.bindValue(":title", n.getTitle());\r
130                 if (isDirty) {\r
131                         EnmlConverter enml = new EnmlConverter(logger);\r
132                         query.bindValue(":content", enml.fixEnXMLCrap(enml.fixEnMediaCrap(n.getContent())));\r
133                 }\r
134                 else\r
135                         query.bindValue(":content", n.getContent());\r
136                 query.bindValue(":contentHash", n.getContentHash());\r
137                 query.bindValue(":contentLength", n.getContentLength());\r
138                 query.bindValue(":created", created.toString());\r
139                 query.bindValue(":updated", updated.toString());\r
140                 query.bindValue(":deleted", deleted.toString());\r
141                 query.bindValue(":active", n.isActive());\r
142                 query.bindValue(":notebookGuid", n.getNotebookGuid());\r
143                 \r
144                 if (n.getAttributes() != null) {\r
145                         created = new StringBuilder(simple.format(n.getAttributes().getSubjectDate()));\r
146                         query.bindValue(":attributeSubjectDate", created.toString());\r
147                         query.bindValue(":attributeLatitude", n.getAttributes().getLatitude());\r
148                         query.bindValue(":attributeLongitude", n.getAttributes().getLongitude());\r
149                         query.bindValue(":attributeAltitude", n.getAttributes().getAltitude());\r
150                         query.bindValue(":attributeAuthor", n.getAttributes().getAuthor());\r
151                         query.bindValue(":attributeSource", n.getAttributes().getSource());\r
152                         query.bindValue(":attributeSourceUrl", n.getAttributes().getSourceURL());\r
153                         query.bindValue(":attributeSourceApplication", n.getAttributes().getSourceApplication());\r
154                 } else {\r
155                         created = new StringBuilder(simple.format(n.getCreated()));     \r
156                         query.bindValue(":attributeSubjectDate", created.toString());\r
157                         query.bindValue(":attributeLatitude", 0.0);\r
158                         query.bindValue(":attributeLongitude", 0.0);\r
159                         query.bindValue(":attributeAltitude", 0.0);\r
160                         query.bindValue(":attributeAuthor", "");\r
161                         query.bindValue(":attributeSource", "");\r
162                         query.bindValue(":attributeSourceUrl", "");\r
163                         query.bindValue(":attributeSourceApplication", "");\r
164                 }\r
165                 query.bindValue(":indexNeeded", true);\r
166                 query.bindValue(":isExpunged", false);\r
167                 query.bindValue(":isDirty", isDirty);\r
168 \r
169                 \r
170                 if (!query.exec())\r
171                         logger.log(logger.MEDIUM, query.lastError());\r
172                 \r
173                 // Save the note tags\r
174                 if (n.getTagGuids() != null) {\r
175                         for (int i=0; i<n.getTagGuids().size(); i++) \r
176                                 noteTagsTable.saveNoteTag(n.getGuid(), n.getTagGuids().get(i));\r
177                 }\r
178                 logger.log(logger.EXTREME, "Leaving addNote");\r
179         } \r
180         // Setup queries for get to save time later\r
181         private void prepareQueries() {\r
182                 if (getQueryWithContent == null) {\r
183                         getQueryWithContent = new NSqlQuery(db.getConnection());\r
184                         if (!getQueryWithContent.prepare("Select "\r
185                                         +"guid, updateSequenceNumber, title, "\r
186                                         +"created, updated, deleted, active, notebookGuid, "\r
187                                         +"attributeSubjectDate, attributeLatitude, attributeLongitude, attributeAltitude, "\r
188                                         +"attributeAuthor, attributeSource, attributeSourceUrl, attributeSourceApplication, "\r
189                                         +"attributeContentClass, "\r
190                                         +"content, contentHash, contentLength"\r
191                                         +" from Note where guid=:guid and isExpunged=false")) {\r
192                                                 logger.log(logger.EXTREME, "Note SQL select prepare with content has failed.");\r
193                                                 logger.log(logger.MEDIUM, getQueryWithContent.lastError());\r
194                         }\r
195                 }\r
196                 \r
197                 if (getQueryWithoutContent == null) {\r
198                         getQueryWithoutContent = new NSqlQuery(db.getConnection());\r
199                         if (!getQueryWithoutContent.prepare("Select "\r
200                                         +"guid, updateSequenceNumber, title, "\r
201                                         +"created, updated, deleted, active, notebookGuid, "\r
202                                         +"attributeSubjectDate, attributeLatitude, attributeLongitude, attributeAltitude, "\r
203                                         +"attributeAuthor, attributeSource, attributeSourceUrl, attributeSourceApplication, "\r
204                                         +"attributeContentClass"\r
205                                         +" from Note where guid=:guid and isExpunged=false")) {\r
206                                                 logger.log(logger.EXTREME, "Note SQL select prepare without content has failed.");\r
207                                                 logger.log(logger.MEDIUM, getQueryWithoutContent.lastError());\r
208                         }\r
209                 }\r
210                         \r
211                 if (getAllQueryWithoutContent == null) {\r
212                         getAllQueryWithoutContent = new NSqlQuery(db.getConnection());\r
213                 \r
214                         if (!getAllQueryWithoutContent.prepare("Select "\r
215                                 +"guid, updateSequenceNumber, title, "\r
216                                 +"created, updated, deleted, active, notebookGuid, "\r
217                                 +"attributeSubjectDate, attributeLatitude, attributeLongitude, attributeAltitude, "\r
218                                 +"attributeAuthor, attributeSource, attributeSourceUrl, attributeSourceApplication, "\r
219                                 +"attributeContentClass "\r
220                                 +" from Note where isExpunged = false")) {\r
221                                 logger.log(logger.EXTREME, "Note SQL select prepare without content has failed.");\r
222                                         logger.log(logger.MEDIUM, getQueryWithoutContent.lastError());\r
223                         }\r
224                 }\r
225         }\r
226 \r
227 \r
228         // Get a note's content in blob format for index.\r
229         public String getNoteContentNoUTFConversion(String guid) {\r
230                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
231                 query.prepare("Select content from note where guid=:guid");\r
232                 query.bindValue(":guid", guid);\r
233                 query.exec();           \r
234                 query.next();\r
235                 return query.valueString(0);\r
236         }\r
237         // Get a note by Guid\r
238         public Note getNote(String noteGuid, boolean loadContent, boolean loadResources, boolean loadRecognition, boolean loadBinary, boolean loadTags) {\r
239 \r
240 //              extractMetadata("otherKey:{values};baumgarte:{titleColor=fff;pinned=true;};finalKey:{values1);");\r
241                 if (noteGuid == null)\r
242                         return null;\r
243                 if (noteGuid.trim().equals(""))\r
244                         return null;\r
245 \r
246                 prepareQueries();\r
247                 NSqlQuery query;\r
248                 if (loadContent) {\r
249                         query = getQueryWithContent;\r
250                 } else {\r
251                         query = getQueryWithoutContent;\r
252                 }\r
253                 \r
254                 query.bindValue(":guid", noteGuid);\r
255                 if (!query.exec()) {\r
256                         logger.log(logger.EXTREME, "Note SQL select exec has failed.");\r
257                         logger.log(logger.MEDIUM, query.lastError());\r
258                         return null;\r
259                 }\r
260                 if (!query.next()) {\r
261                         logger.log(logger.EXTREME, "SQL Retrieve failed for note guid " +noteGuid + " in getNote()");\r
262                         logger.log(logger.EXTREME, " -> " +query.lastError().toString());\r
263                         logger.log(logger.EXTREME, " -> " +query.lastError());\r
264                         return null;\r
265                 }\r
266                 Note n = mapNoteFromQuery(query, loadContent, loadResources, loadRecognition, loadBinary, loadTags);\r
267                 n.setContent(fixCarriageReturn(n.getContent()));\r
268                 n.getAttributes().setContentClassIsSet(false);\r
269                 return n;\r
270         }\r
271         // Get a note by Guid\r
272         public Note mapNoteFromQuery(NSqlQuery query, boolean loadContent, boolean loadResources, boolean loadRecognition, boolean loadBinary, boolean loadTags) {\r
273                 DateFormat indfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");\r
274 //              indfm = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");\r
275 \r
276                 Note n = new Note();\r
277                 NoteAttributes na = new NoteAttributes();\r
278                 n.setAttributes(na);\r
279                 \r
280                 n.setGuid(query.valueString(0));\r
281                 n.setUpdateSequenceNum(new Integer(query.valueString(1)));\r
282                 n.setTitle(query.valueString(2));\r
283 \r
284                 try {\r
285                         n.setCreated(indfm.parse(query.valueString(3)).getTime());\r
286                         n.setUpdated(indfm.parse(query.valueString(4)).getTime());\r
287                         n.setDeleted(indfm.parse(query.valueString(5)).getTime());\r
288                 } catch (ParseException e) {\r
289                         e.printStackTrace();\r
290                 }\r
291 \r
292                 n.setActive(query.valueBoolean(6,true));\r
293                 n.setNotebookGuid(query.valueString(7));\r
294                 \r
295                 try {\r
296                         String attributeSubjectDate = query.valueString(8);\r
297                         if (!attributeSubjectDate.equals(""))\r
298                                 na.setSubjectDate(indfm.parse(attributeSubjectDate).getTime());\r
299                 } catch (ParseException e) {\r
300                         e.printStackTrace();\r
301                 }\r
302                 na.setLatitude(new Float(query.valueString(9)));\r
303                 na.setLongitude(new Float(query.valueString(10)));\r
304                 na.setAltitude(new Float(query.valueString(11)));\r
305                 na.setAuthor(query.valueString(12));\r
306                 na.setSource(query.valueString(13));\r
307                 na.setSourceURL(query.valueString(14));\r
308                 na.setSourceApplication(query.valueString(15));\r
309                 na.setContentClass(query.valueString(16));\r
310                 \r
311                 if (loadTags) {\r
312                         n.setTagGuids(noteTagsTable.getNoteTags(n.getGuid()));\r
313                         List<String> tagNames = new ArrayList<String>();\r
314                         TagTable tagTable = db.getTagTable();\r
315                         for (int i=0; i<n.getTagGuids().size(); i++) {\r
316                                 String currentGuid = n.getTagGuids().get(i);\r
317                                 Tag tag = tagTable.getTag(currentGuid);\r
318                                 if (tag.getName() != null)\r
319                                         tagNames.add(tag.getName());\r
320                                 else\r
321                                         tagNames.add("");\r
322                         }\r
323                         n.setTagNames(tagNames);\r
324                 }\r
325                 \r
326                 if (loadContent) {\r
327                         QTextCodec codec = QTextCodec.codecForLocale();\r
328                         codec = QTextCodec.codecForName("UTF-8");\r
329                 String unicode =  codec.fromUnicode(query.valueString(17)).toString();\r
330 \r
331                 // This is a hack.  Basically I need to convert HTML Entities to "normal" text, but if I\r
332                 // convert the &lt; character to < it will mess up the XML parsing.  So, to get around this\r
333                 // I am "bit stuffing" the &lt; to &&lt; so StringEscapeUtils doesn't unescape it.  After\r
334                 // I'm done I convert it back.\r
335                 StringBuffer buffer = new StringBuffer(unicode);\r
336                 if (Global.enableHTMLEntitiesFix && unicode.indexOf("&#") > 0) {\r
337                         unicode = query.valueString(17);\r
338                         //System.out.println(unicode);\r
339                         //unicode = unicode.replace("&lt;", "&_lt;");\r
340                         //unicode = codec.fromUnicode(StringEscapeUtils.unescapeHtml(unicode)).toString();\r
341                         //unicode = unicode.replace("&_lt;", "&lt;");\r
342                         //System.out.println("************************");\r
343                         int j=1;\r
344                         for (int i=buffer.indexOf("&#"); i != -1 && buffer.indexOf("&#", i)>0; i=buffer.indexOf("&#",i+1)) {\r
345                                 j = buffer.indexOf(";",i)+1;\r
346                                 if (i<j) {\r
347                                         String entity = buffer.substring(i,j).toString();\r
348                                         int len = entity.length()-1;\r
349                                         String tempEntity = entity.substring(2, len);\r
350                                         try {\r
351                                                 Integer.parseInt(tempEntity);\r
352                                                 entity = codec.fromUnicode(StringEscapeUtils.unescapeHtml4(entity)).toString();\r
353                                                 buffer.delete(i, j);\r
354                                                 buffer.insert(i, entity);\r
355                                         } catch (Exception e){ }\r
356                                         \r
357                                 }\r
358                         } \r
359                 } \r
360                         \r
361                 n.setContent(unicode);\r
362 //                      n.setContent(query.valueString(16).toString());\r
363                         \r
364                         String contentHash = query.valueString(18);\r
365                         if (contentHash != null)\r
366                                 n.setContentHash(contentHash.getBytes());\r
367                         n.setContentLength(new Integer(query.valueString(19)));\r
368                 }\r
369                 if (loadResources)\r
370                         n.setResources(noteResourceTable.getNoteResources(n.getGuid(), loadBinary));\r
371                 if (loadRecognition) {\r
372                         if (n.getResources() == null) {\r
373                                 List<Resource> resources = noteResourceTable.getNoteResourcesRecognition(n.getGuid());\r
374                                 n.setResources(resources);\r
375                         } else {\r
376                                 // We need to merge the recognition resources with the note resources retrieved earlier\r
377                                 for (int i=0; i<n.getResources().size(); i++) {\r
378                                         Resource r = noteResourceTable.getNoteResourceRecognition(n.getResources().get(i).getGuid());\r
379                                         n.getResources().get(i).setRecognition(r.getRecognition());\r
380                                 }\r
381                         }\r
382                 }\r
383                 n.setContent(fixCarriageReturn(n.getContent()));\r
384                 return n;\r
385         }\r
386         // Update a note's title\r
387         public void updateNoteTitle(String guid, String title) {\r
388                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
389                 boolean check = query.prepare("Update Note set title=:title, isDirty=true where guid=:guid");\r
390                 if (!check) {\r
391                         logger.log(logger.EXTREME, "Update note title sql prepare has failed.");\r
392                         logger.log(logger.MEDIUM, query.lastError());\r
393                 }\r
394                 query.bindValue(":title", title);\r
395                 query.bindValue(":guid", guid);\r
396                 check = query.exec();\r
397                 if (!check) {\r
398                         logger.log(logger.EXTREME, "Update note title has failed.");\r
399                         logger.log(logger.MEDIUM, query.lastError());\r
400                 }\r
401         }\r
402         // Update a note's creation date\r
403         public void updateNoteCreatedDate(String guid, QDateTime date) {\r
404                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
405                 boolean check = query.prepare("Update Note set created=:created, isDirty=true where guid=:guid");\r
406                 if (!check) {\r
407                         logger.log(logger.EXTREME, "Update note creation update sql prepare has failed.");\r
408                         logger.log(logger.MEDIUM, query.lastError());\r
409                 }\r
410                 \r
411                 query.bindValue(":created", date.toString("yyyy-MM-dd HH:mm:ss"));\r
412                 query.bindValue(":guid", guid);\r
413                 \r
414                 check = query.exec();\r
415                 if (!check) {\r
416                         logger.log(logger.EXTREME, "Update note creation date has failed.");\r
417                         logger.log(logger.MEDIUM, query.lastError());\r
418                 }\r
419         }\r
420         // Update a note's creation date\r
421         public void updateNoteAlteredDate(String guid, QDateTime date) {\r
422                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
423                 boolean check = query.prepare("Update Note set updated=:altered, isDirty=true where guid=:guid");\r
424                 if (!check) {\r
425                         logger.log(logger.EXTREME, "Update note altered sql prepare has failed.");\r
426                         logger.log(logger.MEDIUM, query.lastError());\r
427                 }\r
428                 \r
429                 query.bindValue(":altered", date.toString("yyyy-MM-dd HH:mm:ss"));\r
430                 query.bindValue(":guid", guid);\r
431                 \r
432                 check = query.exec();\r
433                 if (!check) {\r
434                         logger.log(logger.EXTREME, "Update note altered date has failed.");\r
435                         logger.log(logger.MEDIUM, query.lastError());\r
436                 }\r
437         }\r
438         // Update a note's creation date\r
439         public void updateNoteSubjectDate(String guid, QDateTime date) {\r
440                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
441                 boolean check = query.prepare("Update Note set attributeSubjectDate=:altered, isDirty=true where guid=:guid");\r
442                 if (!check) {\r
443                         logger.log(logger.EXTREME, "Update note subject date sql prepare has failed.");\r
444                         logger.log(logger.MEDIUM, query.lastError());\r
445                 }\r
446         \r
447                 query.bindValue(":altered", date.toString("yyyy-MM-dd HH:mm:ss"));\r
448                 query.bindValue(":guid", guid);\r
449                 \r
450                 check = query.exec();\r
451                 if (!check) {\r
452                         logger.log(logger.EXTREME, "Update note subject date date has failed.");\r
453                         logger.log(logger.MEDIUM, query.lastError());\r
454                 }\r
455         }\r
456         // Update a note's creation date\r
457         public void updateNoteAuthor(String guid, String author) {\r
458                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
459                 boolean check = query.prepare("Update Note set attributeAuthor=:author, isDirty=true where guid=:guid");\r
460                 if (!check) {\r
461                         logger.log(logger.EXTREME, "Update note author sql prepare has failed.");\r
462                         logger.log(logger.MEDIUM, query.lastError());\r
463                 }\r
464 \r
465                 query.bindValue(":author", author);\r
466                 query.bindValue(":guid", guid);\r
467 \r
468                 check = query.exec();\r
469                 if (!check) {\r
470                         logger.log(logger.EXTREME, "Update note author has failed.");\r
471                         logger.log(logger.MEDIUM, query.lastError());\r
472                 }\r
473                 \r
474         }\r
475         // Update a note's geo tags\r
476         public void updateNoteGeoTags(String guid, Double lon, Double lat, Double alt) {\r
477                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
478                 boolean check = query.prepare("Update Note set attributeLongitude=:longitude, "+\r
479                                 "attributeLatitude=:latitude, attributeAltitude=:altitude, isDirty=true where guid=:guid");\r
480                 if (!check) {\r
481                         logger.log(logger.EXTREME, "Update note author sql prepare has failed.");\r
482                         logger.log(logger.MEDIUM, query.lastError());\r
483                 }\r
484 \r
485                 query.bindValue(":longitude", lon);\r
486                 query.bindValue(":latitude", lat);\r
487                 query.bindValue(":altitude", alt);\r
488                 query.bindValue(":guid", guid);\r
489 \r
490                 check = query.exec();\r
491                 if (!check) {\r
492                         logger.log(logger.EXTREME, "Update note geo tag has failed.");\r
493                         logger.log(logger.MEDIUM, query.lastError());\r
494                 }\r
495                 \r
496         }\r
497         // Update a note's creation date\r
498         public void updateNoteSourceUrl(String guid, String url) {\r
499                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
500                 boolean check = query.prepare("Update Note set attributeSourceUrl=:url, isDirty=true where guid=:guid");\r
501                 if (!check) {\r
502                         logger.log(logger.EXTREME, "Update note url sql prepare has failed.");\r
503                         logger.log(logger.MEDIUM, query.lastError());\r
504                 }\r
505                 \r
506                 query.bindValue(":url", url);\r
507                 query.bindValue(":guid", guid);\r
508 \r
509                 check = query.exec();\r
510                 if (!check) {\r
511                         logger.log(logger.EXTREME, "Update note url has failed.");\r
512                         logger.log(logger.MEDIUM, query.lastError());\r
513                 }\r
514                 \r
515         }\r
516         // Update the notebook that a note is assigned to\r
517         public void updateNoteNotebook(String guid, String notebookGuid, boolean expungeFromRemote) {\r
518                 String currentNotebookGuid = new String("");\r
519                 \r
520                 \r
521                 // If we are going from a synchronized notebook to a local notebook, we\r
522                 // need to tell Evernote to purge the note online.  However, if this is  \r
523                 // conflicting change we move it to the local notebook without deleting it \r
524                 // or it would then delete the copy on the remote server.\r
525                 NotebookTable notebookTable = new NotebookTable(logger, db);\r
526                 DeletedTable deletedTable = new DeletedTable(logger, db);\r
527                 if (expungeFromRemote) {\r
528                         if (!notebookTable.isNotebookLocal(currentNotebookGuid) & notebookTable.isNotebookLocal(notebookGuid)) {\r
529                                 deletedTable.addDeletedItem(guid, "NOTE");\r
530                         }\r
531                 }\r
532                 \r
533                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
534                 boolean check = query.prepare("Update Note set notebookGuid=:notebook, isDirty=true where guid=:guid");\r
535                 if (!check) {\r
536                         logger.log(logger.EXTREME, "Update note notebook sql prepare has failed.");\r
537                         logger.log(logger.MEDIUM, query.lastError());\r
538                 }\r
539                 query.bindValue(":notebook", notebookGuid);\r
540                 query.bindValue(":guid", guid);\r
541                 \r
542                 check = query.exec();\r
543                 if (!check) {\r
544                         logger.log(logger.EXTREME, "Update note notebook has failed.");\r
545                         logger.log(logger.MEDIUM, query.lastError());\r
546                 };\r
547         }\r
548         // Update a note's title\r
549         public void updateNoteContent(String guid, String content) {\r
550                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
551                 boolean check = query.prepare("Update Note set content=:content, updated=CURRENT_TIMESTAMP(), isDirty=true, indexNeeded=true, " +\r
552                                 " thumbnailneeded=true where guid=:guid");\r
553                 if (!check) {\r
554                         logger.log(logger.EXTREME, "Update note content sql prepare has failed.");\r
555                         logger.log(logger.MEDIUM, query.lastError());\r
556                 }\r
557                 \r
558 //              QTextCodec codec = QTextCodec.codecForLocale();\r
559 //              codec = QTextCodec.codecForName("UTF-8");\r
560 //              query.bindValue(":content", codec.fromUnicode(content).toString());\r
561                 query.bindValue(":content", content);\r
562                 query.bindValue(":guid", guid);\r
563 \r
564                 check = query.exec();\r
565                 if (!check) {\r
566                         logger.log(logger.EXTREME, "Update note content has failed.");\r
567                         logger.log(logger.MEDIUM, query.lastError());\r
568                 }\r
569         }\r
570 \r
571         // Delete a note\r
572         public void deleteNote(String guid) {\r
573         NSqlQuery query = new NSqlQuery(db.getConnection());\r
574         query.prepare("Update Note set deleted=CURRENT_TIMESTAMP(), active=false, isDirty=true where guid=:guid");\r
575                 query.bindValue(":guid", guid);\r
576                 if (!query.exec()) {\r
577                         logger.log(logger.MEDIUM, "Note delete failed.");\r
578                         logger.log(logger.MEDIUM, query.lastError());\r
579                 }\r
580         }\r
581         public void restoreNote(String guid) {\r
582         NSqlQuery query = new NSqlQuery(db.getConnection());\r
583                 query.prepare("Update Note set deleted=:reset, active=true, isDirty=true where guid=:guid");\r
584 //              query.prepare("Update Note set deleted=0, active=true, isDirty=true where guid=:guid");\r
585                 query.bindValue(":guid", guid);\r
586                 query.bindValue(":reset", "1969-12-31 19:00:00");\r
587                 if (!query.exec()) {\r
588                         logger.log(logger.MEDIUM, "Note restore failed.");\r
589                         logger.log(logger.MEDIUM, query.lastError());\r
590                 }\r
591         }\r
592         // Purge a note (actually delete it instead of just marking it deleted)\r
593         public void expungeNote(String guid, boolean permanentExpunge, boolean needsSync) {\r
594                 \r
595                 if (!permanentExpunge) {\r
596                         hideExpungedNote(guid, needsSync);\r
597                         return;\r
598                 }\r
599                 \r
600                 \r
601         NSqlQuery note = new NSqlQuery(db.getConnection());\r
602         NSqlQuery resources = new NSqlQuery(db.getResourceConnection());\r
603         NSqlQuery tags = new NSqlQuery(db.getConnection());\r
604         NSqlQuery words = new NSqlQuery(db.getIndexConnection());\r
605         \r
606         note.prepare("Delete from Note where guid=:guid");\r
607                 resources.prepare("Delete from NoteResources where noteGuid=:guid");\r
608                 tags.prepare("Delete from NoteTags where noteGuid=:guid");\r
609                 words.prepare("Delete from words where guid=:guid");\r
610 \r
611                 note.bindValue(":guid", guid);\r
612                 resources.bindValue(":guid", guid);\r
613                 tags.bindValue(":guid", guid);\r
614                 words.bindValue(":guid", guid);\r
615         \r
616                 // Start purging notes.\r
617                 if (!note.exec()) {\r
618                         logger.log(logger.MEDIUM, "Purge from note failed.");\r
619                         logger.log(logger.MEDIUM, note.lastError());\r
620                 }\r
621                 if (!resources.exec()) {\r
622                                 logger.log(logger.MEDIUM, "Purge from resources failed.");\r
623                         logger.log(logger.MEDIUM, resources.lastError());\r
624                 }\r
625                 if (!tags.exec()) {\r
626                         logger.log(logger.MEDIUM, "Note tags delete failed.");\r
627                         logger.log(logger.MEDIUM, tags.lastError());\r
628                 }\r
629 \r
630                 if (!words.exec()) {\r
631                         logger.log(logger.MEDIUM, "Word delete failed.");\r
632                         logger.log(logger.MEDIUM, words.lastError());\r
633                 }\r
634                 if (needsSync) {\r
635                         DeletedTable deletedTable = new DeletedTable(logger, db);\r
636                         deletedTable.addDeletedItem(guid, "Note");\r
637                 }\r
638 \r
639         }\r
640         // Purge a bunch of notes based upon the notebook\r
641         public void expungeNotesByNotebook(String notebookGuid, boolean permanentExpunge, boolean needsSync) {\r
642                 List<String> notes = getNotesByNotebook(notebookGuid);\r
643                 for (int i=0; i<notes.size(); i++) {\r
644                         expungeNote(notes.get(i), permanentExpunge, needsSync);\r
645                 }\r
646         }\r
647 \r
648         // Purge a note (actually delete it instead of just marking it deleted)\r
649         public void hideExpungedNote(String guid, boolean needsSync) {\r
650         NSqlQuery note = new NSqlQuery(db.getConnection());\r
651         NSqlQuery resources = new NSqlQuery(db.getResourceConnection());\r
652         NSqlQuery tags = new NSqlQuery(db.getConnection());\r
653         NSqlQuery words = new NSqlQuery(db.getIndexConnection());\r
654         \r
655         note.prepare("Update Note set isExpunged=true where guid=:guid");\r
656                 resources.prepare("Delete from NoteResources where noteGuid=:guid");\r
657                 tags.prepare("Delete from NoteTags where noteGuid=:guid");\r
658 //              words.prepare("Delete from words where guid=:guid");\r
659 \r
660                 note.bindValue(":guid", guid);\r
661                 resources.bindValue(":guid", guid);\r
662                 tags.bindValue(":guid", guid);\r
663                 words.bindValue(":guid", guid);\r
664 \r
665                 // Start purging notes.\r
666                 if (!note.exec()) {\r
667                         logger.log(logger.MEDIUM, "Purge from note failed.");\r
668                         logger.log(logger.MEDIUM, note.lastError());\r
669                 }\r
670                 if (!resources.exec()) {\r
671                                 logger.log(logger.MEDIUM, "Purge from resources failed.");\r
672                         logger.log(logger.MEDIUM, resources.lastError());\r
673                 }\r
674                 if (!tags.exec()) {\r
675                         logger.log(logger.MEDIUM, "Note tags delete failed.");\r
676                         logger.log(logger.MEDIUM, tags.lastError());\r
677                 }\r
678 //              System.out.println("Hiding Note: Deleting words");\r
679 //              if (!words.exec()) {\r
680 //                      logger.log(logger.MEDIUM, "Word delete failed.");\r
681 //                      logger.log(logger.MEDIUM, words.lastError());\r
682 //              }\r
683                 if (needsSync) {\r
684                         DeletedTable deletedTable = new DeletedTable(logger, db);\r
685                         deletedTable.addDeletedItem(guid, "Note");\r
686                 }\r
687         }\r
688 \r
689                 \r
690         // Purge all deleted notes;\r
691         public void expungeAllDeletedNotes() {\r
692                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
693                 query.exec("select guid, updateSequenceNumber from note where active = false");\r
694                 List<String> guids = new ArrayList<String>();\r
695                 List<Integer> usns = new ArrayList<Integer>();\r
696                 while (query.next()) {\r
697                         guids.add(query.valueString(0));\r
698                         Integer usn = new Integer(query.valueString(1));\r
699                         usns.add(usn);\r
700                 }\r
701                 \r
702                 for (int i=0; i<guids.size(); i++) {\r
703                         Integer usn = usns.get(i);\r
704                         String guid = guids.get(i);\r
705                         if (usn == 0)\r
706                                 expungeNote(guid, true, false);\r
707                         else\r
708                                 expungeNote(guid, false, true);\r
709                 }\r
710         }\r
711         // Update the note sequence number\r
712         public void updateNoteSequence(String guid, int sequence) {\r
713                 boolean check;\r
714         NSqlQuery query = new NSqlQuery(db.getConnection());\r
715                 check = query.prepare("Update Note set updateSequenceNumber=:sequence where guid=:guid");\r
716 \r
717                 query.bindValue(":sequence", sequence);\r
718                 query.bindValue(":guid", guid);\r
719                 \r
720                 query.exec();\r
721                 if (!check) {\r
722                         logger.log(logger.MEDIUM, "Note sequence update failed.");\r
723                         logger.log(logger.MEDIUM, query.lastError());\r
724                 } \r
725         }\r
726         // Update the note Guid\r
727         public void updateNoteGuid(String oldGuid, String newGuid) {\r
728                 boolean check;\r
729         NSqlQuery query = new NSqlQuery(db.getConnection());\r
730         NSqlQuery resQuery = new NSqlQuery(db.getResourceConnection());\r
731         NSqlQuery wordQuery = new NSqlQuery(db.getIndexConnection());\r
732                 query.prepare("Update Note set guid=:newGuid, original_guid=:original_guid where guid=:oldGuid");\r
733 \r
734                 query.bindValue(":original_guid", oldGuid);\r
735                 query.bindValue(":newGuid", newGuid);\r
736                 query.bindValue(":oldGuid", oldGuid);\r
737 \r
738                 check = query.exec();\r
739                 if (!check) {\r
740                         logger.log(logger.MEDIUM, "Note Guid update failed.");\r
741                         logger.log(logger.MEDIUM, query.lastError());\r
742                 } \r
743                 \r
744                 query.prepare("Update NoteTags set noteGuid=:newGuid where noteGuid=:oldGuid");\r
745                 query.bindValue(":newGuid", newGuid);\r
746                 query.bindValue(":oldGuid", oldGuid);\r
747                 check = query.exec();\r
748                 if (!check) {\r
749                         logger.log(logger.MEDIUM, "Note guid update failed for NoteTags.");\r
750                         logger.log(logger.MEDIUM, query.lastError());\r
751                 }\r
752                 \r
753                 wordQuery.prepare("Update words set guid=:newGuid where guid=:oldGuid");\r
754                 wordQuery.bindValue(":newGuid", newGuid);\r
755                 wordQuery.bindValue(":oldGuid", oldGuid);\r
756                 wordQuery.exec();\r
757                 if (!check) {\r
758                         logger.log(logger.MEDIUM, "Note guid update failed for Words.");\r
759                         logger.log(logger.MEDIUM, wordQuery.lastError());\r
760                 }\r
761                 resQuery.prepare("Update noteresources set noteguid=:newGuid where noteguid=:oldGuid");\r
762                 resQuery.bindValue(":newGuid", newGuid);\r
763                 resQuery.bindValue(":oldGuid", oldGuid);\r
764                 resQuery.exec();\r
765                 if (!check) {\r
766                         logger.log(logger.MEDIUM, "Note guid update failed for noteresources.");\r
767                         logger.log(logger.MEDIUM, resQuery.lastError());\r
768                 }\r
769         }\r
770         // Update a note\r
771         public void updateNote(Note n) {\r
772                 NoteMetadata meta = getNoteMetaInformation(n.getGuid());\r
773                 String originalGuid = findAlternateGuid(n.getGuid());\r
774                 expungeNote(n.getGuid(), true, false);\r
775                 addNote(n, false);\r
776                 if (n!=null) {\r
777                         updateNoteMetadata(meta);\r
778                 }\r
779                 if (originalGuid != null) {\r
780                         updateNoteGuid(n.getGuid(), originalGuid);\r
781                         updateNoteGuid(originalGuid, n.getGuid());\r
782                 }\r
783         }\r
784         // Does a note exist?\r
785         public boolean exists(String guid) {\r
786                 if (guid == null)\r
787                         return false;\r
788                 if (guid.trim().equals(""))\r
789                         return false;\r
790                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
791                 query.prepare("Select guid from note where guid=:guid");\r
792                 query.bindValue(":guid", guid);\r
793                 if (!query.exec())\r
794                         logger.log(logger.EXTREME, "note.exists SQL retrieve has failed.");\r
795                 boolean retVal = query.next();\r
796                 return retVal;\r
797         }\r
798         // Does a note exist?\r
799         public boolean isNoteExpunged(String guid) {\r
800                 if (guid == null)\r
801                         return false;\r
802                 if (guid.trim().equals(""))\r
803                         return false;\r
804                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
805                 query.prepare("Select isExpunged from note where guid=:guid and isExpunged = true");\r
806                 query.bindValue(":guid", guid);\r
807                 if (!query.exec())\r
808                         logger.log(logger.EXTREME, "note.isNoteExpunged SQL retrieve has failed.");\r
809                 boolean retVal = query.next();\r
810                 return retVal;\r
811         }\r
812         // This is a convience method to check if a note exists & update/create based upon it\r
813         public void syncNote(Note note) {\r
814                 // If we got the note from Evernote we use its \r
815                 // metadata instead of the local copy.\r
816                 NoteMetadata meta = null;\r
817                 if (note.getAttributes() != null && note.getAttributes().getSourceApplication() != null) {\r
818                         meta = extractMetadata(note.getAttributes().getSourceApplication());\r
819                 } else \r
820                         meta = getNoteMetaInformation(note.getGuid());\r
821                 \r
822                 // Now, if the note exists we simply update it.  Otherwise we\r
823                 // add a new note.\r
824                 if (exists(note.getGuid())) {\r
825                         updateNote(note);\r
826                 }\r
827                 else\r
828                         addNote(note, false);\r
829                 \r
830                 // If we have metadata, we write it out.\r
831                 if (meta != null) {\r
832                         meta.setGuid(note.getGuid());\r
833                         updateNoteMetadata(meta);\r
834                 }\r
835         }\r
836         // Get a list of notes that need to be updated\r
837         public List <Note> getDirty() {\r
838                 String guid;\r
839                 Note tempNote;\r
840                 List<Note> notes = new ArrayList<Note>();\r
841                 List<String> index = new ArrayList<String>();\r
842                 \r
843                 boolean check;                  \r
844         NSqlQuery query = new NSqlQuery(db.getConnection());\r
845                                         \r
846                 check = query.exec("Select guid from Note where isDirty = true and isExpunged = false and notebookGuid not in (select guid from notebook where local = true or linked = true)");\r
847                 if (!check) \r
848                         logger.log(logger.EXTREME, "Note SQL retrieve has failed: " +query.lastError().toString());\r
849                 \r
850                 // Get a list of the notes\r
851                 while (query.next()) {\r
852                         guid = new String();\r
853                         guid = query.valueString(0);\r
854                         index.add(guid); \r
855                 }       \r
856                 \r
857                 // Start getting notes\r
858                 for (int i=0; i<index.size(); i++) {\r
859                         tempNote = getNote(index.get(i), true,true,false,true,true);\r
860                         notes.add(tempNote);\r
861                 }\r
862                 return notes;   \r
863         }\r
864         // Get a list of notes that need to be updated\r
865         public List <Note> getDirtyLinkedNotes() {\r
866                 String guid;\r
867                 Note tempNote;\r
868                 List<Note> notes = new ArrayList<Note>();\r
869                 List<String> index = new ArrayList<String>();\r
870                 \r
871                 boolean check;                  \r
872         NSqlQuery query = new NSqlQuery(db.getConnection());\r
873                                         \r
874                 check = query.exec("Select guid from Note where isDirty = true and isExpunged = false and notebookGuid in (select guid from notebook where linked = true)");\r
875                 if (!check) \r
876                         logger.log(logger.EXTREME, "Note SQL retrieve has failed: " +query.lastError().toString());\r
877                 \r
878                 // Get a list of the notes\r
879                 while (query.next()) {\r
880                         guid = new String();\r
881                         guid = query.valueString(0);\r
882                         index.add(guid); \r
883                 }       \r
884                 \r
885                 // Start getting notes\r
886                 for (int i=0; i<index.size(); i++) {\r
887                         tempNote = getNote(index.get(i), true,true,false,true,true);\r
888                         notes.add(tempNote);\r
889                 }\r
890                 return notes;   \r
891         }\r
892         // Get a list of notes that need to be updated\r
893         public List <Note> getDirtyLinked(String notebookGuid) {\r
894                 String guid;\r
895                 Note tempNote;\r
896                 List<Note> notes = new ArrayList<Note>();\r
897                 List<String> index = new ArrayList<String>();\r
898                 \r
899                 boolean check;                  \r
900         NSqlQuery query = new NSqlQuery(db.getConnection());\r
901                                         \r
902                 query.prepare("Select guid from Note where isDirty = true and isExpunged = false and notebookGuid=:notebookGuid");\r
903                 query.bindValue(":notebookGuid", notebookGuid);\r
904                 check = query.exec();\r
905                 if (!check) \r
906                         logger.log(logger.EXTREME, "Note SQL retrieve has failed getting dirty linked notes: " +query.lastError().toString());\r
907                 \r
908                 // Get a list of the notes\r
909                 while (query.next()) {\r
910                         guid = new String();\r
911                         guid = query.valueString(0);\r
912                         index.add(guid); \r
913                 }       \r
914                 \r
915                 // Start getting notes\r
916                 for (int i=0; i<index.size(); i++) {\r
917                         tempNote = getNote(index.get(i), true,true,false,true,true);\r
918                         notes.add(tempNote);\r
919                 }\r
920                 return notes;   \r
921         }\r
922         // Get a list of notes that need to be updated\r
923         public List <String> getNotesByNotebook(String notebookGuid) {\r
924                 List<String> notes = new ArrayList<String>();\r
925                 List<String> index = new ArrayList<String>();\r
926                 \r
927                 boolean check;                  \r
928         NSqlQuery query = new NSqlQuery(db.getConnection());\r
929                                         \r
930                 check = query.prepare("Select guid from Note where notebookguid=:notebookguid");\r
931                 if (!check) \r
932                         logger.log(logger.EXTREME, "Note SQL retrieve has failed: " +query.lastError().toString());\r
933                 query.bindValue(":notebookguid", notebookGuid);\r
934                 query. exec();\r
935                 \r
936                 // Get a list of the notes\r
937                 while (query.next()) {\r
938                         index.add(query.valueString(0)); \r
939                 }       \r
940                 \r
941                 return notes;   \r
942         }\r
943         // Get a list of notes that need to be updated\r
944         public boolean isNoteDirty(String guid) {\r
945                 \r
946                 boolean check;                  \r
947         NSqlQuery query = new NSqlQuery(db.getConnection());\r
948                                         \r
949                 check = query.prepare("Select guid from Note where isDirty = true and guid=:guid");\r
950                 query.bindValue(":guid", guid);\r
951                 check = query.exec();\r
952                 if (!check) \r
953                         logger.log(logger.EXTREME, "Note SQL retrieve has failed: " +query.lastError().toString());\r
954                 \r
955                 boolean returnValue;\r
956                 // Get a list of the notes\r
957                 if (query.next()) \r
958                         returnValue = true; \r
959                 else\r
960                         returnValue = false;\r
961 \r
962                 return returnValue;     \r
963         }\r
964 \r
965         // Reset the dirty bit\r
966         public void  resetDirtyFlag(String guid) {\r
967                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
968                 \r
969                 query.prepare("Update note set isdirty=false where guid=:guid");\r
970                 query.bindValue(":guid", guid);\r
971                 if (!query.exec())\r
972                         logger.log(logger.EXTREME, "Error resetting note dirty field.");\r
973         }\r
974         // Get all notes\r
975         public List<String> getAllGuids() {\r
976                 List<String> notes = new ArrayList<String>();\r
977                 \r
978                 boolean check;                                  \r
979         NSqlQuery query = new NSqlQuery(db.getConnection());\r
980                                         \r
981                 check = query.exec("Select guid from Note");\r
982                 if (!check)\r
983                         logger.log(logger.EXTREME, "Notebook SQL retrieve has failed: "+query.lastError());\r
984 \r
985                 // Get a list of the notes\r
986                 while (query.next()) {\r
987                         notes.add(new String(query.valueString(0))); \r
988                 }\r
989                 return notes;\r
990         }\r
991         // Get all notes\r
992         public List<Note> getAllNotes() {\r
993                 List<Note> notes = new ArrayList<Note>();\r
994                 prepareQueries();\r
995                 boolean check;  \r
996                 if (getAllQueryWithoutContent == null) \r
997                         prepareQueries();\r
998         NSqlQuery query = getAllQueryWithoutContent;\r
999                 check = query.exec();\r
1000                 if (!check)\r
1001                         logger.log(logger.EXTREME, "Notebook SQL retrieve has failed: "+query.lastError());\r
1002                 // Get a list of the notes\r
1003                 while (query.next()) {\r
1004                         notes.add(mapNoteFromQuery(query, false, false, false, false, true));\r
1005                 }\r
1006                 return notes;\r
1007         }\r
1008         // Count unindexed notes\r
1009         public int getUnindexedCount() {\r
1010         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1011                 query.exec("select count(*) from note where indexneeded=true and isExpunged = false");\r
1012                 query.next(); \r
1013                 int returnValue = new Integer(query.valueString(0));\r
1014                 return returnValue;\r
1015         }\r
1016         // Count unsynchronized notes\r
1017         public int getDirtyCount() {\r
1018         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1019                 query.exec("select count(guid) from note where isDirty=true and isExpunged = false");\r
1020                 query.next(); \r
1021                 int returnValue = new Integer(query.valueString(0));\r
1022                 return returnValue;\r
1023         }\r
1024         // Count notes\r
1025         public int getNoteCount() {\r
1026         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1027                 query.exec("select count(*) from note where isExpunged = false");\r
1028                 query.next(); \r
1029                 int returnValue = new Integer(query.valueString(0));\r
1030                 return returnValue;\r
1031         }\r
1032         // Count deleted notes\r
1033         public int getDeletedCount() {\r
1034         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1035                 query.exec("select count(*) from note where isExpunged = false and active = false");\r
1036                 if (!query.next()) \r
1037                         return 0;\r
1038                 int returnValue = new Integer(query.valueString(0));\r
1039                 return returnValue;\r
1040         }\r
1041         // Reset a note sequence number to zero.  This is useful for moving conflicting notes\r
1042         public void resetNoteSequence(String guid) {\r
1043                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
1044                 boolean check = query.prepare("Update Note set updateSequenceNumber=0, isDirty=true where guid=:guid");\r
1045                 if (!check) {\r
1046                         logger.log(logger.EXTREME, "Update note ResetSequence sql prepare has failed.");\r
1047                         logger.log(logger.MEDIUM, query.lastError());\r
1048                 }\r
1049                 query.bindValue(":guid", guid);\r
1050                 check = query.exec();\r
1051                 if (!check) {\r
1052                         logger.log(logger.EXTREME, "Update note sequence number has failed.");\r
1053                         logger.log(logger.MEDIUM, query.lastError());\r
1054                 }\r
1055         }\r
1056         \r
1057         \r
1058         // Update a note resource by the hash\r
1059         public void updateNoteResourceGuidbyHash(String noteGuid, String resGuid, String hash) {\r
1060                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
1061 /*              query.prepare("Select guid from NoteResources where noteGuid=:noteGuid and datahash=:hex");\r
1062                 query.bindValue(":noteGuid", noteGuid);\r
1063                 query.bindValue(":hex", hash);\r
1064                 query.exec();\r
1065                 if (!query.next()) {\r
1066                         logger.log(logger.LOW, "Error finding note resource in RNoteTable.updateNoteResourceGuidbyHash.  GUID="+noteGuid +" resGuid="+ resGuid+" hash="+hash);\r
1067                         return;\r
1068                 }\r
1069                 String guid = query.valueString(0);\r
1070 */              \r
1071                 query.prepare("update noteresources set guid=:guid where noteGuid=:noteGuid and datahash=:hex");\r
1072                 query.bindValue(":guid", resGuid);\r
1073                 query.bindValue(":noteGuid", noteGuid);\r
1074                 query.bindValue(":hex", hash);\r
1075                 if (!query.exec()) {\r
1076                         logger.log(logger.EXTREME, "Note Resource Update by Hash failed");\r
1077                         logger.log(logger.EXTREME, query.lastError().toString());\r
1078                 }\r
1079         }\r
1080 \r
1081         // Fix CRLF problem that is on some notes\r
1082         private String fixCarriageReturn(String note) {\r
1083                 if (note == null || !Global.enableCarriageReturnFix)\r
1084                         return note;\r
1085                 QByteArray a0Hex = new QByteArray("a0");\r
1086                 String a0 = QByteArray.fromHex(a0Hex).toString();\r
1087                 note = note.replace("<div>"+a0+"</div>", "<div>&nbsp;</div>");\r
1088                 return note.replace("<div/>", "<div>&nbsp;</div>");\r
1089         }\r
1090         \r
1091         // Expunge notes that we don't want to synchronize\r
1092         public List<String> expungeIgnoreSynchronizedNotes(List<String> notebooks, List<String>tags, List<String> linked) {\r
1093                 \r
1094                 List<String> noteGuids = new ArrayList<String>();\r
1095                 for (int i=0; i<notebooks.size(); i++) {\r
1096                         List<String> notes = findNotesByNotebook(notebooks.get(i));\r
1097                         for (int j=0; j<notes.size(); j++) {\r
1098                                 if (!isNoteDirty(notes.get(j))) {\r
1099                                         expungeNote(notes.get(j), true, false);\r
1100                                         noteGuids.add(notes.get(j));\r
1101                                 }\r
1102                         }\r
1103                 }\r
1104                 \r
1105                 for (int i=0; i<tags.size(); i++) {\r
1106                         List<String> notes = findNotesByTag(tags.get(i));\r
1107                         for (int j=0; j<notes.size(); j++) {\r
1108                                 if (!isNoteDirty(notes.get(j))) {\r
1109                                         expungeNote(notes.get(j), true, false);\r
1110                                         noteGuids.add(notes.get(j));\r
1111                                 }\r
1112                         }\r
1113                 }\r
1114                 \r
1115                 for (int i=0; i<linked.size(); i++) {\r
1116                         String notebookGuid = db.getLinkedNotebookTable().getNotebookGuid(linked.get(i));\r
1117                         if (notebookGuid != null && !notebookGuid.trim().equals("")) {\r
1118                                 List<Tag> linkedTags = db.getTagTable().getTagsForNotebook(notebookGuid);\r
1119                                 for (int j=0; j<linkedTags.size(); j++)\r
1120                                         db.getTagTable().expungeTag(linkedTags.get(j).getGuid(), false);\r
1121                                 \r
1122                                 List<String> notes = findNotesByNotebook(notebookGuid);\r
1123                                 for (int j=0; j<notes.size(); j++) {\r
1124                                         if (!isNoteDirty(notes.get(j))) {\r
1125                                                 expungeNote(notes.get(j), true, false);\r
1126                                                 noteGuids.add(notes.get(j));\r
1127                                         }\r
1128                                 }\r
1129                         }\r
1130                 }\r
1131                 return noteGuids;\r
1132         }\r
1133         \r
1134         // Find a note by its notebook\r
1135         // Expunge notes that we don't want to synchronize\r
1136         public List<String> findNotesByNotebook(String notebook) {\r
1137                 List<String> values = new ArrayList<String>();\r
1138                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
1139                 query.prepare("Select guid from note where notebookguid=:notebook");\r
1140 \r
1141                 query.bindValue(":notebook", notebook);\r
1142                 query.exec();\r
1143                 while (query.next()) {\r
1144                         values.add(query.valueString(0));\r
1145                 }\r
1146                 return values;\r
1147         }\r
1148         \r
1149         public List<String> findNotesByTag(String tag) {\r
1150                 List<String> values = new ArrayList<String>();\r
1151                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
1152                 query.prepare("Select distinct noteguid from notetags where tagguid=:tag");\r
1153 \r
1154                 query.bindValue(":tag", tag);\r
1155                 query.exec();\r
1156                 while (query.next()) {\r
1157                         values.add(query.valueString(0));\r
1158                 }\r
1159                 return values;\r
1160         }\r
1161         \r
1162         // Find a note based upon its title.\r
1163         public List<Pair<String,String>> findNotesByTitle(String text) {\r
1164                 List<Pair<String,String>> results = new ArrayList<Pair<String,String>>();\r
1165                 boolean check;                  \r
1166         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1167                                         \r
1168                 check = query.prepare("Select guid,title from Note where lower(title) like :title");\r
1169                 if (!check) \r
1170                         logger.log(logger.EXTREME, "Note SQL prepare for search by title has failed: " +query.lastError().toString());\r
1171                 \r
1172                 query.bindValue(":title", "%"+text.toLowerCase()+"%");\r
1173                 query.exec();\r
1174                 // Get a list of the notes\r
1175                 while (query.next()) {\r
1176                         Pair<String,String> p = new Pair<String,String>();\r
1177                         p.setFirst(query.valueString(0));\r
1178                         p.setSecond(query.valueString(1));                      \r
1179                         results.add(p); \r
1180                 }       \r
1181                 return results;\r
1182         }\r
1183 \r
1184         \r
1185         \r
1186         //********************************************************************************\r
1187         //********************************************************************************\r
1188         //* Indexing Functions\r
1189         //********************************************************************************\r
1190         //********************************************************************************\r
1191         // set/unset a note to be reindexed\r
1192         public void setIndexNeeded(String guid, Boolean flag) {\r
1193                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
1194                 query.prepare("Update Note set indexNeeded=:flag where guid=:guid");\r
1195 \r
1196                 if (flag)\r
1197                         query.bindValue(":flag", 1);\r
1198                 else\r
1199                         query.bindValue(":flag", 0);\r
1200                 query.bindValue(":guid", guid);\r
1201                 if (!query.exec()) {\r
1202                         logger.log(logger.MEDIUM, "Note indexNeeded update failed.");\r
1203                         logger.log(logger.MEDIUM, query.lastError());\r
1204                 } \r
1205                 List<Resource> r = noteResourceTable.getNoteResources(guid, false);\r
1206                 for (int i=0; r!= null && i<r.size(); i++) {\r
1207                         noteResourceTable.setIndexNeeded(r.get(i).getGuid(), true);\r
1208                 }\r
1209         }\r
1210         // Set all notes to be reindexed\r
1211         public void reindexAllNotes() {\r
1212                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
1213                 if (!query.exec("Update Note set indexNeeded=true")) {\r
1214                         logger.log(logger.MEDIUM, "Note reindexAllNotes update failed.");\r
1215                         logger.log(logger.MEDIUM, query.lastError());\r
1216                 } \r
1217         }\r
1218 \r
1219         // Get all unindexed notes\r
1220         public List <String> getUnindexed() {\r
1221                 String guid;\r
1222                 List<String> index = new ArrayList<String>();\r
1223         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1224                                         \r
1225                 if (!query.exec("Select guid from Note where isExpunged = false and indexNeeded = true and DATEDIFF('MINUTE',updated,CURRENT_TIMESTAMP)>5"))\r
1226                         logger.log(logger.EXTREME, "Note SQL retrieve has failed on getUnindexed().");\r
1227 \r
1228                 // Get a list of the notes\r
1229                 while (query.next()) {\r
1230                         guid = new String();\r
1231                         guid = query.valueString(0);\r
1232                         index.add(guid); \r
1233                 }       \r
1234                 return index;   \r
1235         }\r
1236         public List<String> getNextUnindexed(int limit) {\r
1237                 List<String> guids = new ArrayList<String>();\r
1238                         \r
1239         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1240                                         \r
1241                 if (!query.exec("Select guid from Note where isExpunged = false and indexNeeded = true and DATEDIFF('MINUTE',Updated,CURRENT_TIMESTAMP)>5 limit " +limit))\r
1242                         logger.log(logger.EXTREME, "Note SQL retrieve has failed on getUnindexed().");\r
1243                 \r
1244                 // Get a list of the notes\r
1245                 String guid;\r
1246                 while (query.next()) {\r
1247                         guid = new String();\r
1248                         guid = query.valueString(0);\r
1249                         guids.add(guid);\r
1250                 }       \r
1251                 return guids;   \r
1252         }\r
1253 \r
1254         \r
1255         // Get note meta information\r
1256         public void updateNoteMetadata(NoteMetadata meta) {\r
1257         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1258                 if (!query.prepare("Update Note set titleColor=:color, pinned=:pinned, attributeSourceApplication=:metaString where guid=:guid"))\r
1259                         logger.log(logger.EXTREME, "Note SQL prepare has failed on updateNoteMetadata.");\r
1260                 query.bindValue(":color", meta.getColor());\r
1261                 query.bindValue(":pinned", meta.isPinned());\r
1262                 query.bindValue(":guid", meta.getGuid());\r
1263                 query.bindValue(":metaString", buildMetadataString(meta));\r
1264                 if (!query.exec()) \r
1265                         logger.log(logger.EXTREME, "Note SQL exec has failed on updateNoteMetadata.");\r
1266                 return;\r
1267         }\r
1268         \r
1269         // Get all note meta information\r
1270         public HashMap<String, NoteMetadata> getNotesMetaInformation() {\r
1271                 HashMap<String, NoteMetadata> returnValue = new HashMap<String, NoteMetadata>();\r
1272         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1273                 \r
1274                 if (!query.exec("Select guid,titleColor, isDirty, pinned from Note"))\r
1275                         logger.log(logger.EXTREME, "Note SQL retrieve has failed on getNoteMetaInformation.");\r
1276 \r
1277                 // Get a list of the notes\r
1278                 while (query.next()) {\r
1279                         NoteMetadata note = new NoteMetadata();\r
1280                         note.setGuid(query.valueString(0));\r
1281                         note.setColor(query.valueInteger(1));\r
1282                         note.setDirty(query.valueBoolean(2, false));\r
1283                         int pinned = query.valueInteger(3);\r
1284                         if (pinned > 0) \r
1285                                 note.setPinned(true);\r
1286                         returnValue.put(note.getGuid(), note); \r
1287                 }       \r
1288 \r
1289                 return returnValue;\r
1290         }\r
1291         // Get note meta information\r
1292         public NoteMetadata getNoteMetaInformation(String guid) {\r
1293         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1294                 \r
1295                 if (!query.prepare("Select guid,titleColor, isDirty, pinned from Note where guid=:guid")) {\r
1296                         logger.log(logger.EXTREME, "Note SQL retrieve has failed on getNoteMetaInformation.");\r
1297                         return null;\r
1298                 }\r
1299                 query.bindValue(":guid", guid);\r
1300                 query.exec();\r
1301 \r
1302                 // Get a list of the notes\r
1303                 while (query.next()) {\r
1304                         NoteMetadata note = new NoteMetadata();\r
1305                         note.setGuid(query.valueString(0));\r
1306                         note.setColor(query.valueInteger(1));\r
1307                         note.setDirty(query.valueBoolean(2, false));\r
1308                         int pinned = query.valueInteger(3);\r
1309                         if (pinned > 0) \r
1310                                 note.setPinned(true);\r
1311                         return note;\r
1312                 }       \r
1313 \r
1314                 return null;\r
1315         }\r
1316         \r
1317         \r
1318         //**********************************************************************************\r
1319         //* Thumbnail functions\r
1320         //**********************************************************************************\r
1321         // Set if a new thumbnail is needed\r
1322         public void setThumbnailNeeded(String guid, boolean needed) {\r
1323                 \r
1324                 boolean check;                  \r
1325         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1326                                         \r
1327                 check = query.prepare("Update note set thumbnailneeded = :needed where guid=:guid");\r
1328                 query.bindValue(":guid", guid);\r
1329                 query.bindValue(":needed", needed);\r
1330                 check = query.exec();\r
1331                 if (!check) \r
1332                         logger.log(logger.EXTREME, "Note SQL set thumbail needed failed: " +query.lastError().toString());\r
1333 \r
1334         }\r
1335         // Is a thumbail needed for this guid?\r
1336         public boolean isThumbnailNeeded(String guid) {\r
1337                 \r
1338                 boolean check;                  \r
1339         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1340                                         \r
1341                 check = query.prepare("select thumbnailneeded from note where guid=:guid");\r
1342                 query.bindValue(":guid", guid);\r
1343                 check = query.exec();\r
1344                 if (!check) \r
1345                         logger.log(logger.EXTREME, "Note SQL isThumbnailNeeded query failed: " +query.lastError().toString());\r
1346                 \r
1347                 boolean returnValue;\r
1348                 // Get a list of the notes\r
1349                 if (query.next()) \r
1350                         returnValue = query.valueBoolean(0, false); \r
1351                 else\r
1352                         returnValue = false;\r
1353 \r
1354                 return returnValue;     \r
1355         }\r
1356         // Set if a new thumbnail is needed\r
1357         public void setThumbnail(String guid, QByteArray thumbnail) {\r
1358                 \r
1359                 boolean check;                  \r
1360         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1361                                         \r
1362                 check = query.prepare("Update note set thumbnail = :thumbnail where guid=:guid");\r
1363                 query.bindValue(":guid", guid);\r
1364                 query.bindValue(":thumbnail", thumbnail.toByteArray());\r
1365                 check = query.exec();\r
1366                 if (!check) \r
1367                         logger.log(logger.EXTREME, "Note SQL set thumbail failed: " +query.lastError().toString());\r
1368 \r
1369         }\r
1370         // Set if a new thumbnail is needed\r
1371         public QByteArray getThumbnail(String guid) {\r
1372                 \r
1373                 boolean check;                  \r
1374         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1375                                         \r
1376                 check = query.prepare("Select thumbnail from note where guid=:guid");\r
1377                 query.bindValue(":guid", guid);\r
1378                 check = query.exec();\r
1379                 if (!check) \r
1380                         logger.log(logger.EXTREME, "Note SQL get thumbail failed: " +query.lastError().toString());\r
1381                 // Get a list of the notes\r
1382                 if (query.next())  {\r
1383                         try {\r
1384                                 if (query.getBlob(0) != null) {\r
1385                                         return new QByteArray(query.getBlob(0)); \r
1386                                 }\r
1387                         } catch (java.lang.IllegalArgumentException e) {\r
1388                                 return null;\r
1389                         }\r
1390                 }\r
1391                 return null;\r
1392         }\r
1393         // Get all thumbnails\r
1394         public HashMap<String, QPixmap> getThumbnails() {\r
1395                 boolean check;                  \r
1396         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1397         HashMap<String, QPixmap> map = new HashMap<String,QPixmap>();\r
1398                                         \r
1399                 check = query.prepare("Select guid,thumbnail from note where thumbnailneeded=false and isExpunged=false");\r
1400                 check = query.exec();\r
1401                 if (!check) \r
1402                         logger.log(logger.EXTREME, "Note SQL get thumbail failed: " +query.lastError().toString());\r
1403                 // Get a list of the notes\r
1404                 while (query.next())  {\r
1405                         try {\r
1406                                 if (query.getBlob(1) != null) {\r
1407                                         QByteArray data = new QByteArray(query.getBlob(1));\r
1408                                         QPixmap img = new QPixmap();\r
1409                                         if (img.loadFromData(data)) {\r
1410                                                 img = img.scaled(Global.largeThumbnailSize);\r
1411                                                 map.put(query.valueString(0), img);\r
1412                                         }\r
1413                                 }       \r
1414                         } catch (java.lang.IllegalArgumentException e) {\r
1415                                 logger.log(logger.HIGH, "Error retrieving thumbnail " +e.getMessage());\r
1416                         }\r
1417                 }\r
1418                 return map;\r
1419         }\r
1420         // Get a list of notes that need thumbnails\r
1421         public List<String> findThumbnailsNeeded() {\r
1422                 \r
1423                 boolean check;\r
1424         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1425                                         \r
1426                 check = query.prepare("select guid from note where thumbnailneeded=true and isExpunged=false and DATEDIFF('MINUTE',updated,CURRENT_TIMESTAMP)>5 limit 5");\r
1427                 check = query.exec();\r
1428                 if (!check) \r
1429                         logger.log(logger.EXTREME, "Note SQL findThumbnailsNeeded query failed: " +query.lastError().toString());\r
1430                 \r
1431 \r
1432                 // Get a list of the notes\r
1433                 List<String> values = new ArrayList<String>();\r
1434                 while (query.next()) {\r
1435                         values.add(query.valueString(0)); \r
1436                 }\r
1437 \r
1438                 return values;  \r
1439         }\r
1440         // Get a count of thumbnails needed\r
1441         public int getThumbnailNeededCount() {\r
1442                 \r
1443                 boolean check;\r
1444         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1445                                         \r
1446                 check = query.prepare("select count(guid) from note where thumbnailneeded=true and isExpunged=false and DATEDIFF('MINUTE',updated,CURRENT_TIMESTAMP)>5 limit 2");\r
1447                 check = query.exec();\r
1448                 if (!check) \r
1449                         logger.log(logger.EXTREME, "Note SQL findThumbnailNeededCount query failed: " +query.lastError().toString());\r
1450                 \r
1451                 if (query.next()) {\r
1452                         return query.valueInteger(0); \r
1453                 }\r
1454 \r
1455                 return 0;       \r
1456         }\r
1457 \r
1458         //***********************************************************************************\r
1459         public String findAlternateGuid(String guid) {\r
1460                 boolean check;\r
1461         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1462                                         \r
1463                 check = query.prepare("select guid from note where original_guid=:guid");\r
1464                 query.bindValue(":guid", guid);\r
1465                 check = query.exec();\r
1466                 if (!check) \r
1467                         logger.log(logger.EXTREME, "Note SQL findAlternateguid query failed: " +query.lastError().toString());\r
1468                 \r
1469                 if (query.next()) {\r
1470                         return query.valueString(0); \r
1471                 }\r
1472 \r
1473                 return null;    \r
1474         }\r
1475         \r
1476         //* Check if a note guid exists\r
1477         public boolean guidExists(String guid) {\r
1478                 boolean check;\r
1479         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1480                                         \r
1481                 check = query.prepare("select guid from note where guid=:guid");\r
1482                 query.bindValue(":guid", guid);\r
1483                 check = query.exec();\r
1484                 if (!check) \r
1485                         logger.log(logger.EXTREME, "Note SQL guidExists query failed: " +query.lastError().toString());\r
1486                 \r
1487                 if (query.next()) {\r
1488                         return true; \r
1489                 }\r
1490 \r
1491                 return false;                   \r
1492         }\r
1493         \r
1494         // Update a note content's hash.  This happens if a resource is edited outside of NN\r
1495         public void updateResourceContentHash(String guid, String oldHash, String newHash) {\r
1496                 Note n = getNote(guid, true, false, false, false,false);\r
1497                 int position = n.getContent().indexOf("<en-media");\r
1498                 int endPos;\r
1499                 for (;position>-1;) {\r
1500                         endPos = n.getContent().indexOf(">", position+1);\r
1501                         String oldSegment = n.getContent().substring(position,endPos);\r
1502                         int hashPos = oldSegment.indexOf("hash=\"");\r
1503                         int hashEnd = oldSegment.indexOf("\"", hashPos+7);\r
1504                         String hash = oldSegment.substring(hashPos+6, hashEnd);\r
1505                         if (hash.equalsIgnoreCase(oldHash)) {\r
1506                                 String newSegment = oldSegment.replace(oldHash, newHash);\r
1507                                 String content = n.getContent().substring(0,position) +\r
1508                                                  newSegment +\r
1509                                                  n.getContent().substring(endPos);\r
1510                                 NSqlQuery query = new NSqlQuery(db.getConnection());\r
1511                                 query.prepare("update note set isdirty=true, thumbnailneeded=true, content=:content where guid=:guid");\r
1512                                 query.bindValue(":content", content);\r
1513                                 query.bindValue(":guid", n.getGuid());\r
1514                                 query.exec();\r
1515                         }\r
1516                         \r
1517                         position = n.getContent().indexOf("<en-media", position+1);\r
1518                 }\r
1519         }\r
1520 \r
1521         // Extract metadata from a note's Note.attributes.sourceApplication\r
1522         private NoteMetadata extractMetadata(String sourceApplication) {\r
1523                 String consumerKey = "baumgarte:{";\r
1524                 int startPos = sourceApplication.indexOf(consumerKey);\r
1525                 if (startPos < 0 )\r
1526                                 return null;\r
1527                 \r
1528                 NoteMetadata meta = new NoteMetadata();\r
1529                 startPos = startPos+consumerKey.length();\r
1530                 \r
1531 //              String startString = sourceApplication.substring(0,startPos);\r
1532                 String metaString = sourceApplication.substring(startPos);\r
1533 //              String endString = metaString.substring(metaString.indexOf("};"));\r
1534                 int endPos = metaString.indexOf("};");\r
1535                 if (endPos > 0)\r
1536                         metaString = metaString.substring(0,endPos);\r
1537                 \r
1538                 String value = parseMetaString(metaString, "titleColor");\r
1539                 if (value != null)\r
1540                         meta.setColor(Integer.parseInt(value));\r
1541                 \r
1542                 value = parseMetaString(metaString, "pinned");\r
1543                 if (value != null && value.equals(true))\r
1544                         meta.setPinned(true);\r
1545                                 \r
1546                 return meta;\r
1547         }\r
1548         \r
1549         // Given a metadata string from attribute.sourceApplication, we\r
1550         // extract the information for a given key.\r
1551         private String parseMetaString(String metaString, String key) {\r
1552                 int startPos = metaString.indexOf(key);\r
1553                 if (startPos < 0)\r
1554                         return null;\r
1555                 \r
1556                 String value = metaString.substring(startPos+key.length()+1);\r
1557                 int endPos = value.indexOf(";");\r
1558                 if (endPos > 0)\r
1559                         value = value.substring(0,endPos);\r
1560                 \r
1561                 return value;\r
1562         }\r
1563         \r
1564         // Given a set of metadata, we build a string that can be inserted\r
1565         // into the attribute.sourceApplication string.\r
1566         private String buildMetadataString(NoteMetadata meta) {\r
1567                 StringBuffer value = new StringBuffer(removeExistingMetaString(meta.getGuid()));\r
1568                 StringBuffer metaString = new StringBuffer();\r
1569                 \r
1570                 if (meta.isPinned()) {\r
1571                         metaString.append("pinned=true;");\r
1572                 }\r
1573                 if (meta.getColor() != -1) {\r
1574                         metaString.append("titleColor=" +new Integer(meta.getColor()).toString()+";");\r
1575                 }\r
1576                 if (metaString.length()>0) {\r
1577                         \r
1578                         // Adda any missing ";" or " " at the end of the existing \r
1579                         // string.\r
1580                         if (value.length()>1 && (!value.toString().trim().endsWith(";") || !value.toString().trim().endsWith(";")))   \r
1581                                 value.append("; ");\r
1582                         \r
1583                         value.append("baumgarte:{");\r
1584                         value.append(metaString);\r
1585                         value.append("};");\r
1586                         return value.toString();\r
1587                 }\r
1588                 return null;\r
1589         }\r
1590 \r
1591         // This will remove the existing metadata string from the attribute.sourceApplication string.\r
1592         private String removeExistingMetaString(String guid) {\r
1593         NSqlQuery query = new NSqlQuery(db.getConnection());\r
1594                 \r
1595                 if (!query.prepare("Select attributeSourceApplication from Note where guid=:guid")) {\r
1596                         logger.log(logger.EXTREME, "Note SQL retrieve has failed in removeExistingMetaString.");\r
1597                         return null;\r
1598                 }\r
1599                 query.bindValue(":guid", guid);\r
1600                 query.exec();\r
1601 \r
1602                 // Get the application source string\r
1603                 String sourceApplication = null;\r
1604                 while (query.next()) {\r
1605                         sourceApplication = query.valueString(0);\r
1606                 }\r
1607                 if (sourceApplication == null) \r
1608                         return "";\r
1609                 \r
1610                 String consumerKey = "baumgarte:{";\r
1611                 int startPos = sourceApplication.indexOf(consumerKey);\r
1612                 if (startPos < 0 )\r
1613                                 return sourceApplication;\r
1614                 String startString = sourceApplication.substring(0,startPos);\r
1615                 String metaString = sourceApplication.substring(startPos);\r
1616                 String endString = metaString.substring(metaString.indexOf("};")+2);\r
1617 \r
1618                 return startString+endString;\r
1619         }\r
1620 \r
1621 }       \r
1622 \r
1623 \r
1624 \r
1625 \r