001package ca.uhn.hl7v2.util;
002
003import java.io.File;
004import java.io.FileNotFoundException;
005import java.io.FileReader;
006import java.io.FileWriter;
007import java.io.IOException;
008
009import org.slf4j.Logger;
010import org.slf4j.LoggerFactory;
011
012import ca.uhn.hl7v2.util.idgenerator.FileBasedHiLoGenerator;
013
014/**
015 * <p>
016 * Creates unique message IDs.  IDs are stored in a file called {@link Home#getHomeDirectory() hapi.home}/id_file for persistence
017 * across JVM sessions.  Note that if one day you run the JVM with a new working directory,
018 * you must move or copy id_file into this directory so that new ID numbers will begin
019 * with the last one used, rather than starting over again.
020 * </p>
021 * <p>
022 * Note that as of HAPI 2.0, by default this class will not fail even if the id_file can
023 * not be read/written. In this case, HAPI will try to fail gracefully by simply generating
024 * a numeric sequence starting at zero. This behaviour can be overwritten using 
025 * {@link #NEVER_FAIL_PROPERTY}
026 * </p>
027 * Also consider using {@link FileBasedHiLoGenerator} which provides better performance
028 * 
029 * 
030 * @author Neal Acharya
031 * @deprecated use one of the IDGenerator implementations
032 */
033public class MessageIDGenerator {
034    
035        private static final Logger ourLog = LoggerFactory.getLogger(MessageIDGenerator.class.getName());
036    private static MessageIDGenerator messageIdGenerator;
037    
038    /**
039     * Contains the complete path to the default ID file, which is a plain text file containing
040     * the number corresponding to the last generated ID
041     */
042    public final static String DEFAULT_ID_FILE = Home.getHomeDirectory().getAbsolutePath() + "/id_file";
043    
044    /**
045     * System property key which indicates that this class should never fail. If this
046     * system property is set to false (default is true), as in the following code:<br>
047     * <code>System.setProperty(MessageIDGenerator.NEVER_FAIL_PROPERTY, Boolean.FALSE.toString());</code><br>
048     * this class will fail if the underlying disk file can not be
049     * read or written. This means you are roughly guaranteed a unique
050     * ID number between JVM sessions (barring the file getting lost or corrupted). 
051     */
052    public static final String NEVER_FAIL_PROPERTY = MessageIDGenerator.class.getName() + "_NEVER_FAIL_PROPERTY";
053    
054    private long id;
055    private FileWriter fileW;
056    
057    /**
058     * Constructor
059     * Creates an instance of the class
060     * Its reads an id (longint#) from an external file, if one is not present then the external file
061     * is created and initialized to zero.
062     * This id is stored into the private field of id.
063     */
064    private  MessageIDGenerator() throws IOException {
065        initialize();
066    }//end constructor code
067
068    
069        /**
070         * Force the generator to re-load the ID file and initialize itself.
071         * 
072         * This method is mostly provided as a convenience to unit tests, and does
073         * not normally need to be called.
074         */
075    void initialize() throws IOException {
076        id = 0;
077        
078                /*check external file for the last value unique id value generated by
079        this class*/
080        try{
081            // We should check to see if the external file for storing the unique ids exists
082            File extFile = new File(DEFAULT_ID_FILE);
083            if (extFile.createNewFile()){
084                /*there was no existing file so a new one has been created with createNewFile method.  The
085                file is stored at  <hapi.home>/id_file.txt */
086                // We can simply initialize the private id field to zero
087                id = 0;
088                
089            }//end if
090            else{
091                /*The file does exist which is why we received false from the
092                createNewFile method. We should now try to read from this file*/
093                FileReader fileR = new FileReader(DEFAULT_ID_FILE);
094                char[] charArray = new char[100];
095                int e = fileR.read(charArray);
096                if (e <= 0){
097                    /*We know the file exists but it has no value stored in it. So at this point we can simply initialize the
098                    private id field to zero*/
099                    id = 0;
100                }//end if
101                else{
102                    /* Here we know that the file exists and has a stored value. we should read this value and set the
103                    private id field to it*/
104                    String idStr = String.valueOf(charArray);
105                    String idStrTrim = idStr.trim();
106                    
107                    try {
108                        id = Long.parseLong(idStrTrim);
109                    } catch (NumberFormatException nfe) {
110                        ourLog.warn("Failed to parse message ID file value \"" + idStrTrim + "\". Defaulting to 0.");
111                    }
112                    
113                }//end else
114                //Fix for bug 1100881:  Close the file after writing.
115                fileR.close();
116            }//end else
117        } catch (FileNotFoundException e) {
118            ourLog.error("Failed to locate message ID file. Message was: {}", e.getMessage());
119        } catch (IOException e) {
120            System.getProperty(NEVER_FAIL_PROPERTY, Boolean.TRUE.toString());
121            throw e;
122        }
123        }
124    
125    /**
126     * Synchronized method used to return the single (static) instance of the class
127     */
128    public static synchronized MessageIDGenerator getInstance() throws IOException {
129        if (messageIdGenerator == null)
130            messageIdGenerator = new MessageIDGenerator();
131        return messageIdGenerator;
132    }//end method
133    
134    /**
135     * Synchronized method used to return the incremented id value
136     */
137    public synchronized String getNewID() throws IOException{
138        try {
139                //increment the private field
140                id = id + 1;
141                //write the id value to the file
142                String idStr = String.valueOf(id);
143
144                //create an instance of the Filewriter Object pointing to "C:\\extfiles\\Idfile.txt"
145                fileW = new FileWriter(DEFAULT_ID_FILE, false);
146                fileW.write(idStr);
147                fileW.flush();
148                fileW.close();
149        } catch (FileNotFoundException e) {
150            System.getProperty(NEVER_FAIL_PROPERTY, Boolean.TRUE.toString());
151        } catch (IOException e) {
152            System.getProperty(NEVER_FAIL_PROPERTY, Boolean.TRUE.toString());
153            throw e;
154        }
155        return String.valueOf(id);
156    }//end method
157    
158}