001package ca.uhn.hl7v2.conf.store; 002 003import java.io.BufferedReader; 004import java.io.BufferedWriter; 005import java.io.File; 006import java.io.FileReader; 007import java.io.FileWriter; 008import java.io.IOException; 009 010import org.slf4j.Logger; 011import org.slf4j.LoggerFactory; 012 013/** 014 * Stores profiles in a local directory. Profiles are stored as text 015 * in files named ID.xml (where ID is the profile ID). 016 * @author Bryan Tripp 017 */ 018public class FileProfileStore implements ProfileStore { 019 020 private File root; 021 private static final Logger log = LoggerFactory.getLogger(FileProfileStore.class); 022 023 /** Creates a new instance of FileProfileStore */ 024 public FileProfileStore(String file) { 025 root = new File(file); 026 if (!root.isDirectory()) 027 if (!root.mkdirs()) 028 throw new IllegalArgumentException(file + " is not a directory"); 029 } 030 031 /** 032 * Retrieves profile from persistent storage (by ID). Returns null 033 * if the profile isn't found. 034 */ 035 public String getProfile(String ID) throws IOException { 036 String profile = null; 037 038 File source = new File(getFileName(ID)); 039 if (source.isFile()) { 040 BufferedReader in = new BufferedReader(new FileReader(source)); 041 char[] buf = new char[(int) source.length()]; 042 int check = in.read(buf, 0, buf.length); 043 in.close(); 044 if (check != buf.length) 045 throw new IOException("Only read " + check + " of " + buf.length 046 + " bytes of file " + source.getAbsolutePath()); 047 profile = new String(buf); 048 } 049 log.info("Got profile {}: \r\n {}", ID, profile); 050 return profile; 051 } 052 053 /** 054 * Stores profile in persistent storage with given ID. 055 */ 056 public void persistProfile(String ID, String profile) throws IOException { 057 File dest = new File(getFileName(ID)); 058 BufferedWriter out = new BufferedWriter(new FileWriter(dest)); 059 out.write(profile); 060 out.flush(); 061 out.close(); 062 } 063 064 private String getFileName(String ID) { 065 return root.getAbsolutePath() + "/" + ID + ".xml"; 066 } 067}