source: main/trunk/greenstone3/src/java/org/greenstone/gsdl3/util/GDBMWrapper.java@ 28965

Last change on this file since 28965 was 25552, checked in by sjm84, 12 years ago

We need to check that a key exists before we try to get it otherwise it may cause a seg-fault (problem in the jni code somewhere)

  • Property svn:keywords set to Author Date Id Revision
File size: 7.9 KB
Line 
1/*
2 * GDBMWrapper.java
3 * Copyright (C) 2008 New Zealand Digital Library, http://www.nzdl.org
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19package org.greenstone.gsdl3.util;
20
21import au.com.pharos.gdbm.GdbmFile;
22import au.com.pharos.packing.*;
23import au.com.pharos.gdbm.GdbmException;
24
25import org.apache.log4j.Logger;
26
27import java.io.UnsupportedEncodingException;
28import java.io.File;
29
30/**
31 * java wrapper class for gdbm - uses Java-GDBM written by Martin Pool replaces
32 * gdbmclass in the old version
33 */
34
35public class GDBMWrapper implements FlatDatabaseWrapper
36{
37
38 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.GDBMWrapper.class.getName());
39
40 /*
41 * GdbmFile modes: READER - read access, many readers may share the database
42 * WRITER - read/write access, exclusive access WRCREAT - read/write access,
43 * create db if doesn't exist NEWDB - read/write access, db should be
44 * replaced if exists
45 */
46
47 protected GdbmFile db_ = null;
48
49 /**
50 * open the database filename, with mode mode - uses the constants above, eg
51 * GdbmFile.WRITER
52 */
53 public boolean openDatabase(String filename, int mode)
54 {
55 // need to convert mode to GdbmFile mode
56 if (mode == READ)
57 {
58 mode = GdbmFile.READER;
59 }
60 else if (mode == WRITE)
61 {
62 mode = GdbmFile.WRITER;
63 }
64 else
65 {
66 logger.error("invalid mode, " + mode + ", opening db for reading only");
67 mode = GdbmFile.READER;
68 }
69 try
70 {
71 if (db_ != null)
72 {
73 db_.close();
74 }
75
76 // The java version of the C++ code in common-src/src/lib/gdbmclass.cpp
77 if (mode == GdbmFile.READER)
78 {
79 // Looking to read in the database
80 // we now use gdb extension. Check for ldb/bdb in case of legacy collection
81 // if not (first time) then generate using txt2db
82 if (!new File(filename).exists())
83 {
84 logger.warn("Database file " + filename + " does not exist. Looking for ldb/bdb version");
85 int extension = filename.lastIndexOf('.');
86 String filename_head = filename.substring(0, extension);
87 filename = filename_head + ".ldb";
88 if (!new File(filename).exists())
89 {
90 filename = filename_head + ".bdb";
91
92 if (!new File(filename).exists())
93 {
94 logger.warn("ldb/bdb version of database file " + filename + " does not exist. Looking for txtgz version of db file.");
95 // put the filename back to gdb
96 filename = filename_head + ".gdb";
97 // need to generate architecture native GDBM file using txt2db
98
99 // replace sought after gdbm filename ext with ".txt.gz"
100
101 String txtgzFilename = filename_head + ".txt.gz";
102 if (new File(txtgzFilename).exists())
103 {
104 // Test to make sure Perl is on the path
105 // On Linux, the output of the test goes to STDOUT so redirect it to STDERR
106 String cmdTest = "perl -v 2>&1";
107 //String cmdTest = "echo %PATH%";
108 int returnValue = Processing.runProcess(cmdTest);
109 if (returnValue != 0)
110 {
111 logger.error("Tried to find Perl. Return exit value of running " + cmdTest + ": " + returnValue + ", (expected this to be 0)");
112 logger.error("Check that Perl is set in your PATH environment variable.");
113 //log.error("At present, PATH=" + System.getenv("PATH"));
114 }
115
116 String cmd = "perl -S txtgz-to-gdbm.pl \"" + txtgzFilename + "\" \"" + filename + "\"";
117 returnValue = Processing.runProcess(cmd);
118 // For some reason, launching this command with gsdl_system() still returns 1
119 // even when it returns 0 when run from the command-line. We can check whether
120 // we succeeded by looking at whether the output database file was created.
121 if (returnValue != 0)
122 {
123 logger.warn("Warning, non-zero return value on running command \"" + cmd + "\": " + returnValue);
124 if (!new File(filename).exists())
125 {
126 logger.error("Tried to run command \"" + cmd + "\", but it failed");
127 }
128 }
129 }
130 }
131 }
132
133 }
134 }
135
136 db_ = new GdbmFile(filename, mode);
137 }
138 catch (GdbmException e)
139 { // the database wasn't opened or created
140 logger.error("couldn't open database " + filename);
141 return false;
142 }
143 db_.setKeyPacking(new StringPacking());
144 db_.setValuePacking(new StringPacking());
145 return true;
146 }
147
148 /** close the database associated with this wrapper */
149 public void closeDatabase()
150 {
151 try
152 {
153 if (db_ != null)
154 {
155 db_.close();
156 db_ = null;
157 if (System.getProperty("os.name").startsWith("Windows"))
158 {
159 //Hack: force Windows to let go of the gdb file
160 System.gc();
161 }
162 }
163 }
164 catch (GdbmException e)
165 {
166 // should never get here - close never actually throws an exception
167 logger.error("error on close()");
168 }
169 }
170
171 public String getValue(String key)
172 {
173 if (db_ == null)
174 {
175 return null;
176 }
177 String s_info = null;
178 try
179 {
180 try
181 {
182 // The key is UTF8: do db lookup using the UTF8 version of key
183 if (db_.exists(key.getBytes("UTF-8")))
184 {
185 s_info = (String) db_.fetch(key.getBytes("UTF-8"));
186 }
187 }
188 catch (UnsupportedEncodingException e)
189 {
190 logger.warn("utf8 key for " + key + " unrecognised. Retrying with default encoding.");
191 // retry db lookup using default encoding of key instead of UTF8
192 s_info = (String) db_.fetch(key);
193 }
194 }
195 catch (GdbmException e)
196 {
197 logger.error("couldn't get record");
198 return null;
199 }
200 if (s_info == null)
201 {
202 // record not present
203 logger.error("key " + key + " not present in db");
204 return null;
205 }
206 return s_info;
207 }
208
209 /**
210 * sets the given key to the given value in the database
211 */
212 public boolean setValue(String key, String value)
213 {
214 if (db_ == null || !db_.isWritable())
215 {
216 logger.error("GDBM database is either null or not writable");
217 return false;
218 }
219
220 try
221 {
222 db_.store(key, value);
223 }
224 catch (GdbmException ex)
225 {
226 logger.error("Error storing " + key + " = " + value + " in GDBM database");
227 logger.error("Error message is: " + ex.getMessage());
228 return false;
229 }
230 return true;
231 }
232
233 /**
234 * deletes the entry for given key
235 */
236 public boolean deleteKey(String key)
237 {
238 if (db_ == null)
239 {
240 logger.error("GDBM database is null");
241 return false;
242 }
243
244 try
245 {
246 db_.delete(key);
247 }
248 catch (GdbmException ex)
249 {
250 logger.error("Error deleting key " + key + " from the database");
251 logger.error("Error message is: " + ex.getMessage());
252 return false;
253 }
254
255 return true;
256 }
257
258 /**
259 * returns a string of key-value entries that can be printed for debugging
260 * purposes.
261 */
262 public String displayAllEntries()
263 {
264 StringBuffer output = new StringBuffer();
265 try
266 {
267 java.util.Enumeration e = db_.keys();
268 while (e.hasMoreElements())
269 {
270 Object key = e.nextElement();
271 Object value = db_.fetch(key);
272
273 output.append("key href: ");
274 output.append((String) key);
275 output.append("\tvalue ID: ");
276 output.append((String) value);
277 output.append("\n");
278 //logger.warn("key: " + key + "\tvalue: " + value);
279
280 String urlkey = java.net.URLEncoder.encode((String) key, "UTF8");
281 output.append("URL encoded key: " + urlkey);
282 //logger.warn("URL encoded key: " + urlkey);
283 }
284 }
285 catch (UnsupportedEncodingException e)
286 {
287 logger.warn("Trouble converting key to UTF-8.");
288 }
289 catch (Exception e)
290 {
291 logger.warn("Exception encountered when trying to displayAllEntries():" + e);
292 }
293 return output.toString();
294 }
295}
Note: See TracBrowser for help on using the repository browser.