Java tutorial
/* * Copyright (c) 2011 Daniel Huckaby * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.handlerexploit.news.data; import java.net.URLEncoder; import org.json.JSONException; import org.json.JSONObject; import com.handlerexploit.news.data.models.WeatherInfo; import com.handlerexploit.news.utils.FileManager; public class WeatherProvider { private static final String WEATHER_URL_TEMPLATE = "http://www.google.com/ig/api?weather=%s"; private static final String BASE_YQL_QUERY = "select * from xml where url=\"%s\""; private static FileManager<WeatherInfo> mFileManager; public static void init(String cacheDirectory) { mFileManager = new FileManager<WeatherInfo>(cacheDirectory); mFileManager.setGlobalTtl(30); } public static WeatherInfo getWeather(String location) { WeatherInfo weatherInfo = null; if (mFileManager != null) { weatherInfo = (WeatherInfo) mFileManager.get(location); if (weatherInfo != null) { return weatherInfo; } } String jsonResponse = YQLHelper.query( String.format(BASE_YQL_QUERY, String.format(WEATHER_URL_TEMPLATE, URLEncoder.encode(location)))); if (jsonResponse == null) { if (mFileManager != null) { weatherInfo = (WeatherInfo) mFileManager.get(location, true); if (weatherInfo != null) { return weatherInfo; } else { return null; } } else { return null; } } try { weatherInfo = new WeatherInfo( new JSONObject(jsonResponse).getJSONObject("xml_api_reply").getJSONObject("weather")); } catch (JSONException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } if (mFileManager != null && weatherInfo != null) { mFileManager.put(location, weatherInfo); } return weatherInfo; } }