package ca.uhn.hl7v2.util; import java.io.*; /** * Creates unique message IDs. IDs are stored in a file called /id_file for persistence * across JVM sessions. Note that if one day you run the JVM with a new working directory, * you must move or copy id_file into this directory so that new ID numbers will begin * with the last one used, rather than starting over again. * @author Neal Acharya */ public class MessageIDGenerator { private static MessageIDGenerator messageIdGenerator; private long id; private FileWriter fileW; private static final String idFile = Home.getHomeDirectory().getAbsolutePath() + "/id_file"; /** * Constructor * Creates an instance of the class * Its reads an id (longint#) from an external file, if one is not present then the external file * is created and initialized to zero. * This id is stored into the private field of id. */ private MessageIDGenerator() throws IOException { /*check external file for the last value unique id value generated by this class*/ try{ // We should check to see if the external file for storing the unique ids exists File extFile = new File(idFile); if (extFile.createNewFile()== true){ /*there was no existing file so a new one has been created with createNewFile method. The file is stored at /id_file.txt */ // We can simply initialize the private id field to zero id = 0; }//end if else{ /*The file does exist which is why we received false from the createNewFile method. We should now try to read from this file*/ FileReader fileR = new FileReader(idFile); char[] charArray = new char[100]; int e = fileR.read(charArray); if (e <= 0){ /*We know the file exists but it has no value stored in it. So at this point we can simply initialize the private id field to zero*/ id = 0; }//end if else{ /* Here we know that the file exists and has a stored value. we should read this value and set the private id field to it*/ String idStr = String.valueOf(charArray); String idStrTrim = idStr.trim(); id = Long.parseLong(idStrTrim); }//end else //Fix for bug 1100881: Close the file after writing. fileR.close(); }//end else }//end try catch (FileNotFoundException e){ System.out.println(e); }//end catch }//end constructor code /** * Synchronized method used to return the single (static) instance of the class */ public static synchronized MessageIDGenerator getInstance() throws IOException { if (messageIdGenerator == null) messageIdGenerator = new MessageIDGenerator(); return messageIdGenerator; }//end method /** * Synchronized method used to return the incremented id value */ public synchronized String getNewID()throws IOException{ //increment the private field id = id + 1; //create an instance of the Filewriter Object pointing to "C:\\extfiles\\Idfile.txt" fileW = new FileWriter(idFile, false); //write the id value to the file String idStr = String.valueOf(id); fileW.write(idStr); fileW.flush(); fileW.close(); return String.valueOf(id); }//end method }