//
// Std.java - The service, speaking in standard messages
//
// Receive a "standard deal" MapMessage from stddealq
// Send a "standard confirmation" BytesMessage to stdconfirmq
//

import java.util.*;
import java.io.*;
import javax.naming.*;
import javax.jms.*;

public class Std
  {
//...sreadFile:2:
public static String readFile(String fn)
  throws IOException
  {
  StringBuffer sb = new StringBuffer();
  BufferedReader br = new BufferedReader(new FileReader(fn));
  String line;
  while ( (line = br.readLine()) != null )
    {
    sb.append(line);
    sb.append("\n");
    }
  br.close();
  return sb.toString();
  }
//...e
  public static void main(String[] args)
    {
    try
      {
      // The JNDI we're going to store fetch JMS AOs from
      InitialContext ic = new InitialContext(
        new Hashtable<String,Object>()
          {{
          // Standard Qs are in a local Tibco EMS
          put(Context.INITIAL_CONTEXT_FACTORY, "com.tibco.tibjms.naming.TibjmsInitialContextFactory");
          put(Context.PROVIDER_URL, "tcp://localhost:7222");
          }}
        );

      QueueConnectionFactory qcf = (QueueConnectionFactory) ic.lookup("QueueConnectionFactory");
      QueueConnection qc = qcf.createQueueConnection("admin", "password");
      QueueSession qs = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      qc.start();

      javax.jms.Queue qDeal = (javax.jms.Queue) ic.lookup("stddealq");
      QueueReceiver r = qs.createReceiver(qDeal);

      javax.jms.Queue qConfirm = (javax.jms.Queue) ic.lookup("stdconfirmq");
      QueueSender s = qs.createSender(qConfirm);

      for ( int n = 0; ; n++ )
        {
        Message m = r.receive();
        if ( ! ( m instanceof MapMessage ) )
          System.out.println("!!! Ignoring non MapMessage "+n);
        else
          {
          MapMessage mDeal = (MapMessage) m;
          String textDeal = mDeal.getString("stdNode");
          if ( textDeal == null )
            System.out.println("!!! Ignoring MapMessage without stdNode "+n);
          else
            {
            System.out.println("=== RECEIVED STANDARD DEAL "+n+"\n"+textDeal);

            String textConfirm = readFile("StdConfirmation.xml");
            System.out.println("=== SENDING STANDARD CONFIRMATION "+n+"\n"+textConfirm);
            BytesMessage mConfirm = qs.createBytesMessage();
            mConfirm.writeUTF(textConfirm);
            mConfirm.setStringProperty("trade", "1234");
            s.send(mConfirm);
            }
          }
        }
      }  
    catch ( JMSException e )
      {
      e.printStackTrace();
      if ( e.getLinkedException() != null )
        {
        System.err.println("Linked Exception:");
        e.getLinkedException().printStackTrace();
        }
      }
    catch ( Exception e )
      {
      e.printStackTrace();
      }
    }
  }
