OSDN Git Service

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