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; /** * Retrieves tweets from a statement and queues the brand analysis. * * @author Peter Wu */ public class BrandAnalyzerQueue implements Runnable { private final BrandChecker checker; private final ResultSet data; private final BlockingQueue 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 { int count = 0; while (data.next()) { List 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); ++count; } getLogger().log(Level.INFO, "Finished with queuing " + count + " analyses of tweets"); } 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 brands; public Result(long tweetid, List brands) { this.tweetid = tweetid; this.brands = brands; } } }