summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/opml/OpmlReader.java
blob: 6f16a8f344497360a889c5adc68b744f8085daaf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package de.danoeh.antennapod.opml;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;
import de.danoeh.antennapod.AppConfig;

/** Reads OPML documents. */
public class OpmlReader {
	private static final String TAG = "OpmlReader";
	
	// ATTRIBUTES
	private boolean isInOpml = false;
	private boolean isInBody = false;
	private ArrayList<OpmlElement> elementList;

	/**
	 * Reads an Opml document and returns a list of all OPML elements it can
	 * find
	 * 
	 * @throws IOException
	 * @throws XmlPullParserException
	 */
	public ArrayList<OpmlElement> readDocument(Reader reader)
			throws XmlPullParserException, IOException {
		elementList = new ArrayList<OpmlElement>();
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		factory.setNamespaceAware(true);
		XmlPullParser xpp = factory.newPullParser();
		xpp.setInput(reader);
		int eventType = xpp.getEventType();

		while (eventType != XmlPullParser.END_DOCUMENT) {
			switch (eventType) {
			case XmlPullParser.START_DOCUMENT:
				if (AppConfig.DEBUG)
					Log.d(TAG, "Reached beginning of document");
				break;
			case XmlPullParser.START_TAG:
				if (xpp.getName().equals(OpmlSymbols.OPML)) {
					isInOpml = true;
					if (AppConfig.DEBUG)
						Log.d(TAG, "Reached beginning of OPML tree.");
				} else if (isInOpml && xpp.getName().equals(OpmlSymbols.BODY)) {
					isInBody = true;
					if (AppConfig.DEBUG)
						Log.d(TAG, "Reached beginning of body tree.");

				} else if (isInBody && xpp.getName().equals(OpmlSymbols.OUTLINE)) {
					if (AppConfig.DEBUG)
						Log.d(TAG, "Found new Opml element");
					OpmlElement element = new OpmlElement();
					element.setText(xpp.getAttributeValue(null, OpmlSymbols.TEXT));
					element.setXmlUrl(xpp.getAttributeValue(null, OpmlSymbols.XMLURL));
					element.setHtmlUrl(xpp.getAttributeValue(null, OpmlSymbols.HTMLURL));
					element.setType(xpp.getAttributeValue(null, OpmlSymbols.TYPE));
					if (element.getXmlUrl() != null) {
						if (element.getText() == null) {
							Log.i(TAG, "Opml element has no text attribute.");
							element.setText(element.getXmlUrl());
						}
						elementList.add(element);
					} else {
						if (AppConfig.DEBUG)
							Log.d(TAG,
									"Skipping element because of missing xml url");
					}
				}
				break;
			}
			eventType = xpp.next();
		}

		if (AppConfig.DEBUG)
			Log.d(TAG, "Parsing finished.");

		return elementList;
	}

}