View Javadoc

1   package ca.uhn.hl7v2.examples;
2   
3   import java.io.FileNotFoundException;
4   import java.io.FileReader;
5   import java.io.IOException;
6   
7   import ca.uhn.hl7v2.DefaultHapiContext;
8   import ca.uhn.hl7v2.HL7Exception;
9   import ca.uhn.hl7v2.HapiContext;
10  import ca.uhn.hl7v2.app.Connection;
11  import ca.uhn.hl7v2.llp.LLPException;
12  import ca.uhn.hl7v2.model.Message;
13  import ca.uhn.hl7v2.util.Hl7InputStreamMessageIterator;
14  
15  public class SendLotsOfMessages {
16  
17  	public static void main(String[] args) throws FileNotFoundException, HL7Exception, LLPException {
18  		
19  		/*
20  		 * This example shows how to send lots of messages. Specifically it
21  		 * reads from a file, but that is not the only way to do this.
22  		 */
23  
24  		/*
25  		 * First set up a reader. 
26  		 *  
27  		 * message_file.txt is a file containing lots of ER7 encoded messages we are going to
28  		 * send out. 
29  		 */
30  		FileReader reader = new FileReader("message_file.txt");
31  		
32  		// Create an iterator to iterate over all the messages
33  		Hl7InputStreamMessageIterator iter = new Hl7InputStreamMessageIterator(reader);
34  		
35  		// Create a HapiContext
36  		HapiContext context = new DefaultHapiContext();
37  		
38  		Connection conn = null;
39  		while (iter.hasNext()) {
40  			
41  			/* If we don't already have a connection, create one.
42  			 * Note that unless something goes wrong, it's very common
43  			 * to keep reusing the same connection until we are done
44  			 * sending messages. Many systems keep a connection open
45  			 * even if a long period will pass between messages being
46  			 * sent. This is good practice, as it is much faster than
47  			 * creating a new connection each time. 
48  			 */ 
49  			if (conn == null) {
50  				boolean useTls = false;
51  				int port = 8888;
52  				conn = context.newClient("localhost", port, useTls);
53  			}
54  			
55  			try {
56  				Message next = iter.next();
57  				Message response = conn.getInitiator().sendAndReceive(next);
58  				System.out.println("Sent message. Response was " + response.encode());
59  			} catch (IOException e) {
60  				System.out.println("Didn't send out this message!");
61  				e.printStackTrace();
62  				
63  				// Since we failed, close the connection
64  				conn.close();
65  				conn = null;
66  				
67  			}
68  			
69  		}
70  		
71  	}
72  
73  }