OSDN Git Service

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