package backtype.storm.contrib.cassandra.bolt;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;

import backtype.storm.contrib.cassandra.bolt.mapper.TupleMapper;
import backtype.storm.coordination.BatchOutputCollector;
import backtype.storm.coordination.IBatchBolt;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Tuple;

@SuppressWarnings({ "serial", "rawtypes" })
public class TransactionalCassandraBatchBolt extends CassandraBatchingBolt implements IBatchBolt {
    private static final Logger LOG = LoggerFactory.getLogger(TransactionalCassandraBatchBolt.class);

    public TransactionalCassandraBatchBolt(TupleMapper tupleMapper) {
        super(tupleMapper);
    }

    @Override
    public void prepare(Map conf, TopologyContext context, BatchOutputCollector collector, Object id) {
        this.queue = new LinkedBlockingQueue<Tuple>();        
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        // By default we don't emit anything.        
    }

    @Override
    public void finishBatch() {
        List<Tuple> batch = new ArrayList<Tuple>();
        queue.drainTo(batch);
        try {
            this.writeTuples(batch);
        } catch (ConnectionException e) {
            LOG.error("Could not write batch to cassandra.", e);
        }
    }

    @Override
    public void execute(Tuple tuple) {
        queue.add(tuple);        
    }
}

@@ -844,16 +844,57 @@
 .class);
+%0A    private Object transactionId = null;
 %0A%0A    pu
@@ -1106,24 +1106,62 @@
 bject id) %7B%0A
+        super.prepare(conf, context);%0A
         this
@@ -1200,30 +1200,129 @@
 %3CTuple%3E();  
+%0A
       
+  this.transactionId = id;%0A        LOG.debug(%22Preparing cassandra batch %5B%22 + transactionId + %22%5D%22);
 %0A    %7D%0A%0A    
@@ -1453,32 +1453,199 @@
         %0A    %7D%0A%0A
+    @Override%0A    public void execute(Tuple tuple) %7B%0A        // LOG.debug(%22Executing tuple for %5B%22 + transactionId + %22%5D%22);%0A        queue.add(tuple);        %0A    %7D%0A    %0A
     @Override%0A  
@@ -1670,24 +1670,33 @@
 shBatch() %7B%0A
+        %0A
         List
@@ -1738,24 +1738,35 @@
 %3E();%0A       
+ int size =
  queue.drain
@@ -1768,32 +1768,130 @@
 drainTo(batch);%0A
+        LOG.debug(%22Finishing batch for %5B%22 + transactionId + %22%5D, writing %5B%22 + size + %22%5D tuples.%22);%0A
         try %7B%0A  
@@ -2053,99 +2053,6 @@
  %7D%0A%0A
-    @Override%0A    public void execute(Tuple tuple) %7B%0A        queue.add(tuple);        %0A    %7D%0A
 %7D%0A

Fix for the transactional bolt, now working in a transactional topology.