1 package org.apache.helix.filestore;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.File;
23 import java.io.FileWriter;
24 import java.io.IOException;
25
26 import org.apache.commons.io.FileUtils;
27
28 public class CheckpointFile
29 {
30 private static final String TEMP = ".bak";
31 private static String CHECK_POINT_FILE = "lastprocessedchange.checkpoint";
32
33 private String checkpointDirPath;
34
35 public CheckpointFile(String checkpointDirPath) throws IOException
36 {
37 this.checkpointDirPath = checkpointDirPath;
38 File checkpointdir = new File(checkpointDirPath);
39 if (!checkpointdir.exists() && !checkpointdir.mkdirs())
40 {
41 throw new IOException("unable to create SCN file parent:"
42 + checkpointdir.getAbsolutePath());
43 }
44 }
45
46 public void checkpoint(ChangeRecord lastRecordProcessed) throws Exception
47 {
48
49
50 File tempCheckpointFile = new File(checkpointDirPath + "/" + CHECK_POINT_FILE
51 + TEMP);
52 if (tempCheckpointFile.exists() && !tempCheckpointFile.delete())
53 {
54 System.err.println("unable to erase temp SCN file: "
55 + tempCheckpointFile.getAbsolutePath());
56 }
57
58 String checkpointFileName = checkpointDirPath + "/" + CHECK_POINT_FILE;
59 File checkpointfile = new File(checkpointFileName);
60 if (checkpointfile.exists() && !checkpointfile.renameTo(tempCheckpointFile))
61 {
62 System.err.println("unable to backup scn file");
63 }
64 if (!checkpointfile.createNewFile())
65 {
66 System.err.println("unable to create new SCN file:"
67 + checkpointfile.getAbsolutePath());
68 }
69 FileWriter writer = new FileWriter(checkpointfile);
70 writer.write(lastRecordProcessed.toString());
71 writer.flush();
72 writer.close();
73 System.out.println("scn persisted: " + lastRecordProcessed.txid);
74
75 }
76
77 public ChangeRecord findLastRecordProcessed()
78 {
79 String checkpointFileName = checkpointDirPath + "/" + CHECK_POINT_FILE;
80 File file = new File(checkpointFileName);
81 ChangeRecord record = null;
82 if (file.exists())
83 {
84 try
85 {
86 String line = FileUtils.readFileToString(file);
87 record = ChangeRecord.fromString(line);
88 } catch (IOException e)
89 {
90 e.printStackTrace();
91 }
92 }
93 return record;
94 }
95 }