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()));
174 } catch (IOException e
) {
177 } catch (Exception e
) {
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");
193 boolean serverChanges
= (tsServer
- tsOriginal
) > GRACE_TIME
;
194 boolean localChanges
= false;
196 Card original
= null;
197 if (tsOriginal
!= -1) {
198 local
= new Card(getCache(cacheDir
), Format
.VCard21
);
199 original
= new Card(getCache(cacheDirOrig
), Format
.VCard21
);
200 localChanges
= !local
.isEquals(original
, true);
205 // Sync to server if:
207 action
= Verb
.PUT_CARD
;
210 // Sync from/to server if
211 if (serverChanges
&& localChanges
) {
212 action
= Verb
.PUT_CARD
;
215 // Sync from server if:
217 // TODO: only sends changed cstate if serverChanges
218 action
= Verb
.GET_CARD
;
221 // PUT the whole file if:
222 if (tsServer
== -1) {
223 action
= Verb
.POST_CARD
;
226 // GET the whole file if:
227 if (tsOriginal
== -1) {
228 action
= Verb
.GET_CARD
;
231 System
.err
.println("remote: " + (tsServer
/ 1000) % 1000 + " ("
233 System
.err
.println("previous: " + (tsOriginal
/ 1000) % 1000 + " ("
235 System
.err
.println("local changes: " + localChanges
);
236 System
.err
.println("server changes: " + serverChanges
);
237 System
.err
.println("choosen action: " + action
);
239 if (action
!= null) {
242 s
.sendCommand(Verb
.GET_CARD
, name
);
243 List
<String
> data
= s
.receiveBlock();
244 setLastModified(data
.remove(0));
245 Card server
= new Card(Vcard21Parser
.parseContact(data
));
246 card
.replaceListContent(server
);
250 card
.saveAs(getCache(cacheDirOrig
), Format
.VCard21
);
253 s
.sendCommand(Verb
.POST_CARD
, name
);
254 s
.sendBlock(Vcard21Parser
.toStrings(card
));
255 card
.saveAs(getCache(cacheDirOrig
), Format
.VCard21
);
256 setLastModified(s
.receiveLine());
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());
268 for (Contact c
: added
) {
269 s
.sendCommand(Verb
.POST_CONTACT
, c
.getId());
270 s
.sendBlock(Vcard21Parser
.toStrings(c
, -1));
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
);
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());
284 for (Data d
: subadded
) {
285 s
.sendCommand(Verb
.POST_DATA
, d
.getContentState());
286 s
.sendBlock(Vcard21Parser
.toStrings(d
));
290 s
.sendCommand(Verb
.PUT_CARD
);
294 throw new IOException(action
295 + " operation not supported yet :(");
305 * Return the requested cache for the current resource.
310 * @return the cached {@link File}
312 private File
getCache(File dir
) {
313 return new File(dir
.getPath() + File
.separator
+ name
);
317 * Return the cached {@link File} corresponding to the current resource.
319 * @return the cached {@link File}
321 public File
getCache() {
322 return new File(cacheDir
.getPath() + File
.separator
+ name
);
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.
330 * @return the last modified time from the server back when this resource
333 public long getLastModified() {
335 BufferedReader in
= new BufferedReader(new InputStreamReader(
336 new FileInputStream(cacheDirOrigTS
.getPath()
337 + File
.separator
+ name
)));
338 String line
= in
.readLine();
341 return StringUtils
.toTime(line
);
342 } catch (FileNotFoundException e
) {
344 } catch (Exception e
) {
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.
355 * the last modified time from the server back when this resource
358 public void setLastModified(String time
) {
360 BufferedWriter out
= new BufferedWriter(new OutputStreamWriter(
361 new FileOutputStream(cacheDirOrigTS
.getPath()
362 + File
.separator
+ name
)));
366 } catch (FileNotFoundException e
) {
368 } catch (IOException e
) {
374 * Configure the synchronisation mechanism (cache, auto update...).
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
380 static private void config() {
382 ResourceBundle bundle
= Bundles
.getBundle("remote");
385 dir
= bundle
.getString("CLIENT_CACHE_DIR").trim();
387 cacheDir
= new File(dir
+ File
.separator
+ "current");
389 cacheDirOrig
= new File(dir
+ File
.separator
+ "original");
390 cacheDirOrig
.mkdir();
391 cacheDirOrigTS
= new File(dir
+ File
.separator
+ "timestamps");
392 cacheDirOrigTS
.mkdir();
394 if (!cacheDir
.exists() || !cacheDirOrig
.exists()) {
395 throw new IOException("Cannot open or create cache store at: "
399 String autoStr
= bundle
.getString("CLIENT_AUTO_SYNC");
400 if (autoStr
!= null && autoStr
.trim().equalsIgnoreCase("true")) {
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
);