diff options
Diffstat (limited to 'src/database/BrandAnalyzerQueue.java')
-rw-r--r-- | src/database/BrandAnalyzerQueue.java | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/src/database/BrandAnalyzerQueue.java b/src/database/BrandAnalyzerQueue.java new file mode 100644 index 0000000..d4e4029 --- /dev/null +++ b/src/database/BrandAnalyzerQueue.java @@ -0,0 +1,88 @@ +package database; + +import analysis.BrandChecker; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author Peter Wu + */ +public class BrandAnalyzerQueue implements Runnable { + + private final BrandChecker checker; + private final ResultSet data; + private final BlockingQueue<Result> queue; + private volatile boolean last = false; + + public BrandAnalyzerQueue(ResultSet data) { + this.checker = new BrandChecker("brandonlyrules.txt"); + this.data = data; + this.queue = new ArrayBlockingQueue<>(1000); + } + + private Logger getLogger() { + return Logger.getLogger(BrandAnalyzerQueue.class.getName()); + } + + @Override + public void run() { + try { + fillQueue(); + } catch (SQLException ex) { + getLogger().log(Level.SEVERE, "Horrible! Database error", ex); + } catch (InterruptedException ex) { + getLogger().log(Level.SEVERE, "Interrupted!", ex); + } + try { + last = true; + queue.put(new Result(-1, null)); + } catch (InterruptedException ex) { + getLogger().log(Level.SEVERE, "Failed to insert suicide pill!"); + } + } + + private void fillQueue() throws SQLException, InterruptedException { + while (data.next()) { + List<String> brands = checker.getBrands(data.getString("text")); + // if there is no brand, add a dummy so we know it got checked + if (brands.isEmpty()) { + brands.add("no"); + } + long tweetid = data.getLong("tweetid"); + Result result = new Result(tweetid, brands); + queue.put(result); + } + } + + public Result next() { + Result result = null; + try { + if (!last) { + result = queue.take(); + if (result.brands == null) { + result = null; + } + } + } catch (InterruptedException ex) { + getLogger().log(Level.SEVERE, "Interrupted!", ex); + } + return result; + } + + public static class Result { + + public final long tweetid; + public final List<String> brands; + + public Result(long tweetid, List<String> brands) { + this.tweetid = tweetid; + this.brands = brands; + } + } +} |