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

Last change on this file since 24395 was 24393, checked in by sjm84, 13 years ago

Adding in the server-side code for the Document Maker as well as several other enhancements

  • 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;
178 try
179 {
180 try
181 {
182 // The key is UTF8: do db lookup using the UTF8 version of key
183 s_info = (String) db_.fetch(key.getBytes("UTF-8"));
184 }
185 catch (UnsupportedEncodingException e)
186 {
187 logger.warn("utf8 key for " + key + " unrecognised. Retrying with default encoding.");
188 // retry db lookup using default encoding of key instead of UTF8
189 s_info = (String) db_.fetch(key);
190 }
191 }
192 catch (GdbmException e)
193 {
194 logger.error("couldn't get record");
195 return null;
196 }
197 if (s_info == null)
198 {
199 // record not present
200 logger.error("key " + key + " not present in db");
201 return null;
202 }
203 return s_info;
204 }
205
206 /**
207 * sets the given key to the given value in the database
208 */
209 public boolean setValue(String key, String value)
210 {
211 if (db_ == null || !db_.isWritable())
212 {
213 logger.error("GDBM database is either null or not writable");
214 return false;
215 }
216
217 try
218 {
219 db_.store(key, value);
220 }
221 catch (GdbmException ex)
222 {
223 logger.error("Error storing " + key + " = " + value + " in GDBM database");
224 logger.error("Error message is: " + ex.getMessage());
225 return false;
226 }
227 return true;
228 }
229
230 /**
231 * deletes the entry for given key
232 */
233 public boolean deleteKey(String key)
234 {
235 if (db_ == null)
236 {
237 logger.error("GDBM database is null");
238 return false;
239 }
240
241 try
242 {
243 db_.delete(key);
244 }
245 catch (GdbmException ex)
246 {
247 logger.error("Error deleting key " + key + " from the database");
248 logger.error("Error message is: " + ex.getMessage());
249 return false;
250 }
251
252 return true;
253 }
254
255 /**
256 * returns a string of key-value entries that can be printed for debugging
257 * purposes.
258 */
259 public String displayAllEntries()
260 {
261 StringBuffer output = new StringBuffer();
262 try
263 {
264 java.util.Enumeration e = db_.keys();
265 while (e.hasMoreElements())
266 {
267 Object key = e.nextElement();
268 Object value = db_.fetch(key);
269
270 output.append("key href: ");
271 output.append((String) key);
272 output.append("\tvalue ID: ");
273 output.append((String) value);
274 output.append("\n");
275 //logger.warn("key: " + key + "\tvalue: " + value);
276
277 String urlkey = java.net.URLEncoder.encode((String) key, "UTF8");
278 output.append("URL encoded key: " + urlkey);
279 //logger.warn("URL encoded key: " + urlkey);
280 }
281 }
282 catch (UnsupportedEncodingException e)
283 {
284 logger.warn("Trouble converting key to UTF-8.");
285 }
286 catch (Exception e)
287 {
288 logger.warn("Exception encountered when trying to displayAllEntries():" + e);
289 }
290 return output.toString();
291 }
292}
Note: See TracBrowser for help on using the repository browser.