Chapter 23
902
// Get the stock price
ObjectMessage objectMessage = (ObjectMessage)message;
Integer stockPrice = (Integer)objectMessage.getObject();
// Allow the user to input a purchase order
System.out.print("Do you want to buy stock <" + stockSymbol + "> at price "
+ stockPrice.toString() + "?\ny)es\nn)o\nq)uit\n:");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String msg = in.readLine();
System.out.println();
if(msg.equalsIgnoreCase("q")){
synchronized(this)
{
quit = true; // All done
this.notifyAll(); // Notify start() thread that we are quitting
return;
}
}
Because the PurchaserGuy chooses which queue to reply to based on the message header, it responds
to the destination the stock quote Publisher wishes it to respond to. If there are two StockGuys sending
quotes, the PurchaserGuy will always reply to the right one:
else if(msg.equalsIgnoreCase("y")){
// Get the queue that we should reply to
Queue replyQueue = (Queue)message.getJMSReplyTo();
// Find out how much the customer wishes to buy
System.out.print("enter the quantity:");
int stockQuantity = Integer.parseInt(in.readLine());
// Send the purchase order
sendPurchaseOrder(replyQueue,stockSymbol,stockQuantity);
}
}
catch(IOException e){
System.out.println("Caught IOException of: " + e.toString() );
}
catch(JMSException e){
System.out.println("Caught JMSException of: " + e.toString() );
}
}
private void sendPurchaseOrder(Queue queue, String stockSymbol, int
stockQuantity) throws JMSException
{
// Create a queue sender for the queue we are to send to
QueueSender queueSender = queueSession.createSender(queue);
// Create a purchase order
PurchaseOrder purchaseOrder = new PurchaseOrder(stockSymbol, stockQuantity);
ObjectMessage message = queueSession.createObjectMessage(purchaseOrder);