New launcher class to start all 3 modes:
[jvcard.git] / src / be / nikiroo / jvcard / remote / Sync.java
CommitLineData
a046fa49
NR
1package be.nikiroo.jvcard.remote;
2
3import java.io.BufferedReader;
4import java.io.BufferedWriter;
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.FileNotFoundException;
8import java.io.FileOutputStream;
9import java.io.IOException;
10import java.io.InputStreamReader;
11import java.io.OutputStreamWriter;
12import java.net.Socket;
13import java.net.UnknownHostException;
14import java.security.InvalidParameterException;
0b6140e4 15import java.util.LinkedList;
a046fa49
NR
16import java.util.List;
17import java.util.MissingResourceException;
18import java.util.ResourceBundle;
19
20import be.nikiroo.jvcard.Card;
0b6140e4
NR
21import be.nikiroo.jvcard.Contact;
22import be.nikiroo.jvcard.Data;
a046fa49 23import be.nikiroo.jvcard.parsers.Format;
0b6140e4 24import be.nikiroo.jvcard.parsers.Vcard21Parser;
a046fa49
NR
25import be.nikiroo.jvcard.remote.Command.Verb;
26import be.nikiroo.jvcard.resources.Bundles;
7da41ecd 27import be.nikiroo.jvcard.resources.StringUtils;
a046fa49
NR
28
29/**
30 * This class will synchronise {@link Card}s between a local instance an a
31 * remote jVCard server.
32 *
33 * @author niki
34 *
35 */
36public class Sync {
37 /** The time in ms after which we declare that 2 timestamps are different */
38 static private final int GRACE_TIME = 2000;
39
40 /** Directory where to store local cache of remote {@link Card}s. */
41 static private File cacheDir;
42
43 /**
44 * Directory where to store cache of remote {@link Card}s without
45 * modifications since the last synchronisation.
46 */
47 static private File cacheDirOrig;
48 /** Directory where to store timestamps for files in cacheDirOrig */
49 static private File cacheDirOrigTS;
50
51 static private boolean autoSync;
52 private String host;
53 private int port;
54
55 /** Resource name on the remote server. */
56 private String name;
57
58 /**
59 * Create a new {@link Sync} object, ready to operate for the given resource
60 * on the given server.
61 *
62 * <p>
63 * Note that the format used is the standard "host:port_number/file", with
64 * an optional <tt>jvcard://</tt> prefix.
65 * </p>
66 *
67 * <p>
68 * E.g.: <tt>jvcard://localhost:4444/family.vcf</tt>
69 * </p>
70 *
71 * @param url
72 * the server and port to contact, optionally prefixed with
73 * <tt>jvcard://</tt>
74 *
75 * @throws InvalidParameterException
76 * if the remote configuration file <tt>remote.properties</tt>
77 * cannot be accessed or if the cache directory cannot be used
78 */
79 public Sync(String url) {
80 if (cacheDir == null) {
81 config();
82 }
83
84 try {
85 url = url.replace("jvcard://", "");
86 int indexSl = url.indexOf('/');
87 this.name = url.substring(indexSl + 1);
88 url = url.substring(0, indexSl);
89 this.host = url.split("\\:")[0];
90 this.port = Integer.parseInt(url.split("\\:")[1]);
91 } catch (Exception e) {
92 throw new InvalidParameterException(
93 "the given parameter was not a valid HOST:PORT value: "
94 + url);
95 }
96 }
97
98 /**
99 * Create a new {@link Sync} object, ready to operate on the given server.
100 *
101 *
102 * @param host
103 * the server to contact
104 * @param port
105 * the port to use
106 * @param name
107 * the resource name to synchronise to
108 */
109 public Sync(String host, int port, String name) {
110 this.host = host;
111 this.port = port;
112 this.name = name;
113 }
114
115 /**
116 * Check if the synchronisation is available for this resource.
117 *
118 * @return TRUE if it is possible to contact the remote server and that this
119 * server has the resource available
120 */
121 public boolean isAvailable() {
122 try {
123 SimpleSocket s = new SimpleSocket(new Socket(host, port),
124 "check avail client");
125 s.open(true);
126 s.sendCommand(Verb.LIST);
127 List<String> timestampedFiles = s.receiveBlock();
128 s.close();
129
130 for (String timestampedFile : timestampedFiles) {
131 String file = timestampedFile.substring(StringUtils.fromTime(0)
132 .length() + 1);
133 if (file.equals(name)) {
134 return true;
135 }
136 }
137 } catch (Exception e) {
138 }
139
140 return false;
141 }
142
143 // return: synced or not
7da41ecd 144 //TODO jDoc
a046fa49
NR
145 public boolean sync(Card card, boolean force) throws UnknownHostException,
146 IOException {
147
148 long tsOriginal = getLastModified();
149
150 // do NOT update unless we are in autoSync or forced mode or we don't
151 // have the file on cache
152 if (!autoSync && !force && tsOriginal != -1) {
153 return false;
154 }
155
156 SimpleSocket s = new SimpleSocket(new Socket(host, port), "sync client");
157
158 // get the server time stamp
159 long tsServer = -1;
160 try {
161 s.open(true);
162 s.sendCommand(Verb.LIST);
163 List<String> timestampedFiles = s.receiveBlock();
164
165 for (String timestampedFile : timestampedFiles) {
166 String file = timestampedFile.substring(StringUtils.fromTime(0)
167 .length() + 1);
168 if (file.equals(name)) {
169 tsServer = StringUtils.toTime(timestampedFile.substring(0,
170 StringUtils.fromTime(0).length()));
171 break;
172 }
173 }
174 } catch (IOException e) {
175 s.close();
176 throw e;
177 } catch (Exception e) {
178 e.printStackTrace();
179 s.close();
180 return false;
181 }
182
183 // Error cases:
184 // - file not preset neither in cache nor on server
185 // - remote < previous
186 if ((tsServer == -1 && tsOriginal == -1)
187 || (tsServer != -1 && tsOriginal != -1 && ((tsOriginal - tsServer) > GRACE_TIME))) {
188 throw new IOException(
189 "The timestamps between server and client are invalid");
190 }
191
192 // Check changes
193 boolean serverChanges = (tsServer - tsOriginal) > GRACE_TIME;
194 boolean localChanges = false;
0b6140e4
NR
195 Card local = null;
196 Card original = null;
a046fa49 197 if (tsOriginal != -1) {
0b6140e4
NR
198 local = new Card(getCache(cacheDir), Format.VCard21);
199 original = new Card(getCache(cacheDirOrig), Format.VCard21);
cf77cb35 200 localChanges = !local.isEquals(original, true);
a046fa49
NR
201 }
202
203 Verb action = null;
204
205 // Sync to server if:
206 if (localChanges) {
0b6140e4 207 action = Verb.PUT_CARD;
a046fa49
NR
208 }
209
0b6140e4 210 // Sync from/to server if
a046fa49 211 if (serverChanges && localChanges) {
0b6140e4
NR
212 action = Verb.PUT_CARD;
213 }
214
215 // Sync from server if:
216 if (serverChanges) {
217 // TODO: only sends changed cstate if serverChanges
218 action = Verb.GET_CARD;
a046fa49
NR
219 }
220
221 // PUT the whole file if:
222 if (tsServer == -1) {
0b6140e4 223 action = Verb.POST_CARD;
a046fa49
NR
224 }
225
226 // GET the whole file if:
0b6140e4
NR
227 if (tsOriginal == -1) {
228 action = Verb.GET_CARD;
a046fa49
NR
229 }
230
231 System.err.println("remote: " + (tsServer / 1000) % 1000 + " ("
232 + tsServer + ")");
233 System.err.println("previous: " + (tsOriginal / 1000) % 1000 + " ("
234 + tsOriginal + ")");
235 System.err.println("local changes: " + localChanges);
236 System.err.println("server changes: " + serverChanges);
237 System.err.println("choosen action: " + action);
238
239 if (action != null) {
240 switch (action) {
0b6140e4
NR
241 case GET_CARD:
242 s.sendCommand(Verb.GET_CARD, name);
a046fa49
NR
243 List<String> data = s.receiveBlock();
244 setLastModified(data.remove(0));
0b6140e4 245 Card server = new Card(Vcard21Parser.parseContact(data));
a046fa49 246 card.replaceListContent(server);
cf77cb35 247
a046fa49
NR
248 if (card.isDirty())
249 card.save();
250 card.saveAs(getCache(cacheDirOrig), Format.VCard21);
251 break;
0b6140e4
NR
252 case POST_CARD:
253 s.sendCommand(Verb.POST_CARD, name);
254 s.sendBlock(Vcard21Parser.toStrings(card));
cf77cb35
NR
255 card.saveAs(getCache(cacheDirOrig), Format.VCard21);
256 setLastModified(s.receiveLine());
a046fa49 257 break;
0b6140e4
NR
258 case PUT_CARD:
259 List<Contact> added = new LinkedList<Contact>();
260 List<Contact> removed = new LinkedList<Contact>();
261 List<Contact> from = new LinkedList<Contact>();
262 List<Contact> to = new LinkedList<Contact>();
263 original.compare(local, added, removed, from, to);
264 s.sendCommand(Verb.PUT_CARD, name);
265 for (Contact c : removed) {
266 s.sendCommand(Verb.DELETE_CONTACT, c.getId());
267 }
268 for (Contact c : added) {
269 s.sendCommand(Verb.POST_CONTACT, c.getId());
270 s.sendBlock(Vcard21Parser.toStrings(c, -1));
271 }
272 if (from.size() > 0) {
273 for (int index = 0; index < from.size(); index++) {
274 Contact f = from.get(index);
275 Contact t = to.get(index);
276
277 List<Data> subadded = new LinkedList<Data>();
278 List<Data> subremoved = new LinkedList<Data>();
279 f.compare(t, subadded, subremoved, subremoved, subadded);
280 s.sendCommand(Verb.PUT_CONTACT, name);
281 for (Data d : subremoved) {
282 s.sendCommand(Verb.DELETE_DATA, d.getContentState());
283 }
284 for (Data d : subadded) {
285 s.sendCommand(Verb.POST_DATA, d.getContentState());
286 s.sendBlock(Vcard21Parser.toStrings(d));
287 }
288 }
289 }
290 s.sendCommand(Verb.PUT_CARD);
291 break;
a046fa49
NR
292 default:
293 // TODO
294 throw new IOException(action
295 + " operation not supported yet :(");
296 }
297 }
298
299 s.close();
300
301 return true;
302 }
303
304 /**
305 * Return the requested cache for the current resource.
306 *
307 * @param dir
308 * the cache to use
309 *
310 * @return the cached {@link File}
311 */
312 private File getCache(File dir) {
313 return new File(dir.getPath() + File.separator + name);
314 }
315
316 /**
317 * Return the cached {@link File} corresponding to the current resource.
318 *
319 * @return the cached {@link File}
320 */
321 public File getCache() {
322 return new File(cacheDir.getPath() + File.separator + name);
323 }
324
325 /**
326 * Get the last modified date of the current resource's original cached
327 * file, that is, the time the server reported as the "last modified time"
328 * when this resource was transfered.
329 *
330 * @return the last modified time from the server back when this resource
331 * was transfered
332 */
333 public long getLastModified() {
334 try {
335 BufferedReader in = new BufferedReader(new InputStreamReader(
336 new FileInputStream(cacheDirOrigTS.getPath()
337 + File.separator + name)));
338 String line = in.readLine();
339 in.close();
340
341 return StringUtils.toTime(line);
342 } catch (FileNotFoundException e) {
343 return -1;
cf77cb35 344 } catch (Exception e) {
a046fa49
NR
345 return -1;
346 }
347 }
348
349 /**
350 * Set the last modified date of the current resource's original cached
351 * file, that is, the time the server reported as the "last modified time"
352 * when this resource was transfered.
353 *
354 * @param time
355 * the last modified time from the server back when this resource
356 * was transfered
357 */
358 public void setLastModified(String time) {
359 try {
360 BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
361 new FileOutputStream(cacheDirOrigTS.getPath()
362 + File.separator + name)));
363 out.append(time);
364 out.newLine();
365 out.close();
366 } catch (FileNotFoundException e) {
367 e.printStackTrace();
368 } catch (IOException e) {
369 e.printStackTrace();
370 }
371 }
372
373 /**
374 * Configure the synchronisation mechanism (cache, auto update...).
375 *
376 * @throws InvalidParameterException
377 * if the remote configuration file <tt>remote.properties</tt>
378 * cannot be accessed or if the cache directory cannot be used
379 */
380 static private void config() {
381 String dir = null;
382 ResourceBundle bundle = Bundles.getBundle("remote");
383
384 try {
385 dir = bundle.getString("CLIENT_CACHE_DIR").trim();
386
387 cacheDir = new File(dir + File.separator + "current");
388 cacheDir.mkdir();
389 cacheDirOrig = new File(dir + File.separator + "original");
390 cacheDirOrig.mkdir();
391 cacheDirOrigTS = new File(dir + File.separator + "timestamps");
392 cacheDirOrigTS.mkdir();
393
394 if (!cacheDir.exists() || !cacheDirOrig.exists()) {
395 throw new IOException("Cannot open or create cache store at: "
396 + dir);
397 }
398
399 String autoStr = bundle.getString("CLIENT_AUTO_SYNC");
400 if (autoStr != null && autoStr.trim().equalsIgnoreCase("true")) {
401 autoSync = true;
402 }
403
404 } catch (MissingResourceException e) {
405 throw new InvalidParameterException(
406 "Cannot access remote.properties configuration file");
407 } catch (Exception e) {
408 throw new InvalidParameterException(
409 "Cannot open or create cache store at: " + dir);
410 }
411 }
412}