OSDN Git Service

Added LaTex image insert & edit
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / sql / NoteResourceTable.java
1 /*\r
2  * This file is part of NeverNote \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 import java.text.SimpleDateFormat;\r
23 import java.util.ArrayList;\r
24 import java.util.List;\r
25 \r
26 import com.evernote.edam.type.Data;\r
27 import com.evernote.edam.type.Resource;\r
28 import com.evernote.edam.type.ResourceAttributes;\r
29 import com.trolltech.qt.core.QByteArray;\r
30 \r
31 import cx.fbn.nevernote.sql.driver.NSqlQuery;\r
32 import cx.fbn.nevernote.utilities.ApplicationLogger;\r
33 \r
34 \r
35 \r
36 public class NoteResourceTable  {\r
37         /**\r
38          * \r
39          */\r
40         private static final long serialVersionUID = 1L;\r
41         private final ApplicationLogger                 logger;\r
42         private final DatabaseConnection                db;     \r
43         \r
44         // Constructor\r
45         public NoteResourceTable(ApplicationLogger l, DatabaseConnection d) {\r
46                 logger = l;\r
47                 db = d;\r
48         }\r
49         // Create the table\r
50         public void createTable() {\r
51                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
52         // Create the NoteResource table\r
53         logger.log(logger.HIGH, "Creating table NoteResource...");\r
54         if (!query.exec("Create table NoteResources (guid varchar primary key, " +\r
55                         "noteGuid varchar, updateSequenceNumber integer, dataHash varchar, "+\r
56                         "dataSize integer, dataBinary blob, "+\r
57                         "mime varchar, width integer, height integer, duration integer, "+\r
58                         "active integer, recognitionHash varchar, recognitionSize integer, " +\r
59                         "recognitionBinary varchar, attributeSourceUrl varchar, attributeTimestamp timestamp, " +\r
60                         "attributeLatitude double, attributeLongitude double, "+\r
61                         "attributeAltitude double, attributeCameraMake varchar, attributeCameraModel varchar, "\r
62                         +"attributeClientWillIndex varchar, attributeRecoType varchar, attributeFileName varchar,"+\r
63                         "attributeAttachment boolean, isDirty boolean, indexNeeded boolean)"))\r
64                 logger.log(logger.HIGH, "Table NoteResource creation FAILED!!!"); \r
65         if (!query.exec("CREATE INDEX unindexed_resources on noteresources (indexneeded desc, guid);"))\r
66                 logger.log(logger.HIGH, "Noteresources unindexed_resources index creation FAILED!!!");\r
67         if (!query.exec("CREATE INDEX resources_dataheshhex on noteresources (datahash, guid);"))\r
68                 logger.log(logger.HIGH, "Noteresources resources_datahash index creation FAILED!!!");  \r
69         if (!query.exec("create index RESOURCES_GUID_INDEX on noteresources (noteGuid, guid);"))\r
70                 logger.log(logger.HIGH, "Noteresources resources_datahash index creation FAILED!!!");  \r
71         }\r
72         // Drop the table\r
73         public void dropTable() {               \r
74                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
75                 query.exec("Drop table NoteResources");\r
76         }\r
77         // Reset the dirty flag\r
78         public void  resetDirtyFlag(String guid) {\r
79                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
80                 \r
81                 query.prepare("Update noteresources set isdirty=false where guid=:guid");\r
82                 query.bindValue(":guid", guid);\r
83                 if (!query.exec())\r
84                         logger.log(logger.EXTREME, "Error resetting noteresource dirty field. " +query.lastError());\r
85                 else\r
86                         query.exec("commit");\r
87         }\r
88         // Set if the resource should be indexed\r
89         public void  setIndexNeeded(String guid, Boolean indexNeeded) {\r
90                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());            \r
91                 query.prepare("Update noteresources set indexNeeded=:needed where guid=:guid");\r
92                 query.bindValue(":needed", indexNeeded);\r
93                 query.bindValue(":guid", guid);\r
94                 if (!query.exec())\r
95                         logger.log(logger.EXTREME, "Error setting noteresource indexneeded field: " +query.lastError());\r
96                 else\r
97                         query.exec("commit");\r
98         }\r
99         // get any unindexed resource\r
100         public List<String> getNextUnindexed(int limit) {\r
101                 List<String> guids = new ArrayList<String>();\r
102         NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
103                                         \r
104                 if (!query.exec("Select guid from NoteResources where indexNeeded = true limit " +limit))\r
105                         logger.log(logger.EXTREME, "NoteResources SQL retrieve has failed on getNextUnindexed(): " +query.lastError());\r
106 \r
107                 // Get a list of the notes\r
108                 String guid;\r
109                 while (query.next()) {\r
110                         guid = new String();\r
111                         guid = query.valueString(0);\r
112                         guids.add(guid);\r
113                 }       \r
114                 return guids;   \r
115         }\r
116         // get any unindexed resource\r
117         public List<String> getUnindexed() {\r
118                 List<String> guids = new ArrayList<String>();\r
119         NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
120                                         \r
121                 if (!query.exec("Select guid from NoteResources where indexNeeded = true"))\r
122                         logger.log(logger.EXTREME, "NoteResources SQL retrieve has failed on getUnindexed(): " +query.lastError());\r
123 \r
124                 // Get a list of the notes\r
125                 String guid;\r
126                 while (query.next()) {\r
127                         guid = new String();\r
128                         guid = query.valueString(0);\r
129                         guids.add(guid);\r
130                 }       \r
131                 return guids;   \r
132         }\r
133 \r
134         public List<String> getAll() {\r
135                 List<String> guids = new ArrayList<String>();\r
136                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
137                 \r
138                 query.prepare("Select guid from noteresources;");\r
139                 if (!query.exec())\r
140                         logger.log(logger.EXTREME, "Error getting all note resource guids. " +query.lastError());\r
141                 \r
142                 while (query.next()) {\r
143                         guids.add(query.valueString(0));\r
144                 }\r
145                 return guids;\r
146         }\r
147         \r
148         public List<String> findInkNotes() {\r
149                 List<String> guids = new ArrayList<String>();\r
150                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
151                 \r
152                 query.prepare("Select guid from noteresources where mime='application/vnd.evernote.ink'");\r
153                 if (!query.exec())\r
154                         logger.log(logger.EXTREME, "Error searching for ink notes. " +query.lastError());\r
155                 \r
156                 while (query.next()) {\r
157                         guids.add(query.valueString(0));\r
158                 }\r
159                 return guids;\r
160         }\r
161         \r
162         public void saveNoteResource(Resource r, boolean isDirty) {\r
163                 logger.log(logger.HIGH, "Entering DBRunner.saveNoteResources");\r
164                 boolean check;\r
165                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
166                 SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");\r
167                 \r
168                 check = query.prepare("Insert Into NoteResources ("\r
169                                 +"guid, noteGuid, dataHash, dataSize, dataBinary, updateSequenceNumber, "\r
170                                 +"mime, width, height, duration, active, recognitionHash, "                             \r
171                                 +"recognitionSize, recognitionBinary, attributeSourceUrl, attributeTimestamp, "\r
172                                 +"attributeLatitude, attributeLongitude, attributeAltitude, attributeCameraMake, "\r
173                                 +"attributeCameraModel, "\r
174                                 +"attributeClientWillIndex, attributeRecoType, attributeFileName, attributeAttachment, isDirty, "\r
175                                 +"indexNeeded) Values("\r
176                                 +":guid, :noteGuid, :dataHash,:dataSize, :dataBody, :updateSequenceNumber, "\r
177                                 +":mime, :width, :height, :duration, :active, :recognitionHash, "                               \r
178                                 +":recognitionSize, :recognitionBody, :attributeSourceUrl, :attributeTimestamp, "\r
179                                 +":attributeLatitude, :attributeLongitude, :attributeAltitude, :attributeCameraMake, "\r
180                                 +":attributeCameraModel, "\r
181                                 +":attributeClientWillIndex, :attributeRecoType, :attributeFileName, :attributeAttachment, "\r
182                                 +":isDirty, true)");\r
183                 if (!check) {\r
184                         logger.log(logger.EXTREME, "NoteResource SQL insert prepare has failed.");\r
185                         logger.log(logger.MEDIUM, query.lastError());\r
186                 }\r
187         \r
188                         query.bindValue(":guid", r.getGuid());\r
189                         query.bindValue(":noteGuid", r.getNoteGuid());\r
190                         if (r.getData() != null) {\r
191 //                              query.bindValue(":dataHash", new QByteArray(r.getData().getBodyHash()).toHex());\r
192 //                              query.bindValue(":dataHash", "");\r
193                                 query.bindValue(":dataHash", byteArrayToHexString(r.getData().getBodyHash()));\r
194                                 query.bindValue(":dataSize", r.getData().getSize());\r
195                                 query.bindBlob(":dataBody", r.getData().getBody());\r
196                         }\r
197                         query.bindValue(":updateSequenceNumber", r.getUpdateSequenceNum());\r
198                         query.bindValue(":mime", r.getMime());\r
199                         query.bindValue(":width", new Integer(r.getWidth()));\r
200                         query.bindValue(":height", new Integer(r.getHeight()));\r
201                         query.bindValue(":duration", new Integer(r.getDuration()));\r
202                         query.bindValue(":active", r.isActive());\r
203                         if (r.getRecognition() != null) {\r
204                                 query.bindValue(":recognitionHash", r.getRecognition().getBodyHash());\r
205                                 query.bindValue(":recognitionSize", r.getRecognition().getSize());\r
206                                 if (r.getRecognition().getBody() != null)\r
207                                         query.bindValue(":recognitionBody", new String(r.getRecognition().getBody()));\r
208                                 else\r
209                                         query.bindValue(":recognitionBody", "");\r
210                         } else {\r
211                                 query.bindValue(":recognitionHash", "");\r
212                                 query.bindValue(":recognitionSize", 0);\r
213                                 query.bindValue(":recognitionBody", "");\r
214                         }\r
215                         if (r.getAttributes() != null) {\r
216                                 query.bindValue(":attributeSourceUrl", r.getAttributes().getSourceURL());\r
217                                 StringBuilder ts = new StringBuilder(simple.format(r.getAttributes().getTimestamp()));\r
218                                 query.bindValue(":attributeTimestamp", ts.toString());\r
219                                 query.bindValue(":attributeLatitude", r.getAttributes().getLatitude());\r
220                                 query.bindValue(":attributeLongitude", r.getAttributes().getLongitude());\r
221                                 query.bindValue(":attributeAltitude", r.getAttributes().getAltitude());\r
222                                 query.bindValue(":attributeCameraMake", r.getAttributes().getCameraMake());\r
223                                 query.bindValue(":attributeCameraModel", r.getAttributes().getCameraModel());\r
224                                 query.bindValue(":attributeClientWillIndex", r.getAttributes().isClientWillIndex());\r
225                                 query.bindValue(":attributeRecoType", r.getAttributes().getRecoType());\r
226                                 query.bindValue(":attributeFileName", r.getAttributes().getFileName());\r
227                                 query.bindValue(":attributeAttachment", r.getAttributes().isAttachment());                      \r
228                         }\r
229                         query.bindValue(":isDirty", isDirty);\r
230                                                 \r
231                         check = query.exec();\r
232                         if (!check) {\r
233                                 logger.log(logger.MEDIUM, "*** NoteResource Table insert failed.");             \r
234                                 logger.log(logger.MEDIUM, query.lastError());\r
235                         } else\r
236                                 query.exec("commit");\r
237                         \r
238                                                 \r
239                         logger.log(logger.HIGH, "Leaving DBRunner.saveNoteResources");\r
240         }\r
241         // delete an old resource\r
242         public void expungeNoteResource(String guid) {\r
243                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
244                 query.prepare("delete from NoteResources where guid=:guid");\r
245                 query.bindValue(":guid", guid);\r
246                 query.exec();\r
247                 query.exec("commit");\r
248                 \r
249                 NSqlQuery query2 = new NSqlQuery(db.getConnection());\r
250                 query2.prepare("Delete from InkImages where guid=:guid");\r
251                 query2.bindValue(":guid", guid);\r
252                 query2.exec();\r
253                 query2.exec("commit");\r
254 \r
255         }\r
256 \r
257         \r
258         // Get a note resource from the database by it's hash value\r
259         public String getNoteResourceGuidByHashHex(String noteGuid, String hash) {\r
260                 logger.log(logger.HIGH, "Entering DBRunner.getNoteResourceGuidByHashHex");\r
261 \r
262                 boolean check;\r
263                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
264                 \r
265                 check = query.prepare("Select guid from NoteResources " +\r
266                                         "where noteGuid=:noteGuid and dataHash=:hash");\r
267                 if (check)\r
268                         logger.log(logger.EXTREME, "NoteResource SQL select prepare was successful.");\r
269                 else {\r
270                         logger.log(logger.EXTREME, "NoteResource SQL select prepare has failed.");\r
271                         logger.log(logger.MEDIUM, query.lastError());\r
272                 }\r
273                 query.bindValue(":noteGuid", noteGuid);\r
274                 query.bindValue(":hash", hash);\r
275         \r
276                 check = query.exec();\r
277                 if (!check)      {\r
278                         logger.log(logger.MEDIUM, "dbRunner.getNoteResourceGuidByHashHex Select failed." +\r
279                                         "Note Guid:" +noteGuid+\r
280                                         "Data Body Hash:" +hash);               \r
281                         logger.log(logger.MEDIUM, query.lastError());\r
282                 }\r
283                 if (!query.next()) {\r
284                         logger.log(logger.MEDIUM, "Note Resource not found.");\r
285                         return null;\r
286                 }\r
287                 return query.valueString(0);\r
288         }\r
289 \r
290         // Get a note resource from the database by it's hash value\r
291         public Resource getNoteResourceDataBodyByHashHex(String noteGuid, String hash) {\r
292                 logger.log(logger.HIGH, "Entering DBRunner.getNoteResourceDataBodyByHash");\r
293 \r
294                 boolean check;\r
295                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
296                 \r
297                 check = query.prepare("Select guid, mime, from NoteResources " +\r
298                                         "where noteGuid=:noteGuid and dataHash=:hash");\r
299                 if (!check) {\r
300                         logger.log(logger.EXTREME, "NoteResource SQL select prepare has failed.");\r
301                         logger.log(logger.MEDIUM, query.lastError());\r
302                 }\r
303                 query.bindValue(":noteGuid", noteGuid);\r
304                 query.bindValue(":hash", hash);\r
305         \r
306                 if (!query.exec()) {\r
307                         logger.log(logger.MEDIUM, "NoteResource Select failed." +\r
308                                         "Note Guid:" +noteGuid+\r
309                                         "Data Body Hash:" +hash);               \r
310                         logger.log(logger.MEDIUM, query.lastError());\r
311                 }\r
312                 if (!query.next()) {\r
313                         logger.log(logger.MEDIUM, "Note Resource not found.");\r
314                         return null;\r
315                 }\r
316                 \r
317                 Resource r = new Resource();\r
318                 r.setGuid(query.valueString(0));\r
319                 r.setMime(query.valueString(1));\r
320                 \r
321                 NSqlQuery binary = new NSqlQuery(db.getResourceConnection());\r
322                 if (!binary.prepare("Select databinary from NoteResources " +\r
323                                         "where guid=:guid")) {\r
324                         logger.log(logger.MEDIUM, "Prepare for NoteResources Binary failed");\r
325                         logger.log(logger.MEDIUM, binary.lastError());\r
326                 }\r
327                 \r
328                 if (!binary.exec()) {\r
329                         logger.log(logger.MEDIUM, "NoteResources Binary Select failed." +\r
330                                         "Note Guid:" +noteGuid+\r
331                                         "Data Body Hash:" +hash);               \r
332                         logger.log(logger.MEDIUM, binary.lastError());\r
333                 }\r
334                 if (!binary.next()) {\r
335                         logger.log(logger.MEDIUM, "Note Resource Binary not found.");\r
336                         return null;\r
337                 }\r
338                 \r
339                 Data d = new Data();\r
340                 r.setData(d);\r
341                 d.setBody(binary.valueString(0).getBytes());\r
342                 logger.log(logger.HIGH, "Leaving DBRunner.getNoteResourceDataBodyByHash");\r
343                 return r;\r
344         }\r
345 \r
346         \r
347         // Get a note's resourcesby Guid\r
348         public Resource getNoteResource(String guid, boolean withBinary) {\r
349                 if (guid == null)\r
350                         return null;\r
351                 \r
352                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
353                 String queryString;\r
354                 queryString = new String("Select guid, noteGuid, mime, width, height, duration, "\r
355                                 +"active, updateSequenceNumber, dataHash, dataSize, "\r
356                                 +"recognitionHash, recognitionSize, "\r
357                                 +"attributeLatitude, attributeLongitude, attributeAltitude, "\r
358                                 +"attributeCameraMake, attributeCameraModel, attributeClientWillIndex, "\r
359                                 +"attributeRecoType, attributeFileName, attributeAttachment, attributeSourceUrl "\r
360                                 +" from NoteResources where guid=:guid");\r
361 \r
362                 \r
363                 query.prepare(queryString);\r
364                 \r
365                 query.bindValue(":guid", guid);\r
366                 if (!query.exec()) {\r
367                         logger.log(logger.EXTREME, "NoteResources SQL select has failed.");\r
368                         logger.log(logger.MEDIUM, query.lastError());\r
369                         return null;\r
370                 }\r
371                 Resource r = null;\r
372                 if (query.next()) {\r
373                                                                         \r
374                         r = new Resource();\r
375                         r.setGuid(query.valueString(0));        // Resource Guid\r
376                         r.setNoteGuid(query.valueString(1));   // note Guid\r
377                         r.setMime(query.valueString(2));       // Mime Type\r
378                         r.setWidth(new Short(query.valueString(3)));  // Width\r
379                         r.setHeight(new Short(query.valueString(4)));  // Height\r
380                         r.setDuration(new Short(query.valueString(5)));  // Duration\r
381                         r.setActive(new Boolean(query.valueString(6)));  // active\r
382                         r.setUpdateSequenceNum(new Integer(query.valueString(7)));  // update sequence number\r
383                         \r
384                         Data d = new Data();\r
385                         byte[] h = query.valueString(8).getBytes();    // data hash\r
386                         QByteArray hData = new QByteArray(h);\r
387                         QByteArray bData = new QByteArray(QByteArray.fromHex(hData));\r
388                         d.setBodyHash(bData.toByteArray());\r
389                         d.setSize(new Integer(query.valueString(9)));\r
390                         r.setData(d);\r
391                         \r
392                         Data rec = new Data();\r
393                         if (query.valueObject(10) != null)\r
394                                 rec.setBodyHash(query.valueString(10).getBytes());   // Recognition Hash\r
395                         if (query.valueObject(11) != null)\r
396                                 rec.setSize(new Integer(query.valueString(11)));\r
397                         else\r
398                                 rec.setSize(0);\r
399                         r.setRecognition(rec);\r
400 \r
401                         ResourceAttributes a = new ResourceAttributes();\r
402                         if (!query.valueString(12).equals(""))              // Latitude\r
403                                 a.setLatitude(new Float(query.valueString(12)));\r
404                         if (!query.valueString(13).equals(""))              // Longitude\r
405                                 a.setLongitude(new Float(query.valueString(13)));\r
406                         if (!query.valueString(14).equals(""))              // Altitude\r
407                                 a.setAltitude(new Float(query.valueString(14)));\r
408                         a.setCameraMake(stringValue(query.valueString(15)));              // Camera Make\r
409                         a.setCameraModel(stringValue(query.valueString(16)));\r
410                         a.setClientWillIndex(booleanValue(query.valueString(17).toString(),false));  // Camera Model\r
411                         a.setRecoType(stringValue(query.valueString(18)));                 // Recognition Type\r
412                         a.setFileName(stringValue(query.valueString(19)));                  // File Name\r
413                         a.setAttachment(booleanValue(query.valueString(20).toString(),false));\r
414                         a.setSourceURL(query.valueString(21));\r
415                         r.setAttributes(a);\r
416                 \r
417                         if (withBinary) {\r
418                             \r
419                                 query.prepare("Select dataBinary from NoteResources where guid=:guid");\r
420                                 query.bindValue(":guid", r.getGuid());\r
421                                 query.exec();\r
422                                 if (query.next()) {\r
423                                         byte[] b = query.getBlob(0);\r
424                                         r.getData().setBody(b);\r
425                                 }\r
426                         } \r
427                 }\r
428                 return r;\r
429         }\r
430         \r
431         \r
432         // Get a note's resourcesby Guid\r
433         public List<Resource> getNoteResources(String noteGuid, boolean withBinary) {\r
434                 if (noteGuid == null)\r
435                         return null;\r
436                 List<Resource> res = new ArrayList<Resource>();\r
437                 \r
438                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
439                 query.prepare("Select guid"\r
440                                 +" from NoteResources where noteGuid = :noteGuid");\r
441                 query.bindValue(":noteGuid", noteGuid);\r
442                 if (!query.exec()) {\r
443                         logger.log(logger.EXTREME, "NoteResources SQL select has failed.");\r
444                         logger.log(logger.MEDIUM, query.lastError());\r
445                         return null;\r
446                 }\r
447                 while (query.next()) {\r
448                         String guid = (query.valueString(0));\r
449                         res.add(getNoteResource(guid, withBinary));\r
450                 }       \r
451                 return res;\r
452         }\r
453         // Get all of a note's recognition data by the note guid\r
454         public List<Resource> getNoteResourcesRecognition(String noteGuid) {\r
455                 if (noteGuid == null)\r
456                         return null;\r
457                 boolean check;\r
458                 List<Resource> res = new ArrayList<Resource>();\r
459                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
460                 check = query.prepare("Select "\r
461                                 +"recognitionHash, recognitionSize, recognitionBinary "\r
462                                 +" from NoteResources where noteGuid=:guid");\r
463                 if (!check) {\r
464                         logger.log(logger.EXTREME, "NoteTable.getNoteRecognition SQL prepare has failed.");\r
465                         logger.log(logger.MEDIUM, query.lastError());\r
466                         return null;\r
467                 }\r
468                 query.bindValue(":guid", noteGuid);\r
469                 if (!check) {\r
470                         logger.log(logger.EXTREME, "NoteTable.getNoteRecognition exec has failed.");\r
471                         logger.log(logger.MEDIUM, query.lastError());\r
472                         return null;\r
473                 }\r
474                 while (query.next()) {  \r
475                         Resource r = new Resource();            \r
476                         res.add(r);\r
477                         Data rec = new Data();\r
478                         rec.setBodyHash(query.valueString(0).getBytes());\r
479                         String x = new String(query.valueString(1));\r
480                         if (!x.equals("")) {\r
481                                 rec.setSize(new Integer(x));\r
482                                 rec.setBody(query.valueString(2).getBytes());\r
483                         } else\r
484                                 rec.setSize(0);\r
485                         r.setRecognition(rec);\r
486                 }       \r
487                 return res;\r
488         }\r
489         \r
490         \r
491         // Get a note's recognition data by it's guid.\r
492         public Resource getNoteResourceRecognition(String guid) {\r
493                 if (guid == null)\r
494                         return null;\r
495                 boolean check;\r
496                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
497                 check = query.prepare("Select "\r
498                                 +"recognitionHash, recognitionSize, recognitionBinary, noteGuid "\r
499                                 +" from NoteResources where guid=:guid");\r
500                 if (!check) {\r
501                         logger.log(logger.EXTREME, "NoteTable.getNoteRecognition SQL prepare has failed.");\r
502                         logger.log(logger.MEDIUM, query.lastError());\r
503                         return null;\r
504                 }\r
505                 query.bindValue(":guid", guid);\r
506                 query.exec();\r
507                 if (!check) {\r
508                         logger.log(logger.EXTREME, "NoteTable.getNoteRecognition exec has failed.");\r
509                         logger.log(logger.MEDIUM, query.lastError());\r
510                         return null;\r
511                 }\r
512                 Resource r = null;\r
513                 while (query.next()) {\r
514                                                                         \r
515                         r = new Resource();             \r
516                         Data rec = new Data();\r
517                         rec.setBodyHash(query.valueString(0).getBytes());\r
518                         String x = new String(query.valueString(1));\r
519                         if (!x.equals("")) {\r
520                                 rec.setSize(new Integer(x));\r
521                                 rec.setBody(query.valueString(2).getBytes());\r
522                         } else\r
523                                 rec.setSize(0);\r
524                         r.setRecognition(rec);\r
525                         r.setNoteGuid(query.valueString(3));\r
526                 }       \r
527                 return r;\r
528         }\r
529 \r
530         // Save Note Resource\r
531         public void updateNoteResource(Resource r, boolean isDirty) {\r
532                 logger.log(logger.HIGH, "Entering ListManager.updateNoteResource");\r
533                 expungeNoteResource(r.getGuid());\r
534                 saveNoteResource(r, isDirty);\r
535                 logger.log(logger.HIGH, "Leaving RNoteResourceTable.updateNoteResource");\r
536         }\r
537         // Update note resource GUID\r
538         public void updateNoteResourceGuid(String oldGuid, String newGuid, boolean isDirty) {\r
539                 logger.log(logger.HIGH, "Entering RNoteResourceTable.updateNoteResourceGuid");\r
540                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
541                 query.prepare("update NoteResources set guid=:newGuid, isDirty=:isDirty where guid=:oldGuid");\r
542                 query.bindValue(":newGuid", newGuid);\r
543                 query.bindValue(":isDirty", isDirty);\r
544                 query.bindValue(":oldGuid", oldGuid);\r
545                 query.exec();\r
546                 query.exec("commit");\r
547                 logger.log(logger.HIGH, "Leaving RNoteResourceTable.updateNoteResourceGuid");\r
548         }\r
549         // Update note resource GUID\r
550         public void resetUpdateSequenceNumber(String guid, boolean isDirty) {\r
551                 logger.log(logger.HIGH, "Entering RNoteResourceTable.updateNoteResourceGuid");\r
552                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
553                 query.prepare("update NoteResources set updateSequenceNumber=0, isDirty=:isDirty where guid=:guid");\r
554                 query.bindValue(":isDirty", isDirty);\r
555                 query.bindValue(":guid", guid);\r
556                 query.exec();\r
557                 query.exec("commit");\r
558                 logger.log(logger.HIGH, "Leaving RNoteResourceTable.updateNoteResourceGuid");\r
559         }\r
560         \r
561         // Drop the table\r
562         public void reindexAll() {              \r
563                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
564                 query.exec("Update NoteResources set indexneeded=true");\r
565                 query.exec("commit");\r
566         }\r
567         // Count attachments\r
568         public int getResourceCount() {\r
569         NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
570                 query.exec("select count(*) from noteresources");\r
571                 query.next(); \r
572                 int returnValue = new Integer(query.valueString(0));\r
573                 return returnValue;\r
574         }\r
575         //\r
576         // Count unindexed notes\r
577         public int getUnindexedCount() {\r
578         NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
579                 query.exec("select count(*) from noteresources where indexneeded=true");\r
580                 query.next(); \r
581                 int returnValue = new Integer(query.valueString(0));\r
582                 return returnValue;\r
583         }\r
584         \r
585         //********************************************\r
586         //** Utility Functions\r
587         //********************************************\r
588         // Convert a byte array to a hex string\r
589         private static String byteArrayToHexString(byte data[]) {\r
590                 StringBuffer buf = new StringBuffer();\r
591             for (byte element : data) {\r
592                 int halfbyte = (element >>> 4) & 0x0F;\r
593                 int two_halfs = 0;\r
594                 do {\r
595                         if ((0 <= halfbyte) && (halfbyte <= 9))\r
596                                buf.append((char) ('0' + halfbyte));\r
597                            else\r
598                                 buf.append((char) ('a' + (halfbyte - 10)));\r
599                         halfbyte = element & 0x0F;\r
600                 } while(two_halfs++ < 1);\r
601             }\r
602             return buf.toString();              \r
603         }\r
604 \r
605         \r
606         private String stringValue(Object value) {\r
607                 if (value != null && value.toString() != null) \r
608                         return value.toString();\r
609                 else\r
610                         return null;\r
611         }\r
612         \r
613         private  boolean booleanValue(Object value, boolean unknown) {\r
614                 if (value != null && value.toString() != null) {\r
615                         try {\r
616                                 if ((Integer)value > 0)\r
617                                         return true;\r
618                                 else\r
619                                         return false;\r
620                         } catch (java.lang.ClassCastException e) {\r
621                                 try {\r
622                                         String stringValue = (String)value;\r
623                                         if (stringValue.equalsIgnoreCase("true"))\r
624                                                 return true;\r
625                                         else \r
626                                                 return false;\r
627                                 } catch (java.lang.ClassCastException e1) { \r
628                                         return unknown;\r
629                                 }\r
630                         }\r
631                 }\r
632                 else\r
633                         return unknown;\r
634         }\r
635 \r
636         // Update note source url. \r
637         public void updateNoteSourceUrl(String guid, String url, boolean isDirty) {\r
638                 logger.log(logger.HIGH, "Entering RNoteResourceTable.updateNoteSourceUrl()");\r
639                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
640                 query.prepare("update NoteResources set attributesourceurl=:url, isDirty=:isDirty where guid=:guid");\r
641                 query.bindValue(":guid", guid);\r
642                 query.bindValue(":isDirty", isDirty);\r
643                 query.bindValue(":url", url);\r
644                 query.exec();\r
645                 query.exec("commit");\r
646                 logger.log(logger.HIGH, "Leaving RNoteResourceTable.updateNoteSourceUrl()");\r
647         }\r
648         \r
649         // Get note source\r
650         public String getNoteSourceUrl(String guid) {\r
651                 logger.log(logger.HIGH, "Entering RNoteResourceTable.getNoteSourceUrl()");\r
652                 NSqlQuery query = new NSqlQuery(db.getResourceConnection());\r
653                 query.prepare("Select attributesourceurl from noteresources where guid=:guid");\r
654                 query.bindValue(":guid", guid);\r
655                 query.exec();\r
656                 if (query.next()) {\r
657                         logger.log(logger.HIGH, "Leaving RNoteResourceTable.getNoteSourceUrl()");\r
658                         return query.valueString(0);\r
659                 }\r
660                 logger.log(logger.HIGH, "Leaving RNoteResourceTable.getNoteSourceUrl() - no value found");\r
661                 return null;\r
662         }\r
663 }\r