All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.gridkit.jvmtool.event.MorphingEventReader Maven / Gradle / Ivy

There is a newer version: 0.23
Show newest version
package org.gridkit.jvmtool.event;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class MorphingEventReader implements EventReader {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static  EventReader morph(EventReader source, EventMorpher morpher) {
        return new MorphingEventReader(source, morpher);
    }

    private final EventReader nested;
    private final EventMorpher morpher;
    private T nextEvent;

    protected MorphingEventReader(EventReader source) {
        this(source, null);
    }

    public MorphingEventReader(EventReader source, EventMorpher morph) {
        this.nested = source;
        this.morpher = morph;
    }

    @Override
    public  EventReader morph(EventMorpher morpher) {
        return morph(this, morpher);
    }

    @Override
    public boolean hasNext() {
        while(nextEvent == null && nested.hasNext()) {
            Event e = nested.next();
            nextEvent = transform(e);
        }
        return nextEvent != null;
    }

    protected T transform(Event event) {
        return morpher.morph(event);
    }

    @Override
    public T next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        T event = nextEvent;
        nextEvent = null;
        return event;
    }

    @Override
    public T peekNext() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        T event = nextEvent;
        return event;
    }

    @Override
    public Iterator iterator() {
        return this;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    @Override
    public void dispose() {
        nested.dispose();
    }
}