65ab6fa5225b91fdacdd3430fdc52abdbb317395
[jvcard.git] / src / be / nikiroo / jvcard / Card.java
1 package be.nikiroo.jvcard;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.File;
6 import java.io.FileReader;
7 import java.io.FileWriter;
8 import java.io.IOException;
9 import java.util.Arrays;
10 import java.util.LinkedList;
11 import java.util.List;
12
13 import be.nikiroo.jvcard.parsers.Format;
14 import be.nikiroo.jvcard.parsers.Parser;
15
16 /**
17 * A card is a contact information card. It contains data about one or more
18 * contacts.
19 *
20 * @author niki
21 *
22 */
23 public class Card {
24 private List<Contact> contacts;
25 private File file;
26 private boolean dirty;
27 private String name;
28
29 public Card(File file, Format format) throws IOException {
30 this.file = file;
31
32 if (file != null) {
33 name = file.getName();
34 }
35
36 BufferedReader buffer = new BufferedReader(new FileReader(file));
37 List<String> lines = new LinkedList<String>();
38 for (String line = buffer.readLine(); line != null; line = buffer
39 .readLine()) {
40 lines.add(line);
41 }
42
43 load(lines, format);
44 dirty = false; // initial load, so no change yet
45 }
46
47 public List<Contact> getContacts() {
48 return contacts;
49 }
50
51 public boolean saveAs(File file, Format format) throws IOException {
52 if (file == null)
53 return false;
54
55 BufferedWriter writer = new BufferedWriter(new FileWriter(file));
56 writer.append(toString(format));
57 writer.close();
58
59 if (file.equals(this.file)) {
60 dirty = false;
61 }
62
63 return true;
64 }
65
66 public boolean save(Format format, boolean bKeys) throws IOException {
67 return saveAs(file, format);
68 }
69
70 public String toString(Format format) {
71 return Parser.toString(this, format);
72 }
73
74 public String toString() {
75 return toString(Format.VCard21);
76 }
77
78 protected void load(String serializedContent, Format format) {
79 // note: fixed size array
80 List<String> lines = Arrays.asList(serializedContent.split("\n"));
81 load(lines, format);
82 }
83
84 protected void load(List<String> lines, Format format) {
85 this.contacts = Parser.parse(lines, format);
86 setDirty();
87
88 for (Contact contact : contacts) {
89 contact.setParent(this);
90 }
91 }
92
93 public boolean isDirty() {
94 return dirty;
95 }
96
97 /**
98 * Return the name of this card.
99 *
100 * @return the name
101 */
102 public String getName() {
103 return name;
104 }
105
106 /**
107 * Notify that this element has unsaved changes.
108 */
109 void setDirty() {
110 dirty = true;
111 }
112 }