Add more warnings source to 1.6) and fix warnings
[jvcard.git] / src / be / nikiroo / jvcard / Contact.java
CommitLineData
a3b510ab
NR
1package be.nikiroo.jvcard;
2
26d2bd05
NR
3import java.io.File;
4import java.io.IOException;
5import java.util.ArrayList;
a3b510ab
NR
6import java.util.HashMap;
7import java.util.LinkedList;
8import java.util.List;
9import java.util.Map;
e253bd50 10import java.util.UUID;
a3b510ab
NR
11
12import be.nikiroo.jvcard.parsers.Format;
13import be.nikiroo.jvcard.parsers.Parser;
f06c8100 14import be.nikiroo.utils.StringUtils;
a3b510ab
NR
15
16/**
17 * A contact is the information that represent a contact person or organisation.
18 *
19 * @author niki
20 *
21 */
26d2bd05 22public class Contact extends BaseClass<Data> {
a3b510ab
NR
23 private int nextBKey = 1;
24 private Map<Integer, Data> binaries;
a3b510ab
NR
25
26 /**
27 * Create a new Contact from the given information. Note that the BKeys data
28 * will be reset.
29 *
30 * @param content
31 * the information about the contact
32 */
33 public Contact(List<Data> content) {
26d2bd05 34 super(load(content));
a3b510ab
NR
35 updateBKeys(true);
36 }
37
a3b510ab 38 /**
7671a249
NR
39 * Return the preferred Data field with the given name, the first one if
40 * none is preferred, or NULL if none at all.
a3b510ab
NR
41 *
42 * @param name
43 * the name to look for
7671a249
NR
44 *
45 * @return the {@link Data} field, or NULL
a3b510ab
NR
46 */
47 public Data getPreferredData(String name) {
7671a249
NR
48 Data pref = null;
49 int ipref = Integer.MAX_VALUE;
a3b510ab 50 for (Data data : getData(name)) {
7671a249
NR
51 if (pref == null)
52 pref = data;
3634193b 53
7671a249
NR
54 if (data.getPreferred() < ipref)
55 pref = data;
a3b510ab
NR
56 }
57
7671a249 58 return pref;
a3b510ab
NR
59 }
60
61 /**
62 * Return the value of the preferred data field with this name, or NULL if
63 * none (you cannot differentiate a NULL value and no value).
64 *
65 * @param name
66 * the name to look for
67 * @return the value (which can be NULL), or NULL
68 */
69 public String getPreferredDataValue(String name) {
70 Data data = getPreferredData(name);
71 if (data != null && data.getValue() != null)
72 return data.getValue().trim();
73 return null;
74 }
75
76 /**
77 * Get the Data fields that share the given name.
78 *
79 * @param name
80 * the name to ook for
81 * @return a list of Data fields with this name
82 */
83 public List<Data> getData(String name) {
84 List<Data> found = new LinkedList<Data>();
85
26d2bd05 86 for (Data data : this) {
a3b510ab
NR
87 if (data.getName().equals(name))
88 found.add(data);
89 }
90
91 return found;
92 }
93
0b0b2b0f
NR
94 /**
95 * Return a {@link String} representation of this contact formated
96 * accordingly to the given format.
97 *
26d254a3 98 * <p>
0b0b2b0f 99 * The format is basically a list of field names separated by a pipe and
30a4aa17
NR
100 * optionally parametrised with the 'at' (@) symbol. The parameters allows
101 * you to:
0b0b2b0f
NR
102 * <ul>
103 * <li>@x: show only a present/not present info</li>
104 * <li>@n: limit the size to a fixed value 'n'</li>
105 * <li>@+: expand the size of this field as much as possible</li>
106 * </ul>
26d254a3 107 * </p>
0b0b2b0f 108 *
26d254a3 109 * <p>
30a4aa17
NR
110 * In case of lists or multiple-fields values, you can select a specific
111 * list or field with:
112 * <ul>
113 * <li>FIELD@(0): select the first value in a list</li>
114 * <li>FIELD@[1]: select the second field in a multiple-fields value</li>
115 * </ul>
116 * </p>
117 *
118 * <p>
26d254a3
NR
119 * You can also add a fixed text if it starts with a simple-quote (').
120 * </p>
121 *
122 * <p>
123 * Example: "'Contact: |N@10|FN@20|NICK@+|PHOTO@x"
124 * </p>
0b0b2b0f
NR
125 *
126 * @param format
127 * the format to use
26d254a3
NR
128 * @param separator
129 * the separator {@link String} to use between fields
0b0b2b0f
NR
130 *
131 * @return the {@link String} representation
132 */
26d254a3 133 public String toString(String format, String separator) {
d5260eeb 134 return toString(format, separator, null, -1, true);
0b0b2b0f
NR
135 }
136
a3b510ab
NR
137 /**
138 * Return a {@link String} representation of this contact formated
139 * accordingly to the given format.
140 *
26d254a3 141 * <p>
a3b510ab
NR
142 * The format is basically a list of field names separated by a pipe and
143 * optionally parametrised. The parameters allows you to:
144 * <ul>
26d254a3 145 * <li>@x: show only a present/not present info</li>
a3b510ab
NR
146 * <li>@n: limit the size to a fixed value 'n'</li>
147 * <li>@+: expand the size of this field as much as possible</li>
148 * </ul>
26d254a3
NR
149 * </p>
150 *
151 * <p>
30a4aa17
NR
152 * In case of lists or multiple-fields values, you can select a specific
153 * list or field with:
154 * <ul>
155 * <li>FIELD@(0): select the first value in a list</li>
156 * <li>FIELD@[1]: select the second field in a multiple-fields value</li>
157 * </ul>
158 * </p>
159 *
160 * <p>
26d254a3
NR
161 * You can also add a fixed text if it starts with a simple-quote (').
162 * </p>
a3b510ab 163 *
26d254a3
NR
164 * <p>
165 * Example: "'Contact: |N@10|FN@20|NICK@+|PHOTO@x"
166 * </p>
a3b510ab
NR
167 *
168 * @param format
169 * the format to use
170 * @param separator
171 * the separator {@link String} to use between fields
0b0b2b0f
NR
172 * @param padding
173 * the {@link String} to use for left and right padding
a3b510ab
NR
174 * @param width
175 * a fixed width or -1 for "as long as needed"
296a0b75 176 * @param unicode
d5260eeb 177 * allow Unicode or only ASCII characters
296a0b75 178 *
a3b510ab
NR
179 * @return the {@link String} representation
180 */
0b0b2b0f 181 public String toString(String format, String separator, String padding,
d5260eeb 182 int width, boolean unicode) {
9c8baf0c 183 StringBuilder builder = new StringBuilder();
a3b510ab 184
296a0b75
NR
185 for (String str : toStringArray(format, separator, padding, width,
186 unicode)) {
0b0b2b0f
NR
187 builder.append(str);
188 }
a3b510ab 189
0b0b2b0f
NR
190 return builder.toString();
191 }
a3b510ab 192
0b0b2b0f
NR
193 /**
194 * Return a {@link String} representation of this contact formated
195 * accordingly to the given format, part by part.
196 *
26d254a3 197 * <p>
0b0b2b0f
NR
198 * The format is basically a list of field names separated by a pipe and
199 * optionally parametrised. The parameters allows you to:
200 * <ul>
201 * <li>@x: show only a present/not present info</li>
202 * <li>@n: limit the size to a fixed value 'n'</li>
203 * <li>@+: expand the size of this field as much as possible</li>
204 * </ul>
26d254a3 205 * </p>
0b0b2b0f 206 *
26d254a3 207 * <p>
30a4aa17
NR
208 * In case of lists or multiple-fields values, you can select a specific
209 * list or field with:
210 * <ul>
211 * <li>FIELD@(0): select the first value in a list</li>
212 * <li>FIELD@[1]: select the second field in a multiple-fields value</li>
213 * </ul>
214 * </p>
215 *
216 * <p>
26d254a3
NR
217 * You can also add a fixed text if it starts with a simple-quote (').
218 * </p>
219 *
220 * <p>
221 * Example: "'Contact: |N@10|FN@20|NICK@+|PHOTO@x"
222 * </p>
0b0b2b0f
NR
223 *
224 * @param format
225 * the format to use
226 * @param separator
227 * the separator {@link String} to use between fields
228 * @param padding
229 * the {@link String} to use for left and right padding
230 * @param width
231 * a fixed width or -1 for "as long as needed"
232 *
296a0b75
NR
233 * @param unicode
234 * allow Uniode or only ASCII characters
235 *
0b0b2b0f
NR
236 * @return the {@link String} representation
237 */
238 public String[] toStringArray(String format, String separator,
296a0b75 239 String padding, int width, boolean unicode) {
0b0b2b0f
NR
240 if (width > -1) {
241 int numOfFields = format.split("\\|").length;
242 if (separator != null)
243 width -= (numOfFields - 1) * separator.length();
244 if (padding != null)
245 width -= (numOfFields) * (2 * padding.length());
246
247 if (width < 0)
248 width = 0;
a3b510ab
NR
249 }
250
0b0b2b0f
NR
251 List<String> str = new LinkedList<String>();
252
253 boolean first = true;
296a0b75 254 for (String s : toStringArray(format, width, unicode)) {
0b0b2b0f
NR
255 if (!first) {
256 str.add(separator);
257 }
258
259 if (padding != null)
260 str.add(padding + s + padding);
261 else
262 str.add(s);
263
264 first = false;
9c8baf0c
NR
265 }
266
0b0b2b0f 267 return str.toArray(new String[] {});
9c8baf0c
NR
268 }
269
270 /**
271 * Return a {@link String} representation of this contact formated
272 * accordingly to the given format, part by part.
273 *
26d254a3 274 * <p>
9c8baf0c 275 * The format is basically a list of field names separated by a pipe and
0b0b2b0f
NR
276 * optionally parametrised. The parameters allows you to:
277 * <ul>
278 * <li>@x: show only a present/not present info</li>
279 * <li>@n: limit the size to a fixed value 'n'</li>
280 * <li>@+: expand the size of this field as much as possible</li>
281 * </ul>
26d254a3
NR
282 * </p>
283 *
284 * <p>
30a4aa17
NR
285 * In case of lists or multiple-fields values, you can select a specific
286 * list or field with:
287 * <ul>
288 * <li>FIELD@(0): select the first value in a list</li>
289 * <li>FIELD@[1]: select the second field in a multiple-fields value</li>
290 * </ul>
291 * </p>
292 *
293 * <p>
26d254a3
NR
294 * You can also add a fixed text if it starts with a simple-quote (').
295 * </p>
0b0b2b0f 296 *
26d254a3
NR
297 * <p>
298 * Example: "'Contact: |N@10|FN@20|NICK@+|PHOTO@x"
299 * </p>
9c8baf0c
NR
300 *
301 * @param format
302 * the format to use
303 * @param width
304 * a fixed width or -1 for "as long as needed"
296a0b75
NR
305 * @param unicode
306 * allow Uniode or only ASCII characters
d5260eeb 307 *
9c8baf0c
NR
308 * @return the {@link String} representation
309 */
296a0b75 310 public String[] toStringArray(String format, int width, boolean unicode) {
9c8baf0c
NR
311 List<String> str = new LinkedList<String>();
312
313 String[] formatFields = format.split("\\|");
314 String[] values = new String[formatFields.length];
315 Boolean[] expandedFields = new Boolean[formatFields.length];
316 Boolean[] fixedsizeFields = new Boolean[formatFields.length];
317 int numOfFieldsToExpand = 0;
318 int totalSize = 0;
319
320 if (width == 0) {
0b0b2b0f
NR
321 for (int i = 0; i < formatFields.length; i++) {
322 str.add("");
323 }
bcb54330 324
9c8baf0c
NR
325 return str.toArray(new String[] {});
326 }
327
a3b510ab
NR
328 for (int i = 0; i < formatFields.length; i++) {
329 String field = formatFields[i];
330
331 int size = -1;
332 boolean binary = false;
333 boolean expand = false;
30a4aa17
NR
334 int fieldNum = -1;
335 int valueNum = -1;
a3b510ab 336
26d254a3
NR
337 if (field.length() > 0 && field.charAt(0) != '\''
338 && field.contains("@")) {
a3b510ab
NR
339 String[] opts = field.split("@");
340 if (opts.length > 0)
341 field = opts[0];
342 for (int io = 1; io < opts.length; io++) {
343 String opt = opts[io];
344 if (opt.equals("x")) {
345 binary = true;
346 } else if (opt.equals("+")) {
347 expand = true;
348 numOfFieldsToExpand++;
30a4aa17
NR
349 } else if (opt.length() > 0 && opt.charAt(0) == '(') {
350 try {
351 opt = opt.substring(1, opt.length() - 1);
352 valueNum = Integer.parseInt(opt);
353 } catch (Exception e) {
354 }
355 } else if (opt.length() > 0 && opt.charAt(0) == '[') {
356 try {
357 opt = opt.substring(1, opt.length() - 1);
358 fieldNum = Integer.parseInt(opt);
359 } catch (Exception e) {
360 }
a3b510ab
NR
361 } else {
362 try {
363 size = Integer.parseInt(opt);
30a4aa17 364 } catch (NumberFormatException e) {
a3b510ab
NR
365 }
366 }
367 }
368 }
369
26d254a3
NR
370 String value = null;
371 if (field.length() > 0 && field.charAt(0) == '\'') {
372 value = field.substring(1);
30a4aa17
NR
373 } else if (valueNum >= 0) {
374 List<String> vv = getPreferredData(field).getValues();
375 if (valueNum < vv.size()) {
376 value = vv.get(valueNum);
377 }
378 } else if (fieldNum >= 0) {
379 List<String> ff = getPreferredData(field).getFields();
380 if (fieldNum < ff.size()) {
381 value = ff.get(fieldNum);
382 }
26d254a3 383 } else {
59597d59
NR
384 // we don't need the *data* in binary mode...
385 if (binary)
386 value = getData(field).size() > 0 ? "x" : null;
387 else
388 value = getPreferredDataValue(field);
26d254a3
NR
389 }
390
296a0b75 391 if (value == null) {
a3b510ab 392 value = "";
296a0b75
NR
393 } else {
394 value = StringUtils.sanitize(value, unicode);
395 }
a3b510ab
NR
396
397 if (size > -1) {
296a0b75 398 value = StringUtils.padString(value, size);
a3b510ab
NR
399 }
400
401 expandedFields[i] = expand;
402 fixedsizeFields[i] = (size > -1);
403
404 if (binary) {
405 if (value != null && !value.equals(""))
406 values[i] = "x";
407 else
408 values[i] = " ";
409 totalSize++;
410 } else {
411 values[i] = value;
412 totalSize += value.length();
413 }
414 }
9c8baf0c 415
a3b510ab
NR
416 if (width > -1 && totalSize > width) {
417 int toDo = totalSize - width;
418 for (int i = fixedsizeFields.length - 1; toDo > 0 && i >= 0; i--) {
419 if (!fixedsizeFields[i]) {
420 int valueLength = values[i].length();
421 if (valueLength > 0) {
422 if (valueLength >= toDo) {
423 values[i] = values[i].substring(0, valueLength
424 - toDo);
425 toDo = 0;
426 } else {
427 values[i] = "";
428 toDo -= valueLength;
429 }
430 }
431 }
432 }
433
434 totalSize = width + toDo;
435 }
9c8baf0c 436
a3b510ab
NR
437 if (width > -1 && numOfFieldsToExpand > 0) {
438 int availablePadding = width - totalSize;
439
440 if (availablePadding > 0) {
441 int padPerItem = availablePadding / numOfFieldsToExpand;
442 int remainder = availablePadding % numOfFieldsToExpand;
443
444 for (int i = 0; i < values.length; i++) {
445 if (expandedFields[i]) {
446 if (remainder > 0) {
296a0b75
NR
447 values[i] = values[i]
448 + StringUtils.padString("", remainder);
a3b510ab
NR
449 remainder = 0;
450 }
451 if (padPerItem > 0) {
296a0b75
NR
452 values[i] = values[i]
453 + StringUtils.padString("", padPerItem);
a3b510ab
NR
454 }
455 }
456 }
457
458 totalSize = width;
459 }
460 }
a3b510ab 461
9c8baf0c
NR
462 int currentSize = 0;
463 for (int i = 0; i < values.length; i++) {
464 currentSize += addToList(str, values[i], currentSize, width);
a3b510ab
NR
465 }
466
9c8baf0c 467 return str.toArray(new String[] {});
a3b510ab
NR
468 }
469
a3b510ab
NR
470 /**
471 * Update the information from this contact with the information in the
472 * given contact. Non present fields will be removed, new fields will be
473 * added, BKey'ed fields will be completed with the binary information known
474 * by this contact.
475 *
476 * @param vc
477 * the contact with the newer information and optional BKeys
478 */
479 public void updateFrom(Contact vc) {
480 updateBKeys(false);
481
26d2bd05 482 List<Data> newDatas = new LinkedList<Data>(vc);
a3b510ab
NR
483 for (int i = 0; i < newDatas.size(); i++) {
484 Data data = newDatas.get(i);
485 int bkey = Parser.getBKey(data);
486 if (bkey >= 0) {
487 if (binaries.containsKey(bkey)) {
488 newDatas.set(i, binaries.get(bkey));
489 }
490 }
491 }
492
26d2bd05 493 replaceListContent(newDatas);
a3b510ab 494 this.nextBKey = vc.nextBKey;
78e4af97
NR
495 }
496
e253bd50
NR
497 @Override
498 public String getId() {
499 return "" + getPreferredDataValue("UID");
500 }
501
502 @Override
503 public String getState() {
e4444b0b 504 return getId();
e253bd50
NR
505 }
506
78e4af97
NR
507 /**
508 * Return a {@link String} representation of this contact, in vCard 2.1,
509 * without BKeys.
510 *
511 * @return the {@link String} representation
512 */
513 @Override
514 public String toString() {
59597d59 515 return "[Contact: " + getPreferredDataValue("FN") + "]";
78e4af97
NR
516 }
517
a3b510ab
NR
518 /**
519 * Mark all the binary fields with a BKey number.
520 *
521 * @param force
522 * force the marking, and reset all the numbers.
523 */
524 protected void updateBKeys(boolean force) {
525 if (force) {
526 binaries = new HashMap<Integer, Data>();
527 nextBKey = 1;
528 }
529
530 if (binaries == null) {
531 binaries = new HashMap<Integer, Data>();
532 }
533
26d2bd05 534 for (Data data : this) {
a3b510ab
NR
535 if (data.isBinary() && (data.getB64Key() <= 0 || force)) {
536 binaries.put(nextBKey, data);
537 data.resetB64Key(nextBKey++);
538 }
539 }
540 }
541
a3b510ab 542 /**
26d2bd05
NR
543 * Load the data from the given {@link File} under the given {@link Format}.
544 *
545 * @param file
546 * the {@link File} to load from
547 * @param format
548 * the {@link Format} to load as
549 *
550 * @return the list of elements
551 * @throws IOException
552 * in case of IO error
a3b510ab 553 */
26d2bd05
NR
554 static private List<Data> load(List<Data> content) {
555 List<Data> datas = new ArrayList<Data>();
a3b510ab 556
26d2bd05
NR
557 boolean fn = false;
558 boolean n = false;
e253bd50 559 boolean uid = false;
26d2bd05
NR
560 if (content != null) {
561 for (Data data : content) {
562 if (data.getName().equals("N")) {
563 n = true;
564 } else if (data.getName().equals("FN")) {
565 fn = true;
e253bd50
NR
566 } else if (data.getName().equals("UID")) {
567 uid = true;
26d2bd05
NR
568 }
569
570 if (!data.getName().equals("VERSION")) {
571 datas.add(data);
572 }
573 }
78e4af97 574 }
78e4af97 575
26d2bd05 576 // required fields:
e253bd50 577 if (!n) // required since vCard 3.0, supported in 2.1
26d2bd05 578 datas.add(new Data(null, "N", "", null));
e253bd50 579 if (!fn) // not required anymore but still supported in 4.0
26d2bd05 580 datas.add(new Data(null, "FN", "", null));
e253bd50
NR
581 if (!uid) // supported by vCard, required by this program
582 datas.add(new Data(null, "UID", UUID.randomUUID().toString(), null));
26d2bd05
NR
583
584 return datas;
a3b510ab 585 }
296a0b75 586
bcb54330 587 /**
78e4af97
NR
588 * Add a {@link String} to the given {@link List}, but make sure it does not
589 * exceed the maximum size, and truncate it if needed to fit.
bcb54330 590 *
78e4af97
NR
591 * @param list
592 * @param add
593 * @param currentSize
594 * @param maxSize
595 * @return
bcb54330 596 */
78e4af97
NR
597 static private int addToList(List<String> list, String add,
598 int currentSize, int maxSize) {
599 if (add == null || add.length() == 0) {
600 if (add != null)
601 list.add(add);
602 return 0;
603 }
604
605 if (maxSize > -1) {
606 if (currentSize < maxSize) {
607 if (currentSize + add.length() >= maxSize) {
608 add = add.substring(0, maxSize - currentSize);
bcb54330 609 }
78e4af97
NR
610 } else {
611 add = "";
bcb54330
NR
612 }
613 }
614
78e4af97
NR
615 list.add(add);
616 return add.length();
bcb54330 617 }
a3b510ab 618}