001    package stringtransformers;
002    
003    import cs101.lang.Animate;
004    import cs101.io.connection.*;
005    import cs101.io.Console;
006    import cs101.util.AnimateObject;
007    import cs101.util.gamecontrol.Initializable;
008    
009    public abstract class StringTransformer extends AnimateObject 
010                                            implements InputAcceptor, 
011                                                       OutputAcceptor,
012                                                       Initializable
013    {
014      protected InputConnection in;
015      protected OutputConnection out;
016    
017      // next field is for visualization, not functionality
018      protected TransformerVisualizer visualizer;
019    
020    
021      private static int instanceNumber;
022      private final int myIndex;
023    
024      public StringTransformer ()
025      {
026        super();
027    
028        this.myIndex = instanceNumber++;
029    
030        this.visualizer = new TransformerVisualizer( this );
031        this.visualizer.init();
032        Console.println(this + " created ");
033        
034      }
035    
036      public void init()
037      {
038      }
039    
040      public String toString()
041      {
042        return this.getClass().getName() + " #" + this.myIndex;
043      }
044    
045      public void addInputConnection( InputConnection in ) 
046           throws ConnectionRejectedException
047      {
048        if ( this.in != null )
049          {
050            throw new ConnectionRejectedException ( 
051                        this + ":  redundant input connection rejected" );
052          } 
053        else
054          {
055            this.in = this.visualizer.interceptInput( in );
056            Console.println( this + " added input connection ");
057          }
058      }
059    
060      public void addOutputConnection( OutputConnection out ) 
061           throws ConnectionRejectedException
062      {
063        if ( this.out != null )
064          {
065            throw new ConnectionRejectedException ( 
066                        this + ":  redundant output connection rejected" );
067          } 
068        else
069          {
070            this.out = this.visualizer.interceptOutput( out );
071            Console.println( this + " added output connection ");
072          }
073      }
074    
075      public void act () 
076      {
077        if ( ( this.in != null ) && ( this.out != null ) )
078          {
079            this.out.writeOutput( this.transform( this.in.readInput() ));
080          }
081      }
082    
083      public abstract String transform( String input );
084    
085    }
086