/*
 Copyright 2005-2007 Matthew J. Battey

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software distributed
	under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
	CONDITIONS OF ANY KIND, either express or implied. See the License for the
	specific language governing permissions and limitations under the License.


This software implements a Java interface to SAFMQ (see http://safmq.sourceforge.net).

Created on Jun 3, 2005
*/

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URI;

import com.safmq.MQBuilder;
import com.safmq.MQException;
import com.safmq.MessageQueue;
import com.safmq.QueueMessage;
import com.safmq.Safmq;
import com.safmq.UUID;

/**
 * Note: this example expects a SAFMQ server to be running on the "localhost"
 * or same computer as the example is being run.  It also expects a user to exist
 * with the name "username" and password "password".  Additionally there should
 * be two queues "query" and "resposne", and the user "username" should have
 * read and write access to to this queue. 
 * 
 * @author Matt
 */
public class RoundTripClient {
    static URI queue_name;
    static URI response_name;
    static String user_name = "username";
    static String password = "password";

    static {
        try {
            queue_name = new URI("safmq://localhost/query");
            response_name = new URI("safmq://localhost/response");
        } catch (Exception e) {

        }
    }

    public static void main(String[] args) {
        try {
            // Allocate a connection to the query queue, this queue will be used to send the first message
            MessageQueue mq = MQBuilder.buildMessageQueue(queue_name,user_name,password);
            // Allocate the message itself
            QueueMessage    msg = new QueueMessage();

            // Set the type for the body so that clients may have a chance to understand what is in the boyd            
            msg.setBodyType(Safmq.BT_TEXT);
            // Set a name for the message, note this is optional, but some receivers
            // may choose an action depending on the name specified here
            msg.setLabel("Round Trip Test");
            // Set the time to live for the message, this value is the number of seconds
            // before the SAFMQ server will remove the message and generate an error
            msg.setTimeToLiveSeconds(5);
            // Indicate that this message should be responded to by the SAFMQ server
            msg.setTTLErrorWanted(true);
            // Indicate where the response message goes
            msg.setResponseQueueName(response_name.toString());
            // Get the output stream to fill the body.
            // In this case wrap it with a PrintWriter so that we can have formated output.
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(msg.getOutputStream()));

            pw.println("Hello world");
            pw.println("This is a test of the round trip capabilities of SAFMQ.");
            pw.flush(); // Not all output stream wrappers need this but it's good practice

            // Send the message and check the result code
            int error = mq.Enqueue(msg);
            // Close the queue we don't need it any more, this release resources on the server
            mq.Close();
            if (error == Safmq.EC_NOERROR) {
                // Grab this message's id  this will let us search for the resposne
                UUID id = msg.getMessageID();
                // Open a connection to the response queue
                MessageQueue responseQueue = MQBuilder.buildMessageQueue(response_name,user_name,password);

                // Get a fresh QueueMessage object
                msg = new QueueMessage();

                // Retreive the response message
                error = responseQueue.RetreiveID(true,id,10,msg);

                // Close the queue we don't need it any more, this release resources on the server
                responseQueue.Close();
                if (error == Safmq.EC_NOERROR) {
                    // Note: if the message class is Safmq.MC_SYSTEMERRMSG the message was generated by SAFMQ
                    if (msg.getMessageClass() == Safmq.MC_SYSTEMERRMSG) {
                        System.out.println("Received an error from the server");
                    }
                    // Output the contents of the emssage
                    System.out.println("Message Data Follows");
                    System.out.println("Label: " + msg.getLabel());
                    InputStream in = msg.getInputStream();
                    byte        data[] = new byte[1024];
                    int         read;
                    while ( (read=in.read(data)) > 0) {
                        System.out.write(data,0,read);
                    }
                } else {
                    System.out.println("Error while retreiving: "+Safmq.errorDecode(error));
                }
            } else {
                System.out.println("Error while enqueing: "+Safmq.errorDecode(error));
            }
        } catch (MQException mqe) {
            mqe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}