1 package ca.uhn.hl7v2.conf.store;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.File;
6 import java.io.FileReader;
7 import java.io.FileWriter;
8 import java.io.IOException;
9
10 import org.slf4j.Logger;
11 import org.slf4j.LoggerFactory;
12
13
14
15
16
17
18
19 public class FileProfileStore implements ProfileStore {
20
21 private final File root;
22 private static final Logger log = LoggerFactory.getLogger(FileProfileStore.class);
23
24
25 public FileProfileStore(String theFile) {
26 root = new File(theFile);
27 if (root.exists()) {
28 if (!root.isDirectory()) {
29 log.warn("Profile store is not a directory (won't be able to retrieve any profiles): {}", theFile);
30 }
31 } else {
32 log.debug("Profile store directory doesn't exist: {}", theFile);
33 }
34 }
35
36
37
38
39
40 public String getProfile(String theID) throws IOException {
41 String profile = null;
42
43 String fileName = getFileName(theID);
44 File source = new File(fileName);
45 if (!source.exists()) {
46 log.debug("File for profile {} doesn't exist: {}", theID, fileName);
47 } else if (source.isFile()) {
48 BufferedReader in = new BufferedReader(new FileReader(source));
49 char[] buf = new char[(int) source.length()];
50 int check = in.read(buf, 0, buf.length);
51 in.close();
52 if (check != buf.length)
53 throw new IOException("Only read " + check + " of " + buf.length
54 + " bytes of file " + source.getAbsolutePath());
55 profile = new String(buf);
56 log.debug("Got profile {}: \r\n {}", theID, profile);
57 }
58 return profile;
59 }
60
61
62
63
64 public void persistProfile(String ID, String profile) throws IOException {
65 if (!root.exists()) {
66 throw new IOException("Can't persist profile. Directory doesn't exist: " + root.getAbsolutePath());
67 }
68 if (!root.isDirectory()) {
69 throw new IOException("Can't persist profile. Not a directory: " + root.getAbsolutePath());
70 }
71
72 File dest = new File(getFileName(ID));
73 BufferedWriter out = new BufferedWriter(new FileWriter(dest));
74 out.write(profile);
75 out.flush();
76 out.close();
77 }
78
79 private String getFileName(String ID) {
80 return root.getAbsolutePath() + "/" + ID + ".xml";
81 }
82 }