001    /*
002     * Created on Jun 25, 2005 @author paulk
003     */
004    package toolbus.atom.note;
005    
006    import java.util.Stack;
007    
008    import toolbus.State;
009    import toolbus.TBTermFactory;
010    import toolbus.atom.Atom;
011    import toolbus.atom.Ref;
012    import toolbus.exceptions.ToolBusException;
013    import toolbus.exceptions.ToolBusExecutionException;
014    import toolbus.matching.MatchStore;
015    import toolbus.parsercup.PositionInformation;
016    import toolbus.process.ProcessExpression;
017    import toolbus.process.ProcessInstance;
018    import aterm.ATerm;
019    
020    public class Subscribe extends Atom{
021            public final ATerm notePattern;
022            
023            public Subscribe(ATerm msgpat, TBTermFactory tbfactory, PositionInformation posInfo){
024                    super(tbfactory, posInfo);
025                    this.notePattern = msgpat;
026                    setAtomArgs(new Ref[]{new Ref(msgpat)});
027            }
028            
029            public ProcessExpression copy(){
030                    Atom a = new Subscribe(notePattern, tbfactory, getPosInfo());
031                    a.copyAtomAttributes(this);
032                    return a;
033            }
034            
035            public void compile(ProcessInstance pi, Stack<String> calls, State follow) throws ToolBusException{
036                    super.compile(pi, calls, follow);
037                    
038                    registerPartners();
039            }
040            
041            public void registerPartners(){
042                    MatchStore matchStore = getToolBus().getMatchStore();
043                    matchStore.registerSubscribeNote(this);
044            }
045            
046            public void destroy(){
047                    MatchStore matchStore = getToolBus().getMatchStore();
048                    matchStore.deregisterSubscribeNote(this);
049            }
050            
051            public ATerm getMatchPattern(){
052                    return notePattern;
053            }
054            
055            public boolean execute() throws ToolBusException{
056                    if(!isEnabled()) return false;
057                    
058                    ATerm subscribePattern = tbfactory.fullSubstitute(notePattern, getEnv());
059                    if(subscribePattern == null) throw new ToolBusExecutionException("Illegal subscription pattern: "+notePattern+".", getPosInfo());
060                    
061                    getProcess().subscribe(subscribePattern);
062                    return true;
063            }
064    }