* returns the reply as a Message object. This method is thread-safe - multiple
* threads can share an Initiator and call this method. Responses are returned to
* the calling thread on the basis of message ID.
*/
public Message sendAndReceive(Message out) throws HL7Exception, LLPException, IOException {
HapiLog rawOutbound = HapiLogFactory.getHapiLog("ca.uhn.hl7v2.raw.outbound");
HapiLog rawInbound = HapiLogFactory.getHapiLog("ca.uhn.hl7v2.raw.inbound");
if (out == null) {
throw new HL7Exception("Can't encode null message", HL7Exception.REQUIRED_FIELD_MISSING);
}
//register message with response Receiver(s) (by message ID)
Terser t = new Terser(out);
String messID = t.get("/MSH-10");
if (messID == null || messID.length() == 0) {
throw new HL7Exception("MSH segment missing required field Control ID (MSH-10)", HL7Exception.REQUIRED_FIELD_MISSING);
}
MessageReceipt mr = this.conn.reserveResponse(messID);
//log and send message
String outbound = conn.getParser().encode(out);
log.info("Initiator sending message: " + outbound);
rawOutbound.info(outbound);
try {
this.conn.getSendWriter().writeMessage(outbound);
}
catch (IOException e) {
conn.close();
throw e;
}
//wait for response
boolean done = false;
Message response = null;
long startTime = System.currentTimeMillis();
while (!done) {
synchronized (mr) {
try {
mr.wait(500); //if it comes, notifyAll() will be called
}
catch (InterruptedException e) {
}
if (mr.getMessage() != null) {
//get message from receipt
String inbound = mr.getMessage();
//log that we got the message
log.info( "Initiator received message: " + inbound );
rawInbound.info(inbound);
//parse message
response = conn.getParser().parse(inbound);
log.debug("response parsed");
done = true;