1 package be
.nikiroo
.jvcard
.remote
;
3 import java
.io
.BufferedReader
;
4 import java
.io
.BufferedWriter
;
6 import java
.io
.FileInputStream
;
7 import java
.io
.FileNotFoundException
;
8 import java
.io
.FileOutputStream
;
9 import java
.io
.IOException
;
10 import java
.io
.InputStreamReader
;
11 import java
.io
.OutputStreamWriter
;
12 import java
.net
.Socket
;
13 import java
.net
.UnknownHostException
;
14 import java
.security
.InvalidParameterException
;
15 import java
.util
.HashMap
;
16 import java
.util
.LinkedList
;
17 import java
.util
.List
;
20 import be
.nikiroo
.jvcard
.Card
;
21 import be
.nikiroo
.jvcard
.Contact
;
22 import be
.nikiroo
.jvcard
.Data
;
23 import be
.nikiroo
.jvcard
.launcher
.CardResult
;
24 import be
.nikiroo
.jvcard
.launcher
.CardResult
.MergeCallback
;
25 import be
.nikiroo
.jvcard
.parsers
.Format
;
26 import be
.nikiroo
.jvcard
.parsers
.Vcard21Parser
;
27 import be
.nikiroo
.jvcard
.resources
.StringUtils
;
28 import be
.nikiroo
.jvcard
.resources
.bundles
.RemoteBundle
;
29 import be
.nikiroo
.jvcard
.resources
.enums
.RemotingOption
;
32 * This class will synchronise {@link Card}s between a local instance an a
33 * remote jVCard server.
39 /** The time in ms after which we declare that 2 timestamps are different */
40 static private final int GRACE_TIME
= 2001;
42 /** Directory where to store local cache of remote {@link Card}s. */
43 static private File cacheDir
;
46 * Directory where to store cache of remote {@link Card}s without
47 * modifications since the last synchronisation.
49 static private File cacheDirOrig
;
50 /** Directory where to store timestamps for files in cacheDirOrig */
51 static private File cacheDirOrigTS
;
53 static private boolean autoSync
;
57 /** Resource name on the remote server. */
61 * Create a new {@link Sync} object, ready to operate for the given resource
62 * on the given server.
65 * Note that the format used is the standard "host:port_number/file", with
66 * an optional <tt>jvcard://</tt> prefix.
70 * E.g.: <tt>jvcard://localhost:4444/family.vcf</tt>
74 * the server and port to contact, optionally prefixed with
77 * @throws InvalidParameterException
78 * if the remote configuration file <tt>remote.properties</tt>
79 * cannot be accessed or if the cache directory cannot be used
81 public Sync(String url
) {
82 if (cacheDir
== null) {
87 url
= url
.replace("jvcard://", "");
88 int indexSl
= url
.indexOf('/');
89 this.name
= url
.substring(indexSl
+ 1);
90 url
= url
.substring(0, indexSl
);
91 this.host
= url
.split("\\:")[0];
92 this.port
= Integer
.parseInt(url
.split("\\:")[1]);
93 } catch (Exception e
) {
94 throw new InvalidParameterException(
95 "the given parameter was not a valid HOST:PORT value: "
101 * Create a new {@link Sync} object, ready to operate on the given server.
105 * the server to contact
109 * the resource name to synchronise to
111 public Sync(String host
, int port
, String name
) {
118 * Check if the remote server already know about this resource.
120 * @return TRUE if it is possible to contact the remote server and that this
121 * server has the resource available
123 public boolean isAvailable() {
125 SimpleSocket s
= new SimpleSocket(new Socket(host
, port
),
126 "check avail client");
128 s
.sendCommand(Command
.LIST_CARD
);
129 List
<String
> timestampedFiles
= s
.receiveBlock();
132 for (String timestampedFile
: timestampedFiles
) {
133 String file
= timestampedFile
.substring(StringUtils
.fromTime(0)
135 if (file
.equals(name
)) {
139 } catch (Exception e
) {
146 * Synchronise the current resource if needed, then return the locally
147 * cached version of said resource.
150 * A synchronisation is deemed necessary if one of the following is true:
152 * <li><tt>force</tt> is TRUE</li>
153 * <li><tt>CLIENT_AUTO_SYNC</tt> is TRUE in the configuration file</li>
154 * <li>the {@link Card} exists locally but not on the remote server</li>
155 * <li>the {@link Card} exists on the remote server but not locally</li>
160 * force the synchronisation to occur
162 * the {@link MergeCallback} to call in case of conflict
164 * @return the synchronised (or not) {@link Card}
166 * @throws UnknownHostException
167 * in case of server name resolution failure
168 * @throws IOException
169 * in case of IO error
171 public CardResult
sync(boolean force
, MergeCallback callback
)
172 throws UnknownHostException
, IOException
{
173 long tsOriginal
= getLastModified();
175 Card local
= new Card(getCache(cacheDir
), Format
.VCard21
);
177 // do NOT update unless we are in autoSync or forced mode or we don't
178 // have the file on cache
179 if (!autoSync
&& !force
&& tsOriginal
!= -1) {
180 return new CardResult(local
, true, false, false);
183 SimpleSocket s
= new SimpleSocket(new Socket(host
, port
), "sync client");
185 // get the server time stamp
187 boolean serverChanges
= false;
190 s
.sendCommand(Command
.LIST_CARD
);
191 List
<String
> timestampedFiles
= s
.receiveBlock();
193 for (String timestampedFile
: timestampedFiles
) {
194 String file
= timestampedFile
.substring(StringUtils
.fromTime(0)
196 if (file
.equals(name
)) {
197 tsServer
= StringUtils
.toTime(timestampedFile
.substring(0,
198 StringUtils
.fromTime(0).length()));
204 // - file not present neither in cache nor on server
205 // - remote < previous
206 if ((tsServer
== -1 && tsOriginal
== -1)
207 || (tsServer
!= -1 && tsOriginal
!= -1 && ((tsOriginal
- tsServer
) > GRACE_TIME
))) {
208 throw new IOException(
209 "The timestamps between server and client are invalid");
213 serverChanges
= (tsServer
- tsOriginal
) > GRACE_TIME
;
214 boolean localChanges
= false;
215 Card original
= null;
216 if (tsOriginal
!= -1) {
217 original
= new Card(getCache(cacheDirOrig
), Format
.VCard21
);
218 localChanges
= !local
.isEquals(original
, true);
221 Command action
= null;
223 // Sync to server if:
225 action
= Command
.PUT_CARD
;
228 // Sync from server if:
230 action
= Command
.HASH_CONTACT
;
233 // Sync from/to server if
234 if (serverChanges
&& localChanges
) {
235 action
= Command
.HELP
;
238 // POST the whole file if:
239 if (tsServer
== -1) {
240 action
= Command
.POST_CARD
;
243 // GET the whole file if:
244 if (tsOriginal
== -1) {
245 action
= Command
.GET_CARD
;
248 System
.err
.println("remote: " + (tsServer
/ 1000) % 1000 + " ("
250 System
.err
.println("previous: " + (tsOriginal
/ 1000) % 1000 + " ("
252 System
.err
.println("local changes: " + localChanges
);
253 System
.err
.println("server changes: " + serverChanges
);
254 System
.err
.println("choosen action: " + action
);
256 if (action
!= null) {
257 s
.sendCommand(Command
.SELECT
, name
);
258 if (tsServer
!= StringUtils
.toTime(s
.receiveLine())) {
259 System
.err
.println("DEBUG: it changed. retry.");
260 s
.sendCommand(Command
.SELECT
);
262 return sync(force
, callback
);
267 s
.sendCommand(Command
.GET_CARD
);
268 List
<String
> data
= s
.receiveBlock();
269 setLastModified(data
.remove(0));
270 local
.replaceListContent(Vcard21Parser
.parseContact(data
));
274 local
.saveAs(getCache(cacheDirOrig
), Format
.VCard21
);
278 s
.sendCommand(Command
.POST_CARD
);
279 s
.sendBlock(Vcard21Parser
.toStrings(local
));
280 local
.saveAs(getCache(cacheDirOrig
), Format
.VCard21
);
281 setLastModified(s
.receiveLine());
285 String serverLastModifTime
= updateToServer(s
, original
,
288 local
.saveAs(getCache(cacheDirOrig
), Format
.VCard21
);
290 setLastModified(serverLastModifTime
);
294 String serverLastModifTime
= updateFromServer(s
, local
);
297 local
.saveAs(getCache(cacheDirOrig
), Format
.VCard21
);
299 setLastModified(serverLastModifTime
);
303 // note: we are holding the server here, so it could throw
304 // us away if we take too long
306 // TODO: check if those files are deleted
307 File mergeF
= File
.createTempFile("contact-merge", ".vcf");
309 .createTempFile("contact-server", ".vcf");
310 original
.saveAs(serverF
, Format
.VCard21
);
312 Card server
= new Card(serverF
, Format
.VCard21
);
313 updateFromServer(s
, server
);
316 server
.saveAs(mergeF
, Format
.VCard21
);
317 Card merge
= new Card(mergeF
, Format
.VCard21
);
318 List
<Contact
> added
= new LinkedList
<Contact
>();
319 List
<Contact
> removed
= new LinkedList
<Contact
>();
320 original
.compare(local
, added
, removed
, removed
, added
);
321 for (Contact c
: removed
)
322 merge
.getById(c
.getId()).delete();
323 for (Contact c
: added
)
324 merge
.add(Vcard21Parser
.clone(c
));
329 if (callback
== null) {
330 throw new IOException(
331 "Conflicting changes detected and merge operation not allowed");
334 merge
= callback
.merge(original
, local
, server
, merge
);
336 throw new IOException(
337 "Conflicting changes detected and merge operation cancelled");
340 // TODO: something like:
341 // String serverLastModifTime = updateToServer(s, original,
343 // ...but without starting with original since it is not
345 s
.sendCommand(Command
.POST_CARD
);
346 s
.sendBlock(Vcard21Parser
.toStrings(merge
));
347 String serverLastModifTime
= s
.receiveLine();
350 merge
.saveAs(getCache(cacheDir
), Format
.VCard21
);
351 merge
.saveAs(getCache(cacheDirOrig
), Format
.VCard21
);
353 setLastModified(serverLastModifTime
);
364 s
.sendCommand(Command
.SELECT
);
366 } catch (IOException e
) {
367 return new CardResult(e
);
368 } catch (Exception e
) {
369 return new CardResult(new IOException(e
));
374 return new CardResult(local
, true, true, serverChanges
);
378 * Will update the currently selected {@link Card} on the remote server to
379 * be in the same state as <tt>local</tt>, assuming the server is currently
380 * in <tt>original</tt> state.
383 * the {@link SimpleSocket} to work on, which <b>MUST</b> be in
386 * the original {@link Card} as it was before the client made
389 * the {@link Card} to which state we want the server in
391 * @return the last modified time from the remote server (which is basically
394 * @throws IOException
395 * in case of IO error
397 private String
updateToServer(SimpleSocket s
, Card original
, Card local
)
399 List
<Contact
> added
= new LinkedList
<Contact
>();
400 List
<Contact
> removed
= new LinkedList
<Contact
>();
401 List
<Contact
> from
= new LinkedList
<Contact
>();
402 List
<Contact
> to
= new LinkedList
<Contact
>();
403 original
.compare(local
, added
, removed
, from
, to
);
405 s
.sendCommand(Command
.PUT_CARD
);
407 for (Contact c
: removed
) {
408 s
.sendCommand(Command
.DELETE_CONTACT
, c
.getId());
410 for (Contact c
: added
) {
411 s
.sendCommand(Command
.POST_CONTACT
, c
.getId());
412 s
.sendBlock(Vcard21Parser
.toStrings(c
, -1));
414 if (from
.size() > 0) {
415 for (int index
= 0; index
< from
.size(); index
++) {
416 Contact f
= from
.get(index
);
417 Contact t
= to
.get(index
);
419 List
<Data
> subadded
= new LinkedList
<Data
>();
420 List
<Data
> subremoved
= new LinkedList
<Data
>();
421 f
.compare(t
, subadded
, subremoved
, subremoved
, subadded
);
422 s
.sendCommand(Command
.PUT_CONTACT
, f
.getId());
423 for (Data d
: subremoved
) {
424 s
.sendCommand(Command
.DELETE_DATA
, d
.getContentState(true));
426 for (Data d
: subadded
) {
427 s
.sendCommand(Command
.POST_DATA
, d
.getContentState(true));
428 s
.sendBlock(Vcard21Parser
.toStrings(d
));
430 s
.sendCommand(Command
.PUT_CONTACT
);
434 s
.sendCommand(Command
.PUT_CARD
);
436 return s
.receiveLine();
440 * Will update the given {@link Card} object (not {@link File}) to the
441 * currently selected {@link Card} on the remote server.
444 * the {@link SimpleSocket} to work on, which <b>MUST</b> be in
447 * the {@link Card} to update
449 * @return the last modified time from the remote server
451 * @throws IOException
452 * in case of IO error
454 private String
updateFromServer(SimpleSocket s
, Card local
)
456 s
.sendCommand(Command
.PUT_CARD
);
458 s
.sendCommand(Command
.LIST_CONTACT
);
459 Map
<String
, String
> remote
= new HashMap
<String
, String
>();
460 for (String line
: s
.receiveBlock()) {
461 int indexSp
= line
.indexOf(" ");
462 String hash
= line
.substring(0, indexSp
);
463 String uid
= line
.substring(indexSp
+ 1);
465 remote
.put(uid
, hash
);
468 List
<Contact
> deleted
= new LinkedList
<Contact
>();
469 List
<Contact
> changed
= new LinkedList
<Contact
>();
470 List
<String
> added
= new LinkedList
<String
>();
472 for (Contact c
: local
) {
473 String hash
= remote
.get(c
.getId());
476 } else if (!hash
.equals(c
.getContentState(true))) {
481 for (String uid
: remote
.keySet()) {
482 if (local
.getById(uid
) == null)
488 for (Contact c
: deleted
) {
492 for (String uid
: added
) {
493 s
.sendCommand(Command
.GET_CONTACT
, uid
);
494 for (Contact cc
: Vcard21Parser
.parseContact(s
.receiveBlock())) {
499 for (Contact c
: changed
) {
501 s
.sendCommand(Command
.GET_CONTACT
, c
.getId());
502 for (Contact cc
: Vcard21Parser
.parseContact(s
.receiveBlock())) {
507 s
.sendCommand(Command
.PUT_CARD
);
509 return s
.receiveLine();
513 * Return the requested cache for the current resource.
518 * @return the cached {@link File}
520 private File
getCache(File dir
) {
521 return new File(dir
.getPath() + File
.separator
+ name
);
525 * Return the cached {@link File} corresponding to the current resource.
527 * @return the cached {@link File}
529 public File
getCache() {
530 return new File(cacheDir
.getPath() + File
.separator
+ name
);
534 * Get the last modified date of the current resource's original cached
535 * file, that is, the time the server reported as the "last modified time"
536 * when this resource was transfered.
538 * @return the last modified time from the server back when this resource
541 public long getLastModified() {
543 BufferedReader in
= new BufferedReader(new InputStreamReader(
544 new FileInputStream(cacheDirOrigTS
.getPath()
545 + File
.separator
+ name
)));
546 String line
= in
.readLine();
549 return StringUtils
.toTime(line
);
550 } catch (FileNotFoundException e
) {
552 } catch (Exception e
) {
558 * Set the last modified date of the current resource's original cached
559 * file, that is, the time the server reported as the "last modified time"
560 * when this resource was transfered.
563 * the last modified time from the server back when this resource
566 public void setLastModified(String time
) {
568 BufferedWriter out
= new BufferedWriter(new OutputStreamWriter(
569 new FileOutputStream(cacheDirOrigTS
.getPath()
570 + File
.separator
+ name
)));
574 } catch (FileNotFoundException e
) {
576 } catch (IOException e
) {
582 * Configure the synchronisation mechanism (cache, auto update...).
584 * @throws InvalidParameterException
585 * if the remote configuration file <tt>remote.properties</tt>
586 * cannot be accessed or if the cache directory cannot be used
588 static private void config() {
590 RemoteBundle bundle
= new RemoteBundle();
593 dir
= bundle
.getString(RemotingOption
.CLIENT_CACHE_DIR
);
595 cacheDir
= new File(dir
+ File
.separator
+ "current");
597 cacheDirOrig
= new File(dir
+ File
.separator
+ "original");
598 cacheDirOrig
.mkdir();
599 cacheDirOrigTS
= new File(dir
+ File
.separator
+ "timestamps");
600 cacheDirOrigTS
.mkdir();
602 if (!cacheDir
.exists() || !cacheDirOrig
.exists()) {
603 throw new IOException("Cannot open or create cache store at: "
608 .getBoolean(RemotingOption
.CLIENT_AUTO_SYNC
, false);
609 } catch (Exception e
) {
610 throw new InvalidParameterException(
611 "Cannot open or create cache store at: " + dir
);