use of android.sax.RootElement in project c-geo by just-radovan.
the class cgGPXParser method parse.
public long parse(File file, int version, Handler handlerIn) {
handler = handlerIn;
if (file == null) {
return 0l;
}
if (version == 11) {
// GPX 1.1
ns = "http://www.topografix.com/GPX/1/1";
} else {
// GPX 1.0
ns = "http://www.topografix.com/GPX/1/0";
}
final RootElement root = new RootElement(ns, "gpx");
final Element waypoint = root.getChild(ns, "wpt");
// waypoint - attributes
waypoint.setStartElementListener(new StartElementListener() {
public void start(Attributes attrs) {
try {
if (attrs.getIndex("lat") > -1) {
cache.latitude = new Double(attrs.getValue("lat"));
}
if (attrs.getIndex("lon") > -1) {
cache.longitude = new Double(attrs.getValue("lon"));
}
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse waypoint's latitude and/or longitude.");
}
}
});
// waypoint
waypoint.setEndElementListener(new EndElementListener() {
public void end() {
if (cache.geocode == null || cache.geocode.length() == 0) {
// try to find geocode somewhere else
String geocode = null;
Matcher matcherGeocode = null;
if (name != null && geocode == null) {
matcherGeocode = patternGeocode.matcher(name);
while (matcherGeocode.find()) {
if (matcherGeocode.groupCount() > 0) {
geocode = matcherGeocode.group(1);
}
}
}
if (desc != null && geocode == null) {
matcherGeocode = patternGeocode.matcher(desc);
while (matcherGeocode.find()) {
if (matcherGeocode.groupCount() > 0) {
geocode = matcherGeocode.group(1);
}
}
}
if (cmt != null && geocode == null) {
matcherGeocode = patternGeocode.matcher(cmt);
while (matcherGeocode.find()) {
if (matcherGeocode.groupCount() > 0) {
geocode = matcherGeocode.group(1);
}
}
}
if (geocode != null && geocode.length() > 0) {
cache.geocode = geocode;
}
geocode = null;
matcherGeocode = null;
}
if (cache.geocode != null && cache.geocode.length() > 0 && cache.latitude != null && cache.longitude != null && ((type == null && sym == null) || (type != null && type.indexOf("geocache") > -1) || (sym != null && sym.indexOf("geocache") > -1))) {
cache.latitudeString = base.formatCoordinate(cache.latitude, "lat", true);
cache.longitudeString = base.formatCoordinate(cache.longitude, "lon", true);
if (cache.inventory != null) {
cache.inventoryItems = cache.inventory.size();
} else {
cache.inventoryItems = 0;
}
cache.reason = listId;
cache.updated = new Date().getTime();
cache.detailedUpdate = new Date().getTime();
cache.detailed = true;
app.addCacheToSearch(search, cache);
}
if (handler != null) {
final Message msg = new Message();
msg.obj = search.getCount();
handler.sendMessage(msg);
}
htmlShort = true;
htmlLong = true;
type = null;
sym = null;
name = null;
desc = null;
cmt = null;
cache = null;
cache = new cgCache();
}
});
// waypoint.time
waypoint.getChild(ns, "time").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
try {
cache.hidden = cgBase.dateGPXIn.parse(body.trim());
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse cache date: " + e.toString());
}
}
});
// waypoint.name
waypoint.getChild(ns, "name").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
name = body;
final String content = Html.fromHtml(body).toString().trim();
cache.name = content;
if (cache.name.length() > 2 && cache.name.substring(0, 2).equalsIgnoreCase("GC") == true) {
cache.geocode = cache.name.toUpperCase();
}
}
});
// waypoint.desc
waypoint.getChild(ns, "desc").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
desc = body;
final String content = Html.fromHtml(body).toString().trim();
cache.shortdesc = content;
}
});
// waypoint.cmt
waypoint.getChild(ns, "cmt").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
cmt = body;
final String content = Html.fromHtml(body).toString().trim();
cache.description = content;
}
});
// waypoint.type
waypoint.getChild(ns, "type").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
final String[] content = body.split("\\|");
if (content.length > 0) {
type = content[0].toLowerCase().trim();
}
}
});
// waypoint.sym
waypoint.getChild(ns, "sym").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
body = body.toLowerCase();
sym = body;
if (body.indexOf("geocache") != -1 && body.indexOf("found") != -1) {
cache.found = true;
}
}
});
for (String nsGC : nsGCList) {
// waypoints.cache
final Element gcCache = waypoint.getChild(nsGC, "cache");
gcCache.setStartElementListener(new StartElementListener() {
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1) {
cache.cacheid = attrs.getValue("id");
}
if (attrs.getIndex("archived") > -1) {
final String at = attrs.getValue("archived").toLowerCase();
if (at.equals("true")) {
cache.archived = true;
} else {
cache.archived = false;
}
}
if (attrs.getIndex("available") > -1) {
final String at = attrs.getValue("available").toLowerCase();
if (at.equals("true")) {
cache.disabled = false;
} else {
cache.disabled = true;
}
}
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse cache attributes.");
}
}
});
// waypoint.cache.name
gcCache.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
final String content = Html.fromHtml(body).toString().trim();
cache.name = content;
}
});
// waypoint.cache.owner
gcCache.getChild(nsGC, "owner").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
final String content = Html.fromHtml(body).toString().trim();
cache.owner = content;
}
});
// waypoint.cache.type
gcCache.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
final String content = cgBase.cacheTypes.get(body.toLowerCase());
cache.type = content;
}
});
// waypoint.cache.container
gcCache.getChild(nsGC, "container").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
final String content = body.toLowerCase();
cache.size = content;
}
});
// waypoint.cache.difficulty
gcCache.getChild(nsGC, "difficulty").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
try {
cache.difficulty = new Float(body);
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse difficulty: " + e.toString());
}
}
});
// waypoint.cache.terrain
gcCache.getChild(nsGC, "terrain").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
try {
cache.terrain = new Float(body);
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse terrain: " + e.toString());
}
}
});
// waypoint.cache.country
gcCache.getChild(nsGC, "country").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
if (cache.location == null || cache.location.length() == 0) {
cache.location = body.trim();
} else {
cache.location = cache.location + ", " + body.trim();
}
}
});
// waypoint.cache.state
gcCache.getChild(nsGC, "state").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
if (cache.location == null || cache.location.length() == 0) {
cache.location = body.trim();
} else {
cache.location = body.trim() + ", " + cache.location;
}
}
});
// waypoint.cache.encoded_hints
gcCache.getChild(nsGC, "encoded_hints").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
cache.hint = body.trim();
}
});
// waypoint.cache.short_description
gcCache.getChild(nsGC, "short_description").setStartElementListener(new StartElementListener() {
public void start(Attributes attrs) {
try {
if (attrs.getIndex("html") > -1) {
final String at = attrs.getValue("html").toLowerCase();
if (at.equals("false")) {
htmlShort = false;
}
}
} catch (Exception e) {
// nothing
}
}
});
gcCache.getChild(nsGC, "short_description").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
if (htmlShort == false) {
cache.shortdesc = Html.fromHtml(body).toString();
} else {
cache.shortdesc = body;
}
}
});
// waypoint.cache.long_description
gcCache.getChild(nsGC, "long_description").setStartElementListener(new StartElementListener() {
public void start(Attributes attrs) {
try {
if (attrs.getIndex("html") > -1) {
final String at = attrs.getValue("html").toLowerCase();
if (at.equals("false")) {
htmlLong = false;
}
}
} catch (Exception e) {
// nothing
}
}
});
gcCache.getChild(nsGC, "long_description").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
if (htmlLong == false) {
cache.description = Html.fromHtml(body).toString().trim();
} else {
cache.description = body;
}
}
});
// waypoint.cache.travelbugs
final Element gcTBs = gcCache.getChild(nsGC, "travelbugs");
// waypoint.cache.travelbugs.travelbug
gcTBs.getChild(nsGC, "travelbug").setStartElementListener(new StartElementListener() {
public void start(Attributes attrs) {
trackable = new cgTrackable();
try {
if (attrs.getIndex("ref") > -1) {
trackable.geocode = attrs.getValue("ref").toUpperCase();
}
} catch (Exception e) {
// nothing
}
}
});
// waypoint.cache.travelbug
final Element gcTB = gcTBs.getChild(nsGC, "travelbug");
gcTB.setEndElementListener(new EndElementListener() {
public void end() {
if (trackable.geocode != null && trackable.geocode.length() > 0 && trackable.name != null && trackable.name.length() > 0) {
if (cache.inventory == null)
cache.inventory = new ArrayList<cgTrackable>();
cache.inventory.add(trackable);
}
}
});
// waypoint.cache.travelbugs.travelbug.name
gcTB.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
String content = Html.fromHtml(body).toString();
trackable.name = content;
}
});
// waypoint.cache.logs
final Element gcLogs = gcCache.getChild(nsGC, "logs");
// waypoint.cache.log
final Element gcLog = gcLogs.getChild(nsGC, "log");
gcLog.setStartElementListener(new StartElementListener() {
public void start(Attributes attrs) {
log = new cgLog();
try {
if (attrs.getIndex("id") > -1) {
log.id = Integer.parseInt(attrs.getValue("id"));
}
} catch (Exception e) {
// nothing
}
}
});
gcLog.setEndElementListener(new EndElementListener() {
public void end() {
if (log.log != null && log.log.length() > 0) {
if (cache.logs == null)
cache.logs = new ArrayList<cgLog>();
cache.logs.add(log);
}
}
});
// waypoint.cache.logs.log.date
gcLog.getChild(nsGC, "date").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
try {
log.date = cgBase.dateGPXIn.parse(body.trim()).getTime();
} catch (Exception e) {
Log.w(cgSettings.tag, "Failed to parse log date: " + e.toString());
}
}
});
// waypoint.cache.logs.log.type
gcLog.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
final String content = body.trim().toLowerCase();
if (cgBase.logTypes0.containsKey(content) == true) {
log.type = cgBase.logTypes0.get(content);
} else {
log.type = 4;
}
}
});
// waypoint.cache.logs.log.finder
gcLog.getChild(nsGC, "finder").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
String content = Html.fromHtml(body).toString();
log.author = content;
}
});
// waypoint.cache.logs.log.finder
gcLog.getChild(nsGC, "text").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
String content = Html.fromHtml(body).toString();
log.log = content;
}
});
}
try {
Xml.parse(new FileInputStream(file), Xml.Encoding.UTF_8, root.getContentHandler());
return search.getCurrentId();
} catch (Exception e) {
Log.e(cgSettings.tag, "Cannot parse .gpx file " + file.getAbsolutePath() + " as GPX " + version + ": " + e.toString());
}
return 0l;
}
use of android.sax.RootElement in project SeriesGuide by UweTrottmann.
the class TvdbTools method parseEpisodes.
/**
* Loads the given zipped XML and parses containing episodes to create an array of {@link
* ContentValues} for new episodes.<br> Adds update ops for updated episodes and delete ops for
* local orphaned episodes to the given {@link ContentProviderOperation} batch.
*/
private ArrayList<ContentValues> parseEpisodes(final ArrayList<ContentProviderOperation> batch, final Show show, String url) throws TvdbException {
final long dateLastMonthEpoch = (System.currentTimeMillis() - (DateUtils.DAY_IN_MILLIS * 30)) / 1000;
final DateTimeZone showTimeZone = TimeTools.getDateTimeZone(show.release_timezone);
final LocalTime showReleaseTime = TimeTools.getShowReleaseTime(show.release_time);
final String deviceTimeZone = TimeZone.getDefault().getID();
RootElement root = new RootElement("Data");
Element episode = root.getChild("Episode");
final ArrayList<ContentValues> newEpisodesValues = new ArrayList<>();
final HashMap<Integer, Long> localEpisodeIds = DBUtils.getEpisodeMapForShow(app, show.tvdb_id);
final HashMap<Integer, Long> removableEpisodeIds = new HashMap<>(// just copy episodes list, then remove valid ones
localEpisodeIds);
final HashSet<Integer> localSeasonIds = DBUtils.getSeasonIdsOfShow(app, show.tvdb_id);
// store updated seasons to avoid duplicate ops
final HashSet<Integer> seasonIdsToUpdate = new HashSet<>();
final ContentValues values = new ContentValues();
// set handlers for elements we want to react to
episode.setEndElementListener(new EndElementListener() {
public void end() {
Integer episodeId = values.getAsInteger(Episodes._ID);
if (episodeId == null || episodeId <= 0) {
// invalid id, skip
return;
}
// don't clean up this episode
removableEpisodeIds.remove(episodeId);
// decide whether to insert or update
if (localEpisodeIds.containsKey(episodeId)) {
/*
* Update uses provider ops which take a long time. Only
* update if episode was edited on TVDb or is not older than
* a month (ensures show air time changes get stored).
*/
Long lastEditEpoch = localEpisodeIds.get(episodeId);
Long lastEditEpochNew = values.getAsLong(Episodes.LAST_EDITED);
if (lastEditEpoch != null && lastEditEpochNew != null && (lastEditEpoch < lastEditEpochNew || dateLastMonthEpoch < lastEditEpoch)) {
// complete update op for episode
batch.add(DBUtils.buildEpisodeUpdateOp(values));
}
} else {
// episode does not exist, yet
newEpisodesValues.add(new ContentValues(values));
}
Integer seasonId = values.getAsInteger(Seasons.REF_SEASON_ID);
if (seasonId != null && !seasonIdsToUpdate.contains(seasonId)) {
// add insert/update op for season
batch.add(DBUtils.buildSeasonOp(values, !localSeasonIds.contains(seasonId)));
seasonIdsToUpdate.add(values.getAsInteger(Seasons.REF_SEASON_ID));
}
values.clear();
}
});
episode.getChild("id").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes._ID, body.trim());
}
});
episode.getChild("EpisodeNumber").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.NUMBER, body.trim());
}
});
episode.getChild("absolute_number").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.ABSOLUTE_NUMBER, body.trim());
}
});
episode.getChild("SeasonNumber").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.SEASON, body.trim());
}
});
episode.getChild("DVD_episodenumber").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.DVDNUMBER, body.trim());
}
});
episode.getChild("FirstAired").setEndTextElementListener(new EndTextElementListener() {
public void end(String releaseDate) {
long releaseDateTime = TimeTools.parseEpisodeReleaseDate(app, showTimeZone, releaseDate, showReleaseTime, show.country, show.network, deviceTimeZone);
values.put(Episodes.FIRSTAIREDMS, releaseDateTime);
}
});
episode.getChild("EpisodeName").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.TITLE, body.trim());
}
});
episode.getChild("Overview").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.OVERVIEW, body.trim());
}
});
episode.getChild("seasonid").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Seasons.REF_SEASON_ID, body.trim());
}
});
episode.getChild("seriesid").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Shows.REF_SHOW_ID, body.trim());
}
});
episode.getChild("Director").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.DIRECTORS, body.trim());
}
});
episode.getChild("GuestStars").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.GUESTSTARS, body.trim());
}
});
episode.getChild("Writer").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.WRITERS, body.trim());
}
});
episode.getChild("filename").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.IMAGE, body.trim());
}
});
episode.getChild("IMDB_ID").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.IMDBID, body.trim());
}
});
episode.getChild("lastupdated").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
// system populated field, trimming not necessary
try {
values.put(Episodes.LAST_EDITED, Long.valueOf(body));
} catch (NumberFormatException e) {
values.put(Episodes.LAST_EDITED, 0);
}
}
});
downloadAndParse(root.getContentHandler(), url, true, "parseEpisodes: ");
// add delete ops for leftover episodeIds in our db
for (Integer episodeId : removableEpisodeIds.keySet()) {
batch.add(ContentProviderOperation.newDelete(Episodes.buildEpisodeUri(episodeId)).build());
}
return newEpisodesValues;
}
use of android.sax.RootElement in project SeriesGuide by UweTrottmann.
the class TvdbTools method searchShow.
/**
* Search TheTVDB for shows which include a certain keyword in their title.
*
* @param language If not provided, will query for results in all languages.
* @return At most 100 results (limited by TheTVDB API).
*/
@Nonnull
public List<SearchResult> searchShow(@NonNull String query, @Nullable final String language) throws TvdbException {
final List<SearchResult> series = new ArrayList<>();
final SearchResult currentShow = new SearchResult();
RootElement root = new RootElement("Data");
Element item = root.getChild("Series");
// set handlers for elements we want to react to
item.setEndElementListener(new EndElementListener() {
public void end() {
// only take results in the selected language
if (language == null || language.equals(currentShow.language)) {
series.add(currentShow.copy());
}
}
});
item.getChild("id").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.tvdbid = Integer.valueOf(body);
}
});
item.getChild("language").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
currentShow.language = body.trim();
}
});
item.getChild("SeriesName").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.title = body.trim();
}
});
item.getChild("Overview").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.overview = body.trim();
}
});
// build search URL: encode query...
String url;
try {
url = TVDB_API_GETSERIES + URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new TvdbDataException("searchShow: " + e.getMessage(), e);
}
// ...and set language filter
if (language == null) {
url += TVDB_PARAM_LANGUAGE + "all";
} else {
url += TVDB_PARAM_LANGUAGE + language;
}
downloadAndParse(root.getContentHandler(), url, false, "searchShow: ");
return series;
}
use of android.sax.RootElement in project android_frameworks_base by ParanoidAndroid.
the class SafeSaxTest method testMixedContent.
@SmallTest
public void testMixedContent() throws Exception {
String xml = "<feed><entry></entry></feed>";
RootElement root = new RootElement("feed");
root.setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
}
});
try {
Xml.parse(xml, root.getContentHandler());
fail("expected exception not thrown");
} catch (SAXException e) {
// Expected.
}
}
use of android.sax.RootElement in project platform_frameworks_base by android.
the class SafeSaxTest method testMissingRequiredChild.
@SmallTest
public void testMissingRequiredChild() throws Exception {
String xml = "<feed></feed>";
RootElement root = new RootElement("feed");
root.requireChild("entry");
try {
Xml.parse(xml, root.getContentHandler());
fail("expected exception not thrown");
} catch (SAXException e) {
// Expected.
}
}
Aggregations