made modifications to read content from file
Project: http://git-wip-us.apache.org/repos/asf/storm/repo Commit: http://git-wip-us.apache.org/repos/asf/storm/commit/3a627953 Tree: http://git-wip-us.apache.org/repos/asf/storm/tree/3a627953 Diff: http://git-wip-us.apache.org/repos/asf/storm/diff/3a627953 Branch: refs/heads/master Commit: 3a627953b0c2221c049d7ab0a8c6bd0b3dc1b430 Parents: 2e0c5e5 Author: Sanket <schintap@untilservice-lm> Authored: Tue Dec 15 10:59:06 2015 -0600 Committer: Sanket <schintap@untilservice-lm> Committed: Tue Dec 15 10:59:06 2015 -0600 ---------------------------------------------------------------------- .../starter/BlobStoreAPIWordCountTopology.java | 194 ++++++++++++------- 1 file changed, 126 insertions(+), 68 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/storm/blob/3a627953/examples/storm-starter/src/jvm/storm/starter/BlobStoreAPIWordCountTopology.java ---------------------------------------------------------------------- diff --git a/examples/storm-starter/src/jvm/storm/starter/BlobStoreAPIWordCountTopology.java b/examples/storm-starter/src/jvm/storm/starter/BlobStoreAPIWordCountTopology.java index e0a4679..5877f52 100644 --- a/examples/storm-starter/src/jvm/storm/starter/BlobStoreAPIWordCountTopology.java +++ b/examples/storm-starter/src/jvm/storm/starter/BlobStoreAPIWordCountTopology.java @@ -51,46 +51,46 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; -import java.util.Arrays; -import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; +import java.util.Set; +import java.util.StringTokenizer; public class BlobStoreAPIWordCountTopology { - private static NimbusBlobStore store = new NimbusBlobStore(); // Client API to invoke blob store API functionality - private static String key = "key1"; + private static ClientBlobStore store; // Client API to invoke blob store API functionality + private static String key = "key"; + private static String fileName = "blacklist.txt"; private static final Logger LOG = LoggerFactory.getLogger(BlobStoreAPIWordCountTopology.class); - private static final List<AccessControl> WORLD_EVERYTHING = Arrays.asList(new AccessControl(AccessControlType.OTHER, - BlobStoreAclHandler.READ | BlobStoreAclHandler.WRITE | BlobStoreAclHandler.ADMIN)); + + public static void prepare() { + Config conf = new Config(); + conf.putAll(Utils.readStormConfig()); + store = Utils.getClientBlobStore(conf); + } // Spout implementation - public static class BlobStoreSpout extends BaseRichSpout { + public static class RandomSentenceSpout extends BaseRichSpout { SpoutOutputCollector _collector; - BlobStoreAPIWordCountTopology wc; - String key; - NimbusBlobStore store; - @Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { _collector = collector; - wc = new BlobStoreAPIWordCountTopology(); - key = "key1"; - store = new NimbusBlobStore(); - store.prepare(Utils.readStormConfig()); } @Override public void nextTuple() { Utils.sleep(100); - try { - _collector.emit(new Values(wc.getBlobContent(key, store))); - } catch (AuthorizationException | KeyNotFoundException | IOException exp) { - throw new RuntimeException(exp); - } + _collector.emit(new Values(getRandomSentence())); } @Override @@ -126,50 +126,45 @@ public class BlobStoreAPIWordCountTopology { } } - public static class WordCount extends BaseBasicBolt { - Map<String, Integer> counts = new HashMap<String, Integer>(); - + public static class FilterWords extends BaseBasicBolt { + String key = "key"; @Override public void execute(Tuple tuple, BasicOutputCollector collector) { - String word = tuple.getString(0); - Integer count = counts.get(word); - if (count == null) - count = 0; - count++; - counts.put(word, count); - collector.emit(new Values(word, count)); + try { + ClientBlobStore store = Utils.getClientBlobStore(Utils.readStormConfig()); + String word = tuple.getString(0); + Set<String> wordSet = parseBlobContent(getBlobContent(key, store).toString()); + if (!wordSet.contains(word)) { + collector.emit(new Values(word)); + } + } catch (AuthorizationException | KeyNotFoundException | IOException exp) { + throw new RuntimeException(exp); + } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { - declarer.declare(new Fields("word", "count")); + declarer.declare(new Fields("word")); } } public void buildAndLaunchWordCountTopology(String[] args) { - TopologyBuilder builder = new TopologyBuilder(); - - builder.setSpout("spout", new BlobStoreSpout(), 5); - + builder.setSpout("spout", new RandomSentenceSpout(), 5); builder.setBolt("split", new SplitSentence(), 8).shuffleGrouping("spout"); - builder.setBolt("count", new WordCount(), 12).fieldsGrouping("split", new Fields("word")); + builder.setBolt("filter", new FilterWords(), 6).shuffleGrouping("split"); Config conf = new Config(); conf.setDebug(true); - try { if (args != null && args.length > 0) { conf.setNumWorkers(3); StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology()); } else { conf.setMaxTaskParallelism(3); - LocalCluster cluster = new LocalCluster(); cluster.submitTopology("word-count", conf, builder.createTopology()); - Thread.sleep(10000); - cluster.shutdown(); } } catch (InvalidTopologyException | AuthorizationException | AlreadyAliveException | InterruptedException exp) { @@ -177,24 +172,42 @@ public class BlobStoreAPIWordCountTopology { } } - private static void createBlobWithContent(String blobKey, ClientBlobStore clientBlobStore, SettableBlobMeta settableBlobMeta) + // Equivalent create command on command line + // storm blobstore create --file blacklist.txt --acl o::rwa key + private static void createBlobWithContent(String blobKey, ClientBlobStore clientBlobStore, File file) throws AuthorizationException, KeyAlreadyExistsException, IOException,KeyNotFoundException { + // For more on how to set acls while creating the blob please look at distcache-blobstore.md documentation + String stringBlobACL = "o::rwa"; + AccessControl blobACL = BlobStoreAclHandler.parseAccessControl(stringBlobACL); + List<AccessControl> acls = new LinkedList<AccessControl>(); + acls.add(blobACL); // more ACLs can be added here + SettableBlobMeta settableBlobMeta = new SettableBlobMeta(acls); AtomicOutputStream blobStream = clientBlobStore.createBlob(blobKey,settableBlobMeta); - blobStream.write(getRandomSentence().getBytes()); + blobStream.write(readFile(file).toString().getBytes()); blobStream.close(); } - private static String getBlobContent(String blobKey, ClientBlobStore clientBlobStore) + // Equivalent read command on command line + // storm blobstore cat --file blacklist.txt key + private static StringBuilder getBlobContent(String blobKey, ClientBlobStore clientBlobStore) throws AuthorizationException, KeyNotFoundException, IOException { InputStreamWithMeta blobInputStream = clientBlobStore.getBlob(blobKey); - BufferedReader r = new BufferedReader(new InputStreamReader(blobInputStream)); - return r.readLine(); + BufferedReader br = new BufferedReader(new InputStreamReader(blobInputStream)); + StringBuilder blobContent = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + blobContent.append(line); + blobContent.append("\n"); + } + return blobContent; } - private static void updateBlobWithContent(String blobKey, ClientBlobStore clientBlobStore) + // Equivalent update command on command line + // storm blobstore update --file blacklist.txt key + private static void updateBlobWithContent(String blobKey, ClientBlobStore clientBlobStore, File file) throws KeyNotFoundException, AuthorizationException, IOException { AtomicOutputStream blobOutputStream = clientBlobStore.updateBlob(blobKey); - blobOutputStream.write(getRandomSentence().getBytes()); + blobOutputStream.write(readFile(file).toString().getBytes()); blobOutputStream.close(); } @@ -205,35 +218,80 @@ public class BlobStoreAPIWordCountTopology { return sentence; } - private void prepareAndPerformBasicOperations() - throws KeyAlreadyExistsException, AuthorizationException, KeyNotFoundException, IOException{ - Map conf = Utils.readStormConfig(); - store.prepare(conf); - // create blob with content - createBlobWithContent(key, store, new SettableBlobMeta(WORLD_EVERYTHING)); - // read blob content - LOG.info(getBlobContent(key, store)); - // update blob - updateBlobWithContent(key, store); - LOG.info(getBlobContent(key, store)); - // delete blob through API - store.deleteBlob(key); + private static Set<String> getRandomWordSet() { + Set<String> randomWordSet = new HashSet<>(); + Random random = new Random(); + String[] words = new String[]{ "cow", "jumped", "over", "the", "moon", "apple", "day", "doctor", "away", + "four", "seven", "ago", "snow", "white", "seven", "dwarfs", "nature", "two" }; + // Choosing atmost 5 words to update the blacklist file for filtering + for (int i=0; i<5; i++) { + randomWordSet.add(words[random.nextInt(words.length)]); + } + return randomWordSet; + } + + private static Set<String> parseBlobContent(String content) { + StringTokenizer tokens = new StringTokenizer(content, "\r\n"); + Set<String> wordSet = new HashSet<>(); + while (tokens.hasMoreElements()) { + wordSet.add(tokens.nextToken()); + } + return wordSet; + } + + private static StringBuilder readFile(File file) throws IOException { + String line; + StringBuilder fileContent = new StringBuilder(); + BufferedReader br = new BufferedReader(new FileReader(file.getCanonicalFile())); + while ((line = br.readLine()) != null) { + fileContent.append(line); + fileContent.append("\n"); + } + return fileContent; + } + + // Creating a blacklist file to read from the disk + public static File createFile(String fileName) throws IOException { + File file = null; + file = new File(fileName); + if (!file.exists()) { + file.createNewFile(); + } + writeToFile(file, getRandomWordSet()); + LOG.info(readFile(file).toString()); + return file; + } + + // Updating a blacklist file periodically with random words + public static File updateFile(File file) throws IOException { + writeToFile(file, getRandomWordSet()); + return file; + } + + // Writing random words to be blacklisted + public static void writeToFile(File file, Set<String> content) throws IOException{ + FileWriter fw = new FileWriter(file.getCanonicalPath(), false); + BufferedWriter bw = new BufferedWriter(fw); + Iterator<String> iter = content.iterator(); + while(iter.hasNext()) { + bw.write(iter.next()); + } + bw.close(); } public static void main(String[] args) { - // Basic blob store API calls create, read, update and delete + prepare(); BlobStoreAPIWordCountTopology wc = new BlobStoreAPIWordCountTopology(); try { - wc.prepareAndPerformBasicOperations(); + File file = createFile(fileName); // Creating blob again before launching topology - createBlobWithContent(key, store, new SettableBlobMeta(WORLD_EVERYTHING)); - LOG.info(getBlobContent(key, store)); + createBlobWithContent(key, store, file); // Launching word count topology with blob updates wc.buildAndLaunchWordCountTopology(args); - // Updating blobs few times - for (int i = 0; i < 10; i++) { - updateBlobWithContent(key, store); - Utils.sleep(100); + // Updating file few times every 5 seconds + for(int i=0; i<10; i++) { + updateBlobWithContent(key, store, updateFile(file)); + Utils.sleep(5000); } } catch (KeyAlreadyExistsException kae) { LOG.info("Key already exists {}", kae);
