/*
(c) Copyright 2008, 2009 Hewlett-Packard Development Company, LP
All rights reserved.
$Id$
*/
/*
(c) Copyright 2008 Hewlett-Packard Development Company, LP
All rights reserved.
$Id$
*/
package com.hp.jena.rules.retelike.impl;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.hp.jena.graph.Node;
import com.hp.jena.graph.Triple;
import com.hp.jena.ymris.util.Consumer;
/**
A Dispatcher consumes triples and directs them to the binders it has been
given. It may optimise by not considering binders that cannot accept the
triple. (This current implementation doesn't.)
@author kers
*/
public class Dispatcher implements Consumer<Triple>
{
protected final Set<Binder> allBinders = new HashSet<Binder>();
protected final Set<Binder> bindersWithWildcardPredicate = new HashSet<Binder>();
protected final Map<Node, Set<Binder>> mapByFixedPredicate = new HashMap<Node, Set<Binder>>();
static final Bindings<Node, Node> empty = new Bindings<Node, Node>();
/**
Initialise this Dispatcher with the set of binders it may forward
triples to.
*/
public Dispatcher( Set<Binder> binders )
{
allBinders.addAll( binders );
for (Binder b: binders) addBinderToAppropriateMap( b );
}
private void addBinderToAppropriateMap( Binder b )
{
TripleTerm boundTerm = b.boundTerm();
if (boundTerm != null)
{
NodeTerm predicate = boundTerm.getPredicate();
if (predicate.isVariable())
bindersWithWildcardPredicate.add( b );
else
{
Node p = predicate.subst( null, empty );
Set<Binder> bound = mapByFixedPredicate.get( p );
if (bound == null) mapByFixedPredicate.put( p, bound = new HashSet<Binder>() );
bound.add( b );
}
}
}
/**
Consume <i>item</i> by sending it to the binders that might accept
it, ie, any binders with variable predicates, and any binders
with fixed matching predicates.
@see com.hp.jena.ymris.util.Consumer#consume(java.lang.Object)
*/
public void consume( Triple item )
{
for (Binder b: bindersWithWildcardPredicate) b.consume( item );
Set<Binder> forPredicate = mapByFixedPredicate.get( item.getPredicate() );
if (forPredicate != null) for (Binder b: forPredicate) b.consume( item );
}
public void start()
{ for (Binder b: allBinders) b.start(); }
public void finish()
{ for (Binder b: allBinders) b.finish(); }
}
/*
(c) Copyright 2008, 2009 Hewlett-Packard Development Company, LP
All rights reserved.
$Id$
*/