/** * Word Count Bolt counts the occurrences of each word that it receives. * * * @author Tarun Sharma * @version 1.0 * @see <a href="http://www.dream-lab.in/">DREAM:Lab</a> * * Copyright 2014 DREAM:Lab, Indian Institute of Science, 2014 * * 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 mypackage.bolts; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichBolt; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; public class WordCount extends BaseRichBolt{ /** * */ private static final long serialVersionUID = -4782405675667761922L; private static Logger LOG = LoggerFactory.getLogger(WordCount.class); OutputCollector collector; Map<String, Integer> counts = new HashMap<String, Integer>(); @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { // TODO Auto-generated method stub this.collector = collector; } @Override public void execute(Tuple tuple) { String word = tuple.getString(0); Integer count = counts.get(word); LOG.info("Inside WordCount anchors to ids is " + tuple.getMessageId().getAnchorsToIds()); if (count == null) count = 0; count++; counts.put(word, count); collector.emit(tuple, new Values(word, count)); collector.ack(tuple); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("word", "count")); } }