further formatting changes
[jpim.git] / src / de / j32 / pimstuff / conduit / FritzAddressbookImporter.java
1 package de.j32.pimstuff.conduit;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5
6 import org.w3c.dom.Document;
7 import org.w3c.dom.Element;
8 import org.xml.sax.SAXException;
9
10 import de.j32.pimstuff.data.Entry;
11 import de.j32.pimstuff.data.EntryConsumer;
12 import de.j32.util.XmlUtil;
13
14 public class FritzAddressbookImporter implements Importer
15 {
16     Document xml_;
17
18     /**
19      * Importer reading Addressbook from Fritzbox XML file
20      * 
21      * @param is InputStream providing the XML data. <em>After successful</em>
22      *            construction, the class takes responsibility for closing the
23      *            stream.
24      * @throws SAXException
25      * @throws IOException
26      */
27     public FritzAddressbookImporter(InputStream is) throws SAXException, IOException
28     {
29         // It does not make sens to try / finally here, at least conceptually:
30         // Since the base-class constructor might throw we would never get a
31         // chance to // properly close is. Thus I deem it safer to only take
32         // responsibility for is when the constructor does NOT throw and place
33         // the try finally into the callers code.
34         xml_ = XmlUtil.parse(is);
35         is.close();
36     }
37
38     @Override
39     public void sendTo(EntryConsumer consumer)
40     {
41         for (Element node : XmlUtil.iterate(xml_.getElementsByTagName("contact"), Element.class)) {
42
43             // subnodes: category (unused, always 0) person/realName
44             // person/imageURL telephony/number (@prio, @type, @vanity)
45             // services/email mod_time
46             Entry entry = new Entry();
47
48             try {
49                 entry.name(node.getElementsByTagName("realName").item(0).getTextContent());
50
51                 for (Element phone : XmlUtil.iterate(node.getElementsByTagName("number"),
52                         Element.class)) {
53                     entry.attribute("phone", phone.getAttribute("type"), phone.getTextContent());
54                 }
55
56                 try {
57                     entry.attribute("email", "", node.getElementsByTagName("email").item(0)
58                             .getTextContent());
59                 }
60                 catch (NullPointerException e) {} // ignore missing optional
61                                                   // email
62             }
63             catch (NullPointerException e) {
64                 // Ignore incomplete entries
65                 entry = null;
66             }
67
68             if (entry != null) consumer.consume(entry);
69         }
70     }
71
72     @Override
73     public void close() throws IOException
74     {}
75
76 }