Project

General

Profile

1
/**
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: daigle $'
9
 *     '$Date: 2009-08-24 14:34:17 -0700 (Mon, 24 Aug 2009) $'
10
 * '$Revision: 5030 $'
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
import java.util.HashMap;
34
import java.lang.Comparable;
35

    
36
import edu.ucsb.nceas.metacat.database.DBConnection;
37
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
38
import edu.ucsb.nceas.metacat.properties.PropertyService;
39
import edu.ucsb.nceas.metacat.util.MetacatUtil;
40
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
41

    
42
import org.apache.log4j.Logger;
43

    
44
public class IndexingQueue {
45

    
46
	private Logger logMetacat = Logger.getLogger(IndexingQueue.class);
47
	//	 Map used to keep tracks of docids to be indexed
48
	private HashMap indexingMap = new HashMap();     
49
	private Vector currentThreads = new Vector();
50
	public Vector currentDocidsBeingIndexed = new Vector();
51
	private boolean metacatRunning = true;
52
	
53
	private static IndexingQueue instance = null;
54

    
55
	final static int NUMBEROFINDEXINGTHREADS;
56
	static {
57
		int numIndexingThreads = 0;
58
		try {
59
			numIndexingThreads = 
60
				Integer.parseInt(PropertyService.getProperty("database.numberOfIndexingThreads"));
61
		} catch (PropertyNotFoundException pnfe) {
62
			System.err.println("Could not get property in static block: " 
63
					+ pnfe.getMessage());
64
		}
65
		NUMBEROFINDEXINGTHREADS = numIndexingThreads;
66
	}
67

    
68
	
69
	private int sleepTime = 2000; 
70

    
71
    private IndexingQueue() {
72
	    for (int i = 0; i < NUMBEROFINDEXINGTHREADS; i++) {
73
	      Thread thread = new IndexingTask();
74
	      thread.start();
75
	      currentThreads.add(thread);
76
	    }
77
    }
78
	
79
	public static synchronized IndexingQueue getInstance(){
80
		if (instance == null) {
81
			instance = new IndexingQueue();
82
		}
83
		return instance;
84
	}//getInstance
85

    
86
    public void add(String docid, String rev) {
87
    	add(new IndexingQueueObject(docid, rev, 0));
88
    }
89
    
90
    protected void add(IndexingQueueObject queueObject) {
91
	    synchronized (indexingMap) {
92
	    	if(!indexingMap.containsKey(queueObject.getDocid())){
93
	    		indexingMap.put(queueObject.getDocid(), queueObject);
94
	    		indexingMap.notify();
95
	    	} else {
96
	    		IndexingQueueObject oldQueueObject = 
97
	    			(IndexingQueueObject) indexingMap.get(queueObject.getDocid());
98
	    		if(oldQueueObject.compareTo(queueObject) < 0){
99
	    	  		indexingMap.put(queueObject.getDocid(), queueObject);
100
		    		indexingMap.notify();  			
101
	    		}
102
	    	}
103
	    }
104
	  }
105
    
106
	public boolean getMetacatRunning(){
107
		return this.metacatRunning;
108
	}
109
	
110
	public void setMetacatRunning(boolean metacatRunning){
111
		this.metacatRunning = metacatRunning;
112
		
113
		if(!metacatRunning){
114
			for(int count=0; count<currentThreads.size(); count++){
115
				((IndexingTask)currentThreads.get(count)).metacatRunning = false;
116
				((Thread)currentThreads.get(count)).interrupt();
117
			}
118
		}
119
	}
120
	
121
    protected IndexingQueueObject getNext() {
122
    	IndexingQueueObject returnVal = null;
123
        synchronized (indexingMap) {
124
          while (indexingMap.isEmpty() && metacatRunning) {
125
            try {
126
            	indexingMap.wait();
127
            } catch (InterruptedException ex) {
128
              System.err.println("Interrupted");
129
            }
130
          }
131
          
132
          if(metacatRunning){
133
        	  String docid = (String) indexingMap.keySet().iterator().next();
134
        	  returnVal = (IndexingQueueObject)indexingMap.get(docid);
135
        	  indexingMap.remove(docid);
136
          }
137
        }
138
        return returnVal;
139
      }
140

    
141
}
142

    
143
class IndexingTask extends Thread {
144
  	  private Logger logMetacat = Logger.getLogger(IndexingTask.class);
145
  	  
146
  	  
147
      protected final static long MAXIMUMINDEXDELAY;
148
      static {
149
    	  long maxIndexDelay = 0;
150
    	  try {
151
    		  maxIndexDelay = 
152
    			  Integer.parseInt(PropertyService.getProperty("database.maximumIndexDelay")); 
153
    	  } catch (PropertyNotFoundException pnfe) {
154
    		  System.err.println("Could not get property in static block: " 
155
  					+ pnfe.getMessage());
156
    	  }
157
    	  MAXIMUMINDEXDELAY = maxIndexDelay;
158
      }
159
      
160
      protected boolean metacatRunning = true;
161
      	
162
	  public void run() {
163
	    while (metacatRunning) {
164
	      // blocks until job
165
	      IndexingQueueObject returnVal = 
166
	    	  IndexingQueue.getInstance().getNext();
167

    
168
	      if(returnVal != null){
169
	    	  if(!IndexingQueue.getInstance().
170
	    			currentDocidsBeingIndexed.contains(returnVal.getDocid())){
171
    		  try {
172
    			  IndexingQueue.getInstance().
173
    			  		currentDocidsBeingIndexed.add(returnVal.getDocid());
174
    		      String docid = returnVal.getDocid() + "." + returnVal.getRev();
175
    			  if(checkDocumentTable(docid, "xml_documents")){
176
    				  logMetacat.warn("Calling buildIndex for " + docid);
177
    				  DocumentImpl doc = new DocumentImpl(docid, false);
178
    				  doc.buildIndex();
179
    				  logMetacat.warn("finish building index for doicd "+docid);
180
    			  } else {
181
    				  logMetacat.warn("Couldn't find the docid:" + docid 
182
	                			+ " in xml_documents table");
183
	                  sleep(MAXIMUMINDEXDELAY);
184
	                  throw(new Exception("Couldn't find the docid:" + docid 
185
	                			+ " in xml_documents table"));
186
    			  }
187
    		  	} catch (Exception e) {
188
    			  logMetacat.warn("Exception: " + e);
189
    			  e.printStackTrace();
190
	        
191
    			  if(returnVal.getCount() < 25){
192
    				  returnVal.setCount(returnVal.getCount()+1);
193
    				  // add the docid back to the list
194
    				  IndexingQueue.getInstance().add(returnVal);
195
    			  } else {
196
    				  logMetacat.fatal("Docid " + returnVal.getDocid() 
197
	        			+ " has been inserted to IndexingQueue "
198
	        			+ "more than 25 times. Not adding the docid to"
199
	        			+ " the queue again.");
200
    			  }
201
    		  	} finally {
202
    			  	IndexingQueue.getInstance().currentDocidsBeingIndexed
203
    			  		.remove(returnVal.getDocid());	    	  
204
    		  	}
205
	    	  } else {
206
	    		  returnVal.setCount(returnVal.getCount()+1);
207
	    		  IndexingQueue.getInstance().add(returnVal);    		  
208
	    	  }
209
	      }
210
	    }
211
	  }
212
	  
213
      private boolean checkDocumentTable(String docid, String tablename) throws Exception{
214
	        DBConnection dbConn = null;
215
	        int serialNumber = -1;
216
	        boolean inxmldoc = false;
217
            
218
	        String revision = docid.substring(docid.lastIndexOf(".")+1,docid.length());
219
	        docid = docid.substring(0,docid.lastIndexOf("."));
220

    
221
	        logMetacat.info("Checking if document exists in xml_documents: docid is " 
222
	        		+ docid + " and revision is " + revision);
223

    
224
	        try {
225
	            // Opening separate db connection for writing XML Index
226
	            dbConn = DBConnectionPool
227
	                    .getDBConnection("DBSAXHandler.checkDocumentTable");
228
	            serialNumber = dbConn.getCheckOutSerialNumber();
229

    
230
	            String xmlDocumentsCheck = "SELECT distinct docid FROM " + tablename
231
	                        + " WHERE docid ='" + docid
232
	                        + "' AND rev ='" + revision + "'";
233

    
234
                PreparedStatement xmlDocCheck = dbConn.prepareStatement(xmlDocumentsCheck);
235
                // Increase usage count
236
	            
237
                dbConn.increaseUsageCount(1);
238
	            xmlDocCheck.execute();
239
	            ResultSet doccheckRS = xmlDocCheck.getResultSet();
240
	            boolean tableHasRows = doccheckRS.next();
241
	            if (tableHasRows) {
242
	            	inxmldoc = true;
243
	            }
244
	            doccheckRS.close();
245
	            xmlDocCheck.close();
246
	        } catch (SQLException e) {
247
	        	   e.printStackTrace();
248
	        } finally {
249
	            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
250
	        }//finally
251
	        
252
	        return inxmldoc;
253
      }
254
	}
255

    
256
class IndexingQueueObject implements Comparable{
257
	// the docid of the document to be indexed. 
258
	private String docid;
259
	// the docid of the document to be indexed. 
260
	private String rev;
261
	// the count of number of times the document has been in the queue
262
	private int count;
263
	
264
	IndexingQueueObject(String docid, String rev, int count){
265
		this.docid = docid;
266
		this.rev = rev;
267
		this.count = count;
268
	}
269
	
270
	public int getCount(){
271
		return count;
272
	}
273

    
274
	public String getDocid(){
275
		return docid;
276
	}
277

    
278
	public String getRev(){
279
		return rev;
280
	}
281

    
282
	public void setCount(int count){
283
		this.count = count;
284
	}
285
	
286
	public void setDocid(String docid){
287
		this.docid = docid;
288
	}
289

    
290
	public void setRev(String rev){
291
		this.rev = rev;
292
	}
293
	
294
	public int compareTo(Object o){
295
		if(o instanceof IndexingQueueObject){
296
			int revision = Integer.parseInt(rev);
297
			int oRevision = Integer.parseInt(((IndexingQueueObject)o).getRev());
298
			
299
			if(revision == oRevision) {
300
				return 0;
301
			} else if (revision > oRevision) {
302
				return 1;
303
			} else {
304
				return -1;
305
			}
306
		} else {
307
			throw new java.lang.ClassCastException();
308
		}
309
	}
310
}
(38-38/62)