/**
* Copyright 1999-2009 The Pegadi Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pegadi.index;
import org.apache.lucene.index.IndexWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class IndexManager implements Runnable {
private final List jobQueue = new ArrayList();
private IndexWriterManager indexWriterManager;
private boolean shutdownHit = false;
private Logger log = LoggerFactory.getLogger(getClass());;
public void addJob(IndexJob job) {
synchronized(jobQueue) {
if(log.isDebugEnabled()) {
log.debug("Adding job " + job + " to queue");
}
jobQueue.add(job);
jobQueue.notifyAll();
}
}
public void init() {
Thread t = new Thread(this);
t.start();
}
public void run() {
while(true) {
IndexJob job;
synchronized(jobQueue) {
while(jobQueue.size() == 0) {
if(log.isDebugEnabled()) {
log.debug("Waiting on empty queue");
}
try {
jobQueue.wait();
} catch (InterruptedException e) {
log.error("Interrupted", e);
}
if(shutdownHit) {
log.info("Shutting down IndexManager");
return;
}
}
job = (IndexJob) jobQueue.get(0);
}
if(log.isDebugEnabled()) {
log.debug("Got job " + job +" from queue");
}
IndexWriter indexWriter = null;
try {
indexWriter = indexWriterManager.getIndexWriter(job.isRecreateJob());
final IndexWriter finalIndexWriter = indexWriter;
JobContext context = new JobContext() {
public IndexWriter getIndexWriter() {
return finalIndexWriter;
}
public boolean isShutdown() {
return shutdownHit;
}
};
job.executeJob(context);
log.debug("Job" + job +" finished");
synchronized(jobQueue) {
if(log.isDebugEnabled()) {
log.debug("Removing job " + job + " + from queue");
jobQueue.remove(job);
}
}
} catch (IOException e) {
log.error("IOException", e);
}
finally{
if(indexWriter != null) {
try {
indexWriter.close();
} catch (IOException e) {
log.error("IOException", e);
}
}
}
}
}
public void shutdown() {
shutdownHit = true;
synchronized(jobQueue) {
jobQueue.notifyAll();
}
}
public void setIndexWriterManager(IndexWriterManager indexWriterManager) {
this.indexWriterManager = indexWriterManager;
}
}