/**
 * EchoMessageHandler is a class that repeats back the message it is
 * sent.  The message must be in the following format:
 * <br>
 * ECHO message
 * <br>
 * This source code is copyright 2005 by Patrick May.  All
 * rights reserved.
 *
 * @author Patrick May (patrick@softwarematters.org)
 * @author &copy; 2005 Patrick May.  All rights reserved.
 * @version 1
 */

package org.softwarematters.example.MessageBroker;

import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.io.PrintWriter;
import java.io.IOException;

public class EchoMessageHandler extends MessageHandler
{
  private static Logger logger_
    = Logger.getLogger(EchoMessageHandler.class.getName());
  private static Pattern pattern_ = Pattern.compile("ECHO (.*)$");

  String message_ = null;

  /**
   * The full constructor for the EchoMessageHandler class.
   *
   * @param message The message to use to attempt to construct an
   *                EchoMessageHandler instance.
   */
  public EchoMessageHandler(String message)
    throws UnknownMessageFormatException
    {
    super(message);

    Matcher matcher = pattern_.matcher(message);
    if (matcher.matches())
      {
      message_ = matcher.group(1);
      logger_.info("Parsed message:  " + message_);
      }
    else
      throw new UnknownMessageFormatException(message);
    }


  /**
   * Handle the message.
   *
   * @param context The context in which the handler has been invoked.
   */
  public void handleMessage(MessageHandlerContext context)
    {
    PrintWriter output = new PrintWriter(context.outputStream());
    output.println(message_);
    output.flush();
    }


  /**
   * A test harness for the EchoMessageHandler class.
   *
   * @param args The command line arguments passed in.
   */
  public static void main(String args[])
    {
    if (args.length == 1)
      {
      try
        {
        EchoMessageHandler handler
          = new EchoMessageHandler(args[0]);
        }
      catch (UnknownMessageFormatException e)
        {
        System.out.println("Bad format:  " + e.toString());
        }
      }
    else
      System.out.println(
        "usage:  java " + EchoMessageHandler.class.getName() + " <message>");
    }  // end EchoMessageHandler::main(String[])
}  // end EchoMessageHandler

