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

com.tinkerpop.pipes.transform.MemoizePipe Maven / Gradle / Ivy

Go to download

Pipes is a dataflow framework written in Java that enables the splitting, merging, filtering, and transformation of data from input to output. Computations are expressed using a combinator model and are evaluated in a memory-efficient, lazy fashion.

There is a newer version: 2.6.0
Show newest version
package com.tinkerpop.pipes.transform;

import com.tinkerpop.pipes.Pipe;
import com.tinkerpop.pipes.util.AbstractMetaPipe;
import com.tinkerpop.pipes.util.MetaPipe;
import com.tinkerpop.pipes.util.PipeHelper;
import com.tinkerpop.pipes.util.iterators.SingleExpandableIterator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public class MemoizePipe extends AbstractMetaPipe implements MetaPipe, TransformPipe {

    protected Pipe pipe;
    protected Map> map;
    protected Iterator currentIterator = PipeHelper.emptyIterator();
    protected final SingleExpandableIterator expando = new SingleExpandableIterator();

    public MemoizePipe(final Pipe pipe) {
        this(pipe, new HashMap>());
    }

    public MemoizePipe(final Pipe pipe, final Map> map) {
        this.pipe = pipe;
        this.pipe.setStarts(this.expando);
        this.map = map;
    }

    public E processNextStart() {
        while (true) {
            if (this.currentIterator.hasNext())
                return this.currentIterator.next();
            else {
                this.getOrCreate(this.starts.next());
            }
        }
    }

    private void getOrCreate(final S s) {
        if (this.map.containsKey(s)) {
            this.currentIterator = this.map.get(s).iterator();
        } else {
            this.expando.add(s);
            final List results = new ArrayList();
            PipeHelper.fillCollection(this.pipe, results);
            this.map.put(s, results);
            this.currentIterator = results.iterator();
        }
    }

    public List getPipes() {
        return (List) Arrays.asList(pipe);
    }

    public void reset() {
        this.currentIterator = PipeHelper.emptyIterator();
        try {
            this.map = this.map.getClass().getConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        super.reset();
    }

    public String toString() {
        return PipeHelper.makePipeString(this, this.pipe);
    }
}