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