BasicDataConsumer.java 2.08 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
6
 * Copyright (C) 2004 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
7
 *
8 9
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
Matt Tucker's avatar
Matt Tucker committed
10
 */
11

Matt Tucker's avatar
Matt Tucker committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
package org.jivesoftware.net.spi;

import org.jivesoftware.net.DataConsumer;
import org.jivesoftware.net.DataProducer;
import org.jivesoftware.net.Monitor;

import java.nio.ByteBuffer;
import java.util.Date;

import org.jivesoftware.net.DataConsumer;
import org.jivesoftware.net.DataProducer;

/**
 * <p>A basic implementation of the data consumer .</p>
 *
 * @author Iain Shigeoka
 */
public class BasicDataConsumer implements DataConsumer {

    protected DataProducer source;
    protected DataConsumer sink;
    protected Monitor monitor;

    BasicDataConsumer(DataProducer source, DataConsumer sink, Monitor monitor){
        this.source = source;
        this.sink = sink;
        this.monitor = monitor;
    }

    BasicDataConsumer(Monitor monitor){
        this.monitor = monitor;
    }

    BasicDataConsumer(){
    }

    public void setSource(DataProducer source) {
        this.source = source;
    }

    public void setSink(DataConsumer sink) {
        this.sink = sink;
    }

    public void consumeAll() {
        if (source != null){
            ByteBuffer data = source.produce(0);
            while (data != null){
                consume(data);
                data = source.produce(0);
            }
        }
    }

    public void consume(ByteBuffer data) {
        Date start = new Date();
        int size = data.remaining();
        preConsume(data);
        if (data.hasRemaining()){
            doConsume(data);
        }
        if (data.hasRemaining()){
            postConsume(data);
        }
        if (monitor != null){
            monitor.addSample(size,start,new Date());
        }

        if (sink != null && data.hasRemaining()){
            sink.consume(data);
        }
    }

    protected void preConsume(ByteBuffer data){
    }

    protected void doConsume(ByteBuffer data){
    }

    protected void postConsume(ByteBuffer data){
    }
}