OSDN Git Service

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