Project

General

Profile

1 2732 sgarg
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that tracks sessions for MetaCatServlet users.
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones
7
 *
8
 *   '$Author$'
9
 *     '$Date$'
10
 * '$Revision$'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26
27
package edu.ucsb.nceas.metacat;
28
29
import java.sql.PreparedStatement;
30
import java.sql.ResultSet;
31
import java.sql.SQLException;
32
import java.util.Vector;
33 2733 sgarg
import java.util.HashMap;
34
import java.lang.Comparable;
35 4080 daigle
36 5015 daigle
import edu.ucsb.nceas.metacat.database.DBConnection;
37
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
38 5030 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
39 4080 daigle
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
40
41 2732 sgarg
import org.apache.log4j.Logger;
42
43
public class IndexingQueue {
44
45 7432 leinfelder
	private static Logger logMetacat = Logger.getLogger(IndexingQueue.class);
46 2733 sgarg
	//	 Map used to keep tracks of docids to be indexed
47 7432 leinfelder
	private HashMap<String, IndexingQueueObject> indexingMap = new HashMap<String, IndexingQueueObject>();
48
	private Vector<IndexingTask> currentThreads = new Vector<IndexingTask>();
49
	public Vector<String> currentDocidsBeingIndexed = new Vector<String>();
50 2901 sgarg
	private boolean metacatRunning = true;
51 2732 sgarg
52
	private static IndexingQueue instance = null;
53
54 4080 daigle
	final static int NUMBEROFINDEXINGTHREADS;
55
	static {
56
		int numIndexingThreads = 0;
57
		try {
58
			numIndexingThreads =
59
				Integer.parseInt(PropertyService.getProperty("database.numberOfIndexingThreads"));
60
		} catch (PropertyNotFoundException pnfe) {
61 7432 leinfelder
			logMetacat.error("Could not get property in static block: "
62 4080 daigle
					+ pnfe.getMessage());
63
		}
64
		NUMBEROFINDEXINGTHREADS = numIndexingThreads;
65
	}
66
67 3199 tao
    private IndexingQueue() {
68 2732 sgarg
	    for (int i = 0; i < NUMBEROFINDEXINGTHREADS; i++) {
69 7432 leinfelder
	    	IndexingTask thread = new IndexingTask();
70
	    	thread.start();
71
	    	currentThreads.add(thread);
72 2732 sgarg
	    }
73
    }
74
75
	public static synchronized IndexingQueue getInstance(){
76
		if (instance == null) {
77
			instance = new IndexingQueue();
78
		}
79
		return instance;
80
	}//getInstance
81
82 2733 sgarg
    public void add(String docid, String rev) {
83
    	add(new IndexingQueueObject(docid, rev, 0));
84
    }
85 2732 sgarg
86 2733 sgarg
    protected void add(IndexingQueueObject queueObject) {
87
	    synchronized (indexingMap) {
88
	    	if(!indexingMap.containsKey(queueObject.getDocid())){
89
	    		indexingMap.put(queueObject.getDocid(), queueObject);
90
	    		indexingMap.notify();
91
	    	} else {
92 7432 leinfelder
	    		IndexingQueueObject oldQueueObject = indexingMap.get(queueObject.getDocid());
93 2733 sgarg
	    		if(oldQueueObject.compareTo(queueObject) < 0){
94
	    	  		indexingMap.put(queueObject.getDocid(), queueObject);
95
		    		indexingMap.notify();
96
	    		}
97
	    	}
98 2732 sgarg
	    }
99
	  }
100
101 2901 sgarg
	public boolean getMetacatRunning(){
102
		return this.metacatRunning;
103
	}
104 2732 sgarg
105 2901 sgarg
	public void setMetacatRunning(boolean metacatRunning){
106
		this.metacatRunning = metacatRunning;
107
108 2902 sgarg
		if(!metacatRunning){
109
			for(int count=0; count<currentThreads.size(); count++){
110 7432 leinfelder
				currentThreads.get(count).metacatRunning = false;
111
				currentThreads.get(count).interrupt();
112 2902 sgarg
			}
113 2901 sgarg
		}
114
	}
115
116 2732 sgarg
    protected IndexingQueueObject getNext() {
117
    	IndexingQueueObject returnVal = null;
118 2733 sgarg
        synchronized (indexingMap) {
119 2901 sgarg
          while (indexingMap.isEmpty() && metacatRunning) {
120 2732 sgarg
            try {
121 2733 sgarg
            	indexingMap.wait();
122 2732 sgarg
            } catch (InterruptedException ex) {
123 7433 leinfelder
              logMetacat.error("Interrupted");
124 2732 sgarg
            }
125
          }
126 2901 sgarg
127
          if(metacatRunning){
128 7432 leinfelder
        	  String docid = indexingMap.keySet().iterator().next();
129
        	  returnVal = indexingMap.get(docid);
130 2901 sgarg
        	  indexingMap.remove(docid);
131
          }
132 2732 sgarg
        }
133
        return returnVal;
134
      }
135 7433 leinfelder
136
    /**
137
     * Removes the Indexing Task object from the queue
138
     * for the given docid. Currently, rev is ignored
139
     * This method should be used to cancel scheduled indexing on a document
140
     * (typically if it is being deleted but indexing has not completed yet)
141
     * see http://bugzilla.ecoinformatics.org/show_bug.cgi?id=5750
142
     * @param docid the docid (without revision)
143
     * @param rev the docid's rev (ignored)
144
     */
145
    public void remove(String docid, String rev) {
146
		synchronized (indexingMap) {
147
			if (indexingMap.containsKey(docid)) {
148 7434 leinfelder
				logMetacat.debug("Removing indexing queue task for docid: " + docid);
149 7433 leinfelder
				indexingMap.remove(docid);
150
			}
151
		}
152
	}
153 2732 sgarg
154
}
155
156
class IndexingTask extends Thread {
157
  	  private Logger logMetacat = Logger.getLogger(IndexingTask.class);
158 4080 daigle
159
160
      protected final static long MAXIMUMINDEXDELAY;
161
      static {
162
    	  long maxIndexDelay = 0;
163
    	  try {
164
    		  maxIndexDelay =
165
    			  Integer.parseInt(PropertyService.getProperty("database.maximumIndexDelay"));
166
    	  } catch (PropertyNotFoundException pnfe) {
167
    		  System.err.println("Could not get property in static block: "
168
  					+ pnfe.getMessage());
169
    	  }
170
    	  MAXIMUMINDEXDELAY = maxIndexDelay;
171
      }
172
173 2902 sgarg
      protected boolean metacatRunning = true;
174
175 2732 sgarg
	  public void run() {
176 2902 sgarg
	    while (metacatRunning) {
177 2732 sgarg
	      // blocks until job
178 7433 leinfelder
	      IndexingQueueObject indexQueueObject =
179 2732 sgarg
	    	  IndexingQueue.getInstance().getNext();
180 2733 sgarg
181 7433 leinfelder
	      if(indexQueueObject != null){
182 2901 sgarg
	    	  if(!IndexingQueue.getInstance().
183 7433 leinfelder
	    			currentDocidsBeingIndexed.contains(indexQueueObject.getDocid())){
184 2733 sgarg
    		  try {
185
    			  IndexingQueue.getInstance().
186 7433 leinfelder
    			  		currentDocidsBeingIndexed.add(indexQueueObject.getDocid());
187
    		      String docid = indexQueueObject.getDocid() + "." + indexQueueObject.getRev();
188 2764 sgarg
    			  if(checkDocumentTable(docid, "xml_documents")){
189
    				  logMetacat.warn("Calling buildIndex for " + docid);
190
    				  DocumentImpl doc = new DocumentImpl(docid, false);
191
    				  doc.buildIndex();
192 3199 tao
    				  logMetacat.warn("finish building index for doicd "+docid);
193 2764 sgarg
    			  } else {
194
    				  logMetacat.warn("Couldn't find the docid:" + docid
195
	                			+ " in xml_documents table");
196
	                  sleep(MAXIMUMINDEXDELAY);
197
	                  throw(new Exception("Couldn't find the docid:" + docid
198
	                			+ " in xml_documents table"));
199
    			  }
200 2901 sgarg
    		  	} catch (Exception e) {
201 2733 sgarg
    			  logMetacat.warn("Exception: " + e);
202
    			  e.printStackTrace();
203 2732 sgarg
204 7433 leinfelder
    			  if(indexQueueObject.getCount() < 25){
205
    				  indexQueueObject.setCount(indexQueueObject.getCount()+1);
206 2733 sgarg
    				  // add the docid back to the list
207 7433 leinfelder
    				  IndexingQueue.getInstance().add(indexQueueObject);
208 2733 sgarg
    			  } else {
209 7433 leinfelder
    				  logMetacat.fatal("Docid " + indexQueueObject.getDocid()
210 2732 sgarg
	        			+ " has been inserted to IndexingQueue "
211 2733 sgarg
	        			+ "more than 25 times. Not adding the docid to"
212
	        			+ " the queue again.");
213
    			  }
214 2901 sgarg
    		  	} finally {
215
    			  	IndexingQueue.getInstance().currentDocidsBeingIndexed
216 7433 leinfelder
    			  		.remove(indexQueueObject.getDocid());
217 2901 sgarg
    		  	}
218
	    	  } else {
219 7433 leinfelder
	    		  indexQueueObject.setCount(indexQueueObject.getCount()+1);
220
	    		  IndexingQueue.getInstance().add(indexQueueObject);
221 2901 sgarg
	    	  }
222
	      }
223 2732 sgarg
	    }
224
	  }
225
226 2764 sgarg
      private boolean checkDocumentTable(String docid, String tablename) throws Exception{
227 2732 sgarg
	        DBConnection dbConn = null;
228
	        int serialNumber = -1;
229 2764 sgarg
	        boolean inxmldoc = false;
230
231 2732 sgarg
	        String revision = docid.substring(docid.lastIndexOf(".")+1,docid.length());
232 6595 leinfelder
	        int rev = Integer.parseInt(revision);
233 2732 sgarg
	        docid = docid.substring(0,docid.lastIndexOf("."));
234
235 4743 walbridge
	        logMetacat.info("Checking if document exists in xml_documents: docid is "
236 2764 sgarg
	        		+ docid + " and revision is " + revision);
237 2732 sgarg
238
	        try {
239
	            // Opening separate db connection for writing XML Index
240
	            dbConn = DBConnectionPool
241
	                    .getDBConnection("DBSAXHandler.checkDocumentTable");
242
	            serialNumber = dbConn.getCheckOutSerialNumber();
243
244 2764 sgarg
	            String xmlDocumentsCheck = "SELECT distinct docid FROM " + tablename
245 6595 leinfelder
	                        + " WHERE docid = ? "
246
	                        + " AND rev = ?";
247 2732 sgarg
248 2764 sgarg
                PreparedStatement xmlDocCheck = dbConn.prepareStatement(xmlDocumentsCheck);
249 6595 leinfelder
                xmlDocCheck.setString(1, docid);
250
                xmlDocCheck.setInt(2, rev);
251 2764 sgarg
                // Increase usage count
252
                dbConn.increaseUsageCount(1);
253
	            xmlDocCheck.execute();
254
	            ResultSet doccheckRS = xmlDocCheck.getResultSet();
255
	            boolean tableHasRows = doccheckRS.next();
256
	            if (tableHasRows) {
257
	            	inxmldoc = true;
258
	            }
259
	            doccheckRS.close();
260
	            xmlDocCheck.close();
261 2732 sgarg
	        } catch (SQLException e) {
262
	        	   e.printStackTrace();
263
	        } finally {
264
	            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
265
	        }//finally
266 2764 sgarg
267
	        return inxmldoc;
268
      }
269 2732 sgarg
	}
270
271 2733 sgarg
class IndexingQueueObject implements Comparable{
272 2732 sgarg
	// the docid of the document to be indexed.
273
	private String docid;
274 2733 sgarg
	// the docid of the document to be indexed.
275
	private String rev;
276 2732 sgarg
	// the count of number of times the document has been in the queue
277
	private int count;
278
279 2733 sgarg
	IndexingQueueObject(String docid, String rev, int count){
280
		this.docid = docid;
281
		this.rev = rev;
282 2732 sgarg
		this.count = count;
283
	}
284
285
	public int getCount(){
286
		return count;
287
	}
288
289
	public String getDocid(){
290
		return docid;
291
	}
292
293 2733 sgarg
	public String getRev(){
294
		return rev;
295
	}
296
297 2732 sgarg
	public void setCount(int count){
298
		this.count = count;
299
	}
300
301
	public void setDocid(String docid){
302
		this.docid = docid;
303
	}
304 2733 sgarg
305
	public void setRev(String rev){
306
		this.rev = rev;
307
	}
308
309
	public int compareTo(Object o){
310
		if(o instanceof IndexingQueueObject){
311
			int revision = Integer.parseInt(rev);
312
			int oRevision = Integer.parseInt(((IndexingQueueObject)o).getRev());
313
314
			if(revision == oRevision) {
315
				return 0;
316
			} else if (revision > oRevision) {
317
				return 1;
318
			} else {
319
				return -1;
320
			}
321
		} else {
322
			throw new java.lang.ClassCastException();
323
		}
324
	}
325 3077 jones
}