Back to project page mobile-android.
The source code is released under:
MIT License
If you think the Android project mobile-android listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.manyconf.conference; /*from ww w . j a va 2 s . c om*/ import android.app.Application; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Scanner; /** * Async task class to get json by making HTTP call * */ public class ConferenceBuilder extends AsyncTask<Void, Void, Void> { // URL to get conference JSON // private static String hostname = "10.0.2.2:8080"; // private static String hostname = "188.226.170.162:8082"; private static String hostname = "www.manyconf.com"; private static String baseUrl = "http://" + hostname + "/conference"; private static String conferenceListUrl = baseUrl + "/api/1.0/conferences"; // JSON Node names private static final String TAG_CONFERENCE_NAME = "name"; private static final String TAG_CONFERENCE_DESCRIPTION = "description"; private static final String TAG_CONFERENCE_LOCATION = "location"; private static final String TAG_CONFERENCE_SHORT_URL = "shortUrl"; // Caching stuff private static File cacheFile = null; // For callback when done parsing private final ConferenceBuilderDelegate delegate; // Determine what to do, and which callback to make private boolean retrieveCache; // Our return values // private ArrayList<ConferenceModel> conferenceList = new ArrayList<ConferenceModel>(); private LinkedHashMap<Integer, ConferenceModel> conferenceList = new LinkedHashMap<Integer, ConferenceModel>(); private String lastError; // Constructor public ConferenceBuilder(ConferenceBuilderDelegate delegate, Context context, Boolean retrieveCache) { this.delegate = delegate; this.retrieveCache = retrieveCache; File cacheDir = context.getCacheDir(); cacheFile = new File(cacheDir, "cache.json"); } @Override protected Void doInBackground(Void... arg0) { Log.d("manyconf.build", "doInBackground()"); this.lastError = null; String jsonStr = null; if(retrieveCache) { Log.d("manyconf.build", "retrieve cached copy"); jsonStr = readCachedCopy(); } else { Log.d("manyconf.build", "retrieve new copy from network"); try { jsonStr = refreshFromNetwork(); } catch (IOException e) { this.lastError = e.getLocalizedMessage(); } } if(jsonStr != null) { parseJsonString(jsonStr); } return null; } private String readCachedCopy() { Log.d("manyconf.build", "readCachedCopy()"); if(cacheFile.exists()) { Log.d("manyconf.confb", String.format("Cached file has size %d bytes", cacheFile.length())); String cacheContent = null; try { // cacheContent = new Scanner(cacheFile).useDelimiter("\\Z").next(); cacheContent = ReadFile.readEntireFile(cacheFile); Log.d("manyconf.confb", String.format("Found %d characters in file", cacheContent.length())); return cacheContent; } catch (FileNotFoundException e) { return null; } catch (IOException ioe) { return null; } } else { Log.d("manyconf.build", "Cache doesn't exist"); } // Cache doesn't exist return null; } private String refreshFromNetwork() throws IOException { Log.d("manyconf.build", "refreshFromNetwork()"); // Creating service handler class instance ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response Log.d("manyconf.build", "Connecting: " + conferenceListUrl); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("api_key", apiKey)); String jsonStr = sh.makeServiceCall(conferenceListUrl, ServiceHandler.GET, params); Log.d("manyconf.build", "Response: " + jsonStr); if (jsonStr == null) { Log.e("manyconf.build", "Got null response from webservice"); return null; } // Save cached copy File tmpCache = null; try { // First store in temporary file tmpCache = File.createTempFile("manyconf","json"); PrintWriter pw = new PrintWriter(tmpCache); pw.println(jsonStr); pw.close(); // Then do atomic move tmpCache.renameTo(cacheFile); Log.d("manyconf.build", "Successfully stored results in cache file"); Log.d("manyconf.build", String.format("Cached file has size %d bytes", cacheFile.length())); } catch (IOException e) { Log.e("manyconf.build", "Can't create temporary file, caching won't work"); } return jsonStr; } private void parseJsonString(String jsonStr) { try { // Getting JSON Array node JSONArray conferences = new JSONArray(jsonStr); parseConferences(conferences); } catch (JSONException e) { Log.e("manyconf.build", "Error parsing JSON", e); } // For each conference, build a unique speaker list and build up the total presentation // list. ArrayList<ConferenceModel> modelList = new ArrayList(conferenceList.values()); for(int ci = 0; ci < modelList.size(); ci++) { ConferenceModel cm = modelList.get(ci); for(int ti = 0; ti < cm.tracks.size(); ti++) { TrackModel tm = cm.tracks.get(ti); cm.nTotalPresentations += tm.presentations.size(); for(int pi = 0; pi < tm.presentations.size(); pi++) { PresentationModel pm = tm.presentations.get(pi); for(int si = 0; si < pm.speakers.size(); si++ ) { SpeakerModel sm = pm.speakers.get(si); cm.speakers.add(sm); } } } Log.d("manyconf.build", String.format("Conference with ID %d has %d presentations and %d speakers", cm.conferenceID, cm.nTotalPresentations, cm.speakers.size())); } } private void parseConferences(JSONArray conferences) throws JSONException { Log.d("manyconf.build", "entry; number of conferences: " + conferences.length()); for (int i = 0; i < conferences.length(); i++) { JSONObject cObj = conferences.getJSONObject(i); ConferenceModel cModel = new ConferenceModel(); cModel.conferenceID = cObj.getInt("id"); cModel.name = cObj.getString("name"); Log.d("manyconf.build", String.format("Parsing conference ID %d with name '%s'", cModel.conferenceID, cModel.name)); cModel.description = cObj.getString("description"); // TODO location is not correctly parsed //cModel.location = cObj.getString("location"); cModel.shortUrl = cObj.getString("shortUrl"); cModel.nTotalPresentations = 0; // Get all conference images JSONArray teaserImagesArray = cObj.getJSONArray("teaserImages"); for (int j = 0; j < teaserImagesArray.length(); j++) { URL url = null; String urlString = teaserImagesArray.getString(j); try { url = new URL(urlString); cModel.teaserImages.add(url); } catch (MalformedURLException mue) { Log.e("manyconf.build", "Skipping URL, because it's malformed: " + urlString); } } Log.d("manyconf.build", "Found " + cModel.teaserImages.size() + " images"); // Parse conference dates cModel.startdate = parseDate(cObj.getString("startdate")); cModel.enddate = parseDate(cObj.getString("enddate")); // Parse conference tracks cModel.tracks = parseTracks(cObj.getJSONArray("tracks")); conferenceList.put(new Integer(cModel.conferenceID), cModel); } Log.d("manyconf.build", "exit; number of parsed conferences: " + conferenceList.size()); } private ArrayList<TrackModel> parseTracks(JSONArray tracks) throws JSONException { Log.d("manyconf.build", "entry; number of tracks: " + tracks.length()); ArrayList<TrackModel> tModelList = new ArrayList<TrackModel>(); for (int i = 0; i < tracks.length(); i++) { JSONObject tObj = tracks.getJSONObject(i); TrackModel tModel = new TrackModel(); tModel.name = tObj.getString("name"); tModel.description = tObj.getString("description"); tModel.location = tObj.getString("location"); // Parse all presentations belonging to this track tModel.presentations = parsePresentations(tObj.getJSONArray("presentations")); // Add parsed tracks. tModelList.add(tModel); } return tModelList; } private ArrayList<PresentationModel> parsePresentations(JSONArray presentations) throws JSONException { Log.d("manyconf.build", "entry; number of presentations: " + presentations.length()); ArrayList<PresentationModel> pModelList = new ArrayList<PresentationModel>(); for (int i = 0; i < presentations.length(); i++) { JSONObject pObj = presentations.getJSONObject(i); PresentationModel pModel = new PresentationModel(); pModel.title = pObj.getString("title"); pModel.description = pObj.getString("description"); pModel.type = pObj.getString("type"); pModel.starttime = parseDate(pObj.getString("startTime")); pModel.endtime = parseDate(pObj.getString("endTime")); pModel.speakers = new ArrayList<SpeakerModel>(); // Parse all presentations belonging to this track pModel.speakers = parseSpeakers(pObj.getJSONArray("speakers")); pModelList.add(pModel); } // Sort list based on start time Collections.sort(pModelList); return pModelList; } private ArrayList<SpeakerModel> parseSpeakers(JSONArray speakers) throws JSONException { Log.d("manyconf.build", "entry; number of speakers: " + speakers.length()); ArrayList<SpeakerModel> sModelList = new ArrayList<SpeakerModel>(); for (int i = 0; i < speakers.length(); i++) { JSONObject sObj = speakers.getJSONObject(i); SpeakerModel sModel = new SpeakerModel(); sModel.firstName = sObj.getString("firstName"); sModel.lastName = sObj.getString("lastName"); sModel.biography = sObj.getString("biography"); sModel.company = sObj.getString("company"); sModelList.add(sModel); } return sModelList; } Date parseDate(String dateString) { Calendar cal = null; try { cal = IsoDateParser.toCalendar(dateString); } catch (ParseException e) { Log.e("manyconf.build", "Skipping startdate, malformed: ["+ dateString + "]"); return null; } return cal.getTime(); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); Log.d("manyconf.build", String.format("Calling delegate with %d results", this.conferenceList.size())); if(retrieveCache) { delegate.retrievedCachedConferenceList(this.conferenceList, lastError); } else { delegate.retrievedConferenceList(this.conferenceList, lastError); } } }