1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.id.uuid.state;
19
20 import java.io.File;
21 import java.io.FileWriter;
22 import java.io.IOException;
23 import java.net.URL;
24 import java.util.Iterator;
25 import java.util.Set;
26
27
28
29
30
31
32
33
34
35
36 public class ReadWriteFileStateImpl extends ReadOnlyResourceStateImpl implements State {
37
38
39
40
41
42
43 public void store(Set nodes) throws IOException {
44 writeXML(genXML(nodes));
45 }
46
47
48
49
50
51
52
53
54 private String genXML(Set nodes) throws IOException {
55 Iterator it = nodes.iterator();
56 StringBuffer buf = new StringBuffer(1024);
57 buf.append(StateHelper.XML_DOC_START);
58 buf.append(getSynchInterval());
59 buf.append(StateHelper.XML_DOC_START_END);
60 while (it.hasNext()) {
61 Node n = (Node) it.next();
62 buf.append(StateHelper.XML_NODE_TAG_START);
63 buf.append(StateHelper.encodeMACAddress(n.getNodeIdentifier()));
64 buf.append(StateHelper.XML_NODE_TAG_AFTER_ID);
65 buf.append(n.getClockSequence());
66 buf.append(StateHelper.XML_NODE_TAG_AFTER_CSEQ);
67 buf.append(n.getLastTimestamp());
68 buf.append(StateHelper.XML_NODE_TAG_END);
69 }
70 buf.append(StateHelper.XML_DOC_END);
71 return buf.toString();
72 }
73
74
75
76
77
78
79
80
81
82 private String genXML(Set nodes, long timestamp) throws IOException {
83 Iterator it = nodes.iterator();
84 StringBuffer buf = new StringBuffer(1024);
85 buf.append(StateHelper.XML_DOC_START);
86 buf.append(getSynchInterval());
87 buf.append(StateHelper.XML_DOC_START_END);
88 while (it.hasNext()) {
89 Node n = (Node) it.next();
90 buf.append(StateHelper.XML_NODE_TAG_START);
91 buf.append(StateHelper.encodeMACAddress(n.getNodeIdentifier()));
92 buf.append(StateHelper.XML_NODE_TAG_AFTER_ID);
93 buf.append(n.getClockSequence());
94 buf.append(StateHelper.XML_NODE_TAG_AFTER_CSEQ);
95 buf.append(timestamp);
96 buf.append(StateHelper.XML_NODE_TAG_END);
97 }
98 buf.append(StateHelper.XML_DOC_END);
99 return buf.toString();
100 }
101
102
103
104
105
106
107 private void writeXML(String xml) {
108 String resourceName = System.getProperty(CONFIG_FILENAME_KEY);
109 if (resourceName == null) {
110 return;
111 } else {
112 URL rUrl = ClassLoader.getSystemResource(resourceName);
113 if (rUrl != null) {
114 File file = new File(rUrl.getFile());
115 if (file != null && file.canWrite()) {
116 FileWriter fw = null;
117 try {
118 fw = new FileWriter(file);
119 fw.write(xml);
120 fw.close();
121 } catch (IOException ioe) {
122
123 } finally {
124 try {
125 fw.close();
126 } catch (IOException ioee) {
127 ;
128 }
129 fw = null;
130 file = null;
131 }
132 }
133 }
134 }
135 }
136 }