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
.LinkedList
;
16 import java
.util
.List
;
17 import java
.util
.MissingResourceException
;
18 import java
.util
.ResourceBundle
;
20 import be
.nikiroo
.jvcard
.Card
;
21 import be
.nikiroo
.jvcard
.Contact
;
22 import be
.nikiroo
.jvcard
.Data
;
23 import be
.nikiroo
.jvcard
.parsers
.Format
;
24 import be
.nikiroo
.jvcard
.parsers
.Vcard21Parser
;
25 import be
.nikiroo
.jvcard
.remote
.Command
.Verb
;
26 import be
.nikiroo
.jvcard
.resources
.Bundles
;
27 import be
.nikiroo
.jvcard
.resources
.StringUtils
;
30 * This class will synchronise {@link Card}s between a local instance an a
31 * remote jVCard server.
37 /** The time in ms after which we declare that 2 timestamps are different */
38 static private final int GRACE_TIME
= 2000;
40 /** Directory where to store local cache of remote {@link Card}s. */
41 static private File cacheDir
;
44 * Directory where to store cache of remote {@link Card}s without
45 * modifications since the last synchronisation.
47 static private File cacheDirOrig
;
48 /** Directory where to store timestamps for files in cacheDirOrig */
49 static private File cacheDirOrigTS
;
51 static private boolean autoSync
;
55 /** Resource name on the remote server. */
59 * Create a new {@link Sync} object, ready to operate for the given resource
60 * on the given server.
63 * Note that the format used is the standard "host:port_number/file", with
64 * an optional <tt>jvcard://</tt> prefix.
68 * E.g.: <tt>jvcard://localhost:4444/family.vcf</tt>
72 * the server and port to contact, optionally prefixed with
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
79 public Sync(String url
) {
80 if (cacheDir
== null) {
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: "
99 * Create a new {@link Sync} object, ready to operate on the given server.
103 * the server to contact
107 * the resource name to synchronise to
109 public Sync(String host
, int port
, String name
) {
116 * Check if the synchronisation is available for this resource.
118 * @return TRUE if it is possible to contact the remote server and that this
119 * server has the resource available
121 public boolean isAvailable() {
123 SimpleSocket s
= new SimpleSocket(new Socket(host
, port
),
124 "check avail client");
126 s
.sendCommand(Verb
.LIST
);
127 List
<String
> timestampedFiles
= s
.receiveBlock();
130 for (String timestampedFile
: timestampedFiles
) {
131 String file
= timestampedFile
.substring(StringUtils
.fromTime(0)
133 if (file
.equals(name
)) {
137 } catch (Exception e
) {
143 // return: synced or not
145 public boolean sync(Card card
, boolean force
) throws UnknownHostException
,
148 long tsOriginal
= getLastModified();
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) {
156 SimpleSocket s
= new SimpleSocket(new Socket(host
, port
), "sync client");
158 // get the server time stamp
162 s
.sendCommand(Verb
.LIST
);
163 List
<String
> timestampedFiles
= s
.receiveBlock();
165 for (String timestampedFile
: timestampedFiles
) {
166 String file
= timestampedFile
.substring(StringUtils
.fromTime(0)
168 if (file
.equals(name
)) {
169 tsServer
= StringUtils
.toTime(timestampedFile
.substring(0,
170 StringUtils
.fromTime(0).length()));
176 // - file not preset neither in cache nor on server
177 // - remote < previous
178 if ((tsServer
== -1 && tsOriginal
== -1)
179 || (tsServer
!= -1 && tsOriginal
!= -1 && ((tsOriginal
- tsServer
) > GRACE_TIME
))) {
180 throw new IOException(
181 "The timestamps between server and client are invalid");
185 boolean serverChanges
= (tsServer
- tsOriginal
) > GRACE_TIME
;
186 boolean localChanges
= false;
188 Card original
= null;
189 if (tsOriginal
!= -1) {
190 local
= new Card(getCache(cacheDir
), Format
.VCard21
);
191 original
= new Card(getCache(cacheDirOrig
), Format
.VCard21
);
192 localChanges
= !local
.isEquals(original
, true);
197 // Sync to server if:
199 action
= Verb
.PUT_CARD
;
202 // Sync from server if:
204 // TODO: only sends changed cstate if serverChanges
205 action
= Verb
.GET_CARD
;
208 // Sync from/to server if
209 if (serverChanges
&& localChanges
) {
214 // PUT the whole file if:
215 if (tsServer
== -1) {
216 action
= Verb
.POST_CARD
;
219 // GET the whole file if:
220 if (tsOriginal
== -1) {
221 action
= Verb
.GET_CARD
;
224 System
.err
.println("remote: " + (tsServer
/ 1000) % 1000 + " ("
226 System
.err
.println("previous: " + (tsOriginal
/ 1000) % 1000 + " ("
228 System
.err
.println("local changes: " + localChanges
);
229 System
.err
.println("server changes: " + serverChanges
);
230 System
.err
.println("choosen action: " + action
);
232 if (action
!= null) {
234 s
.sendCommand(Verb
.SELECT
, name
);
235 if (tsServer
!= StringUtils
.toTime(s
.receiveLine())) {
236 System
.err
.println("DEBUG: it changed. retry.");
237 s
.sendCommand(Verb
.SELECT
);
239 return sync(card
, force
);
244 s
.sendCommand(Verb
.GET_CARD
);
245 List
<String
> data
= s
.receiveBlock();
246 setLastModified(data
.remove(0));
247 Card server
= new Card(Vcard21Parser
.parseContact(data
));
248 card
.replaceListContent(server
);
252 card
.saveAs(getCache(cacheDirOrig
), Format
.VCard21
);
255 s
.sendCommand(Verb
.POST_CARD
);
256 s
.sendBlock(Vcard21Parser
.toStrings(card
));
257 card
.saveAs(getCache(cacheDirOrig
), Format
.VCard21
);
258 setLastModified(s
.receiveLine());
261 List
<Contact
> added
= new LinkedList
<Contact
>();
262 List
<Contact
> removed
= new LinkedList
<Contact
>();
263 List
<Contact
> from
= new LinkedList
<Contact
>();
264 List
<Contact
> to
= new LinkedList
<Contact
>();
265 original
.compare(local
, added
, removed
, from
, to
);
267 s
.sendCommand(Verb
.PUT_CARD
);
269 for (Contact c
: removed
) {
270 s
.sendCommand(Verb
.DELETE_CONTACT
, c
.getId());
272 for (Contact c
: added
) {
273 s
.sendCommand(Verb
.POST_CONTACT
, c
.getId());
274 s
.sendBlock(Vcard21Parser
.toStrings(c
, -1));
276 if (from
.size() > 0) {
277 for (int index
= 0; index
< from
.size(); index
++) {
278 Contact f
= from
.get(index
);
279 Contact t
= to
.get(index
);
281 List
<Data
> subadded
= new LinkedList
<Data
>();
282 List
<Data
> subremoved
= new LinkedList
<Data
>();
283 f
.compare(t
, subadded
, subremoved
, subremoved
,
285 s
.sendCommand(Verb
.PUT_CONTACT
, name
);
286 for (Data d
: subremoved
) {
287 s
.sendCommand(Verb
.DELETE_DATA
,
288 d
.getContentState());
290 for (Data d
: subadded
) {
291 s
.sendCommand(Verb
.POST_DATA
,
292 d
.getContentState());
293 s
.sendBlock(Vcard21Parser
.toStrings(d
));
298 s
.sendCommand(Verb
.PUT_CARD
);
302 throw new IOException(action
303 + " operation not supported yet :(");
306 s
.sendCommand(Verb
.SELECT
);
308 } catch (IOException e
) {
310 } catch (Exception e
) {
321 * Return the requested cache for the current resource.
326 * @return the cached {@link File}
328 private File
getCache(File dir
) {
329 return new File(dir
.getPath() + File
.separator
+ name
);
333 * Return the cached {@link File} corresponding to the current resource.
335 * @return the cached {@link File}
337 public File
getCache() {
338 return new File(cacheDir
.getPath() + File
.separator
+ name
);
342 * Get the last modified date of the current resource's original cached
343 * file, that is, the time the server reported as the "last modified time"
344 * when this resource was transfered.
346 * @return the last modified time from the server back when this resource
349 public long getLastModified() {
351 BufferedReader in
= new BufferedReader(new InputStreamReader(
352 new FileInputStream(cacheDirOrigTS
.getPath()
353 + File
.separator
+ name
)));
354 String line
= in
.readLine();
357 return StringUtils
.toTime(line
);
358 } catch (FileNotFoundException e
) {
360 } catch (Exception e
) {
366 * Set the last modified date of the current resource's original cached
367 * file, that is, the time the server reported as the "last modified time"
368 * when this resource was transfered.
371 * the last modified time from the server back when this resource
374 public void setLastModified(String time
) {
376 BufferedWriter out
= new BufferedWriter(new OutputStreamWriter(
377 new FileOutputStream(cacheDirOrigTS
.getPath()
378 + File
.separator
+ name
)));
382 } catch (FileNotFoundException e
) {
384 } catch (IOException e
) {
390 * Configure the synchronisation mechanism (cache, auto update...).
392 * @throws InvalidParameterException
393 * if the remote configuration file <tt>remote.properties</tt>
394 * cannot be accessed or if the cache directory cannot be used
396 static private void config() {
398 ResourceBundle bundle
= Bundles
.getBundle("remote");
401 dir
= bundle
.getString("CLIENT_CACHE_DIR").trim();
403 cacheDir
= new File(dir
+ File
.separator
+ "current");
405 cacheDirOrig
= new File(dir
+ File
.separator
+ "original");
406 cacheDirOrig
.mkdir();
407 cacheDirOrigTS
= new File(dir
+ File
.separator
+ "timestamps");
408 cacheDirOrigTS
.mkdir();
410 if (!cacheDir
.exists() || !cacheDirOrig
.exists()) {
411 throw new IOException("Cannot open or create cache store at: "
415 String autoStr
= bundle
.getString("CLIENT_AUTO_SYNC");
416 if (autoStr
!= null && autoStr
.trim().equalsIgnoreCase("true")) {
420 } catch (MissingResourceException e
) {
421 throw new InvalidParameterException(
422 "Cannot access remote.properties configuration file");
423 } catch (Exception e
) {
424 throw new InvalidParameterException(
425 "Cannot open or create cache store at: " + dir
);