From: gu.martinm@gmail.com Date: Mon, 14 Apr 2014 03:05:49 +0000 (+0200) Subject: I do not like openweathermap X-Git-Tag: weatherinformation-1.0~175 X-Git-Url: https://git.gumartinm.name/?a=commitdiff_plain;h=0244cbb16082949e1992df62aac3341b13b82a5e;p=AndroidWeatherInformation I do not like openweathermap --- diff --git a/res/values/strings.xml b/res/values/strings.xml index ad65976..bd03e46 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -7,9 +7,9 @@ Get weather Select Location Set Location - http://api.openweathermap.org/data/{0}/weather?lat={1}&lon={2}&lang={3}&cnt=1 - http://api.openweathermap.org/data/{0}/weather?q={1}&lang={2} - http://openweathermap.org/img/w/{0}.png + http://api.openweathermap.org/data/{0}/weather?lat={1}&lon={2}&cnt=1 + http://openweathermap.org/img/w/{0}.png + http://api.openweathermap.org/data/{0}/forecast/daily?lat={1}&lon={2}&cnt={3}&mode=json https://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&sensor=true 2.5 London,uk diff --git a/src/de/example/exampletdd/WeatherInformationActivity.java b/src/de/example/exampletdd/WeatherInformationActivity.java index 2de943e..1e97ba3 100644 --- a/src/de/example/exampletdd/WeatherInformationActivity.java +++ b/src/de/example/exampletdd/WeatherInformationActivity.java @@ -106,6 +106,6 @@ public class WeatherInformationActivity extends Activity { public void getWeather() { - this.mGetWeather.getWeather(); + this.mGetWeather.getRemoteWeatherInformation(); } } diff --git a/src/de/example/exampletdd/WeatherInformationMapActivity.java b/src/de/example/exampletdd/WeatherInformationMapActivity.java index 747a440..d5f6c6c 100644 --- a/src/de/example/exampletdd/WeatherInformationMapActivity.java +++ b/src/de/example/exampletdd/WeatherInformationMapActivity.java @@ -57,7 +57,7 @@ public class WeatherInformationMapActivity extends Activity { this.mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point, 5)); this.mMap.animateCamera(CameraUpdateFactory.zoomIn()); - this.mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); + this.mMap.animateCamera(CameraUpdateFactory.zoomTo(8), 2000, null); final TextView cityCountry = (TextView) WeatherInformationMapActivity.this .findViewById(R.id.weather_map_citycountry_data); @@ -142,20 +142,20 @@ public class WeatherInformationMapActivity extends Activity { final String city = (geocodingData.getCity() == null) ? WeatherInformationMapActivity.this.getString(R.string.city_not_found) : geocodingData.getCity(); - final String country = (geocodingData.getCountry() == null) ? - WeatherInformationMapActivity.this.getString(R.string.country_not_found) - : geocodingData.getCountry(); - final TextView cityCountry = (TextView) WeatherInformationMapActivity.this + final String country = (geocodingData.getCountry() == null) ? + WeatherInformationMapActivity.this.getString(R.string.country_not_found) + : geocodingData.getCountry(); + final TextView cityCountry = (TextView) WeatherInformationMapActivity.this .findViewById(R.id.weather_map_citycountry_data); - cityCountry.setText(city + "," + country); - - final LatLng point = new LatLng(geocodingData.getLatitude(), geocodingData.getLongitude()); - if (WeatherInformationMapActivity.this.mMarker == null) { - WeatherInformationMapActivity.this.mMarker = WeatherInformationMapActivity.this.mMap.addMarker - (new MarkerOptions().position(point).draggable(true)); - } else { - WeatherInformationMapActivity.this.mMarker.setPosition(point); - } + cityCountry.setText(city + "," + country); + + final LatLng point = new LatLng(geocodingData.getLatitude(), geocodingData.getLongitude()); + if (WeatherInformationMapActivity.this.mMarker == null) { + WeatherInformationMapActivity.this.mMarker = WeatherInformationMapActivity.this.mMap.addMarker + (new MarkerOptions().position(point).draggable(true)); + } else { + WeatherInformationMapActivity.this.mMarker.setPosition(point); + } } private GeocodingData getGeocodingData(final double latitude, final double longitude) throws IOException { diff --git a/src/de/example/exampletdd/activityinterface/GetWeather.java b/src/de/example/exampletdd/activityinterface/GetWeather.java index 98734cd..4affd6a 100644 --- a/src/de/example/exampletdd/activityinterface/GetWeather.java +++ b/src/de/example/exampletdd/activityinterface/GetWeather.java @@ -3,6 +3,8 @@ package de.example.exampletdd.activityinterface; public interface GetWeather { - public void getWeather(); + public void getWeatherByDay(final int chosenDay); + + public void getRemoteWeatherInformation(); } diff --git a/src/de/example/exampletdd/fragment/overview/WeatherInformationOverviewFragment.java b/src/de/example/exampletdd/fragment/overview/WeatherInformationOverviewFragment.java index 05a10a9..227e374 100644 --- a/src/de/example/exampletdd/fragment/overview/WeatherInformationOverviewFragment.java +++ b/src/de/example/exampletdd/fragment/overview/WeatherInformationOverviewFragment.java @@ -10,13 +10,12 @@ import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; -import java.util.Collection; import java.util.Date; +import java.util.Iterator; import java.util.List; import java.util.Locale; import org.apache.http.client.ClientProtocolException; -import org.json.JSONException; import android.app.DialogFragment; import android.app.ListFragment; @@ -32,38 +31,40 @@ import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.widget.ListView; + +import com.fasterxml.jackson.core.JsonParseException; + import de.example.exampletdd.R; import de.example.exampletdd.activityinterface.GetWeather; import de.example.exampletdd.fragment.ErrorDialogFragment; import de.example.exampletdd.fragment.ProgressDialogFragment; import de.example.exampletdd.fragment.specific.WeatherInformationSpecificDataFragment; -import de.example.exampletdd.httpclient.WeatherHTTPClient; +import de.example.exampletdd.httpclient.CustomHTTPClient; import de.example.exampletdd.model.GeocodingData; -import de.example.exampletdd.model.WeatherData; +import de.example.exampletdd.model.currentweather.CurrentWeatherData; +import de.example.exampletdd.model.forecastweather.ForecastWeatherData; import de.example.exampletdd.parser.IJPOSWeatherParser; import de.example.exampletdd.parser.JPOSWeatherParser; -import de.example.exampletdd.service.WeatherService; +import de.example.exampletdd.service.WeatherServiceParser; import de.example.exampletdd.service.WeatherServicePersistenceFile; public class WeatherInformationOverviewFragment extends ListFragment implements GetWeather { private boolean mIsFahrenheit; - private String mLanguage; private WeatherServicePersistenceFile mWeatherServicePersistenceFile; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); - final SharedPreferences sharedPreferences = PreferenceManager - .getDefaultSharedPreferences(this.getActivity()); - final String keyPreference = this.getResources().getString( - R.string.weather_preferences_language_key); - this.mLanguage = sharedPreferences.getString( - keyPreference, ""); + // final SharedPreferences sharedPreferences = PreferenceManager + // .getDefaultSharedPreferences(this.getActivity()); + // final String keyPreference = this.getResources().getString( + // R.string.weather_preferences_language_key); + // this.mLanguage = sharedPreferences.getString( + // keyPreference, ""); - this.mWeatherServicePersistenceFile = new WeatherServicePersistenceFile( - this.getActivity()); - this.mWeatherServicePersistenceFile.removeWeatherData(); + this.mWeatherServicePersistenceFile = new WeatherServicePersistenceFile(this.getActivity()); + this.mWeatherServicePersistenceFile.removeForecastWeatherData(); } @Override @@ -76,15 +77,21 @@ public class WeatherInformationOverviewFragment extends ListFragment implements if (savedInstanceState != null) { // Restore state - final WeatherData weatherData = (WeatherData) savedInstanceState - .getSerializable("weatherData"); - try { - this.mWeatherServicePersistenceFile - .storeWeatherData(weatherData); - } catch (final IOException e) { - final DialogFragment newFragment = ErrorDialogFragment - .newInstance(R.string.error_dialog_generic_error); - newFragment.show(this.getFragmentManager(), "errorDialog"); + final ForecastWeatherData forecastWeatherData = (ForecastWeatherData) savedInstanceState + .getSerializable("ForecastWeatherData"); + final CurrentWeatherData currentWeatherData = (CurrentWeatherData) savedInstanceState + .getSerializable("CurrentWeatherData"); + + if ((forecastWeatherData != null) && (currentWeatherData != null)) { + try { + this.mWeatherServicePersistenceFile + .storeForecastWeatherData(forecastWeatherData); + this.mWeatherServicePersistenceFile.storeCurrentWeatherData(currentWeatherData); + } catch (final IOException e) { + final DialogFragment newFragment = ErrorDialogFragment + .newInstance(R.string.error_dialog_generic_error); + newFragment.show(this.getFragmentManager(), "errorDialog"); + } } } @@ -93,11 +100,9 @@ public class WeatherInformationOverviewFragment extends ListFragment implements final WeatherOverviewAdapter adapter = new WeatherOverviewAdapter( this.getActivity(), R.layout.weather_main_entry_list); - final Collection entries = this - .createEmptyEntriesList(); - this.setListAdapter(null); - adapter.addAll(entries); + this.setEmptyText("Press download to receive weather information"); + this.setListAdapter(adapter); this.setListShown(true); this.setListShownNoAnimation(true); @@ -112,10 +117,11 @@ public class WeatherInformationOverviewFragment extends ListFragment implements final Intent intent = new Intent("de.example.exampletdd.WEATHERINFO"). setComponent(new ComponentName("de.example.exampletdd", "de.example.exampletdd.WeatherInformationSpecificDataActivity")); + intent.putExtra("CHOSEN_DAY", id); WeatherInformationOverviewFragment.this.getActivity().startActivity(intent); } else { // tablet layout - fragment.getWeather(); + fragment.getWeatherByDay(position); } } @@ -123,27 +129,32 @@ public class WeatherInformationOverviewFragment extends ListFragment implements public void onSaveInstanceState(final Bundle savedInstanceState) { // Save state - final WeatherData weatherData = this.mWeatherServicePersistenceFile.getWeatherData(); + final ForecastWeatherData forecastWeatherData = this.mWeatherServicePersistenceFile + .getForecastWeatherData(); + + final CurrentWeatherData currentWeatherData = this.mWeatherServicePersistenceFile + .getCurrentWeatherData(); - if (weatherData != null) { - savedInstanceState.putSerializable("weatherData", weatherData); + if ((forecastWeatherData != null) && (currentWeatherData != null)) { + savedInstanceState.putSerializable("ForecastWeatherData", forecastWeatherData); + savedInstanceState.putSerializable("CurrentWeatherData", currentWeatherData); } super.onSaveInstanceState(savedInstanceState); } @Override - public void getWeather() { + public void getRemoteWeatherInformation() { final GeocodingData geocodingData = this.mWeatherServicePersistenceFile.getGeocodingData(); if (geocodingData != null) { final IJPOSWeatherParser JPOSWeatherParser = new JPOSWeatherParser(); - final WeatherService weatherService = new WeatherService( + final WeatherServiceParser weatherService = new WeatherServiceParser( JPOSWeatherParser); final AndroidHttpClient httpClient = AndroidHttpClient .newInstance("Android Weather Information Agent"); - final WeatherHTTPClient HTTPweatherClient = new WeatherHTTPClient( + final CustomHTTPClient HTTPweatherClient = new CustomHTTPClient( httpClient); final WeatherTask weatherTask = new WeatherTask(HTTPweatherClient, weatherService); @@ -153,42 +164,88 @@ public class WeatherInformationOverviewFragment extends ListFragment implements } } - public void updateWeatherData(final WeatherData weatherData) { - final List entries = this.createEmptyEntriesList(); + @Override + public void getWeatherByDay(final int chosenDay) { + // Nothing to do. + } + + public void updateForecastWeatherData(final WeatherData weatherData) { + final List entries = new ArrayList(); final WeatherOverviewAdapter adapter = new WeatherOverviewAdapter(this.getActivity(), R.layout.weather_main_entry_list); - // Bitmap picture = null; - // - // if (weatherData.getWeather().getIcon() != null) { - // picture= BitmapFactory.decodeByteArray( - // weatherData.getIconData(), 0, - // weatherData.getIconData().length); - // } - final Bitmap picture = BitmapFactory.decodeResource( this.getResources(), R.drawable.ic_02d); final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.getDefault()); tempFormatter.applyPattern("#####.##"); final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d", Locale.getDefault()); final double tempUnits = this.mIsFahrenheit ? 0 : 273.15; - double temp = weatherData.getMain().getTemp(); - temp = temp - tempUnits; - double maxTemp = weatherData.getMain().getMaxTemp(); - maxTemp = maxTemp - tempUnits; - double minTemp = weatherData.getMain().getMinTemp(); - minTemp = minTemp - tempUnits; - - final Calendar now = Calendar.getInstance(); - if (weatherData.getWeather() != null) { - for (int i = 0; i<15; i++) { - final Date day = now.getTime(); - entries.set(i, new WeatherOverviewEntry(dateFormat.format(day), - tempFormatter.format(temp), tempFormatter - .format(maxTemp), tempFormatter - .format(minTemp), picture)); - now.add(Calendar.DAY_OF_MONTH, 1); + final String symbol = this.mIsFahrenheit ? "ºF" : "ºC"; + + final CurrentWeatherData currentWeatherData = weatherData.getCurrentWeatherData(); + + String formatMaxTemp; + String formatMinTemp; + + if (currentWeatherData.getMain().getTemp_max() != null) { + double maxTemp = (Double) currentWeatherData.getMain().getTemp_max(); + maxTemp = maxTemp - tempUnits; + formatMaxTemp = tempFormatter.format(maxTemp) + symbol; + } else { + formatMaxTemp = "no data"; + } + if (currentWeatherData.getMain().getTemp_min() != null) { + double minTemp = (Double) currentWeatherData.getMain().getTemp_min(); + minTemp = minTemp - tempUnits; + formatMinTemp = tempFormatter.format(minTemp) + symbol; + } else { + formatMinTemp = "no data"; + } + + entries.add(new WeatherOverviewEntry(dateFormat.format(currentWeatherData.getDate()), + formatMaxTemp, formatMinTemp, picture)); + + + final ForecastWeatherData forecastWeatherData = weatherData.getForecastWeatherData(); + + final Calendar calendar = Calendar.getInstance(); + calendar.setTime(currentWeatherData.getDate()); + + final int forecastSize = forecastWeatherData.getList().size(); + final int chosenForecastDays = 14; + final int index = forecastSize < chosenForecastDays ? forecastSize : chosenForecastDays; + for (int i = 0; i < index; i++) { + calendar.add(Calendar.DAY_OF_MONTH, 1); + + final de.example.exampletdd.model.forecastweather.List forecast = forecastWeatherData + .getList().get(i); + + if (forecast.getTemp().getMax() != null) { + double maxTemp = (Double) forecast.getTemp().getMax(); + maxTemp = maxTemp - tempUnits; + formatMaxTemp = tempFormatter.format(maxTemp) + symbol; + } else { + formatMaxTemp = "no data"; } + + if (forecast.getTemp().getMin() != null) { + double minTemp = (Double) forecast.getTemp().getMin(); + minTemp = minTemp - tempUnits; + formatMinTemp = tempFormatter.format(minTemp) + symbol; + } else { + formatMinTemp = "no data"; + } + + final Date day = calendar.getTime(); + entries.add(new WeatherOverviewEntry(dateFormat.format(day), formatMaxTemp, + formatMinTemp, picture)); + } + + final int leftDays = chosenForecastDays - index; + for (int i = 0; i < leftDays; i++) { + calendar.add(Calendar.DAY_OF_MONTH, 1); + final Date day = calendar.getTime(); + entries.add(new WeatherOverviewEntry(dateFormat.format(day), "no data", "no data", picture)); } this.setListAdapter(null); @@ -204,7 +261,7 @@ public class WeatherInformationOverviewFragment extends ListFragment implements .getDefaultSharedPreferences(this.getActivity()); // 1. Update units of measurement. - String keyPreference = this.getResources().getString( + final String keyPreference = this.getResources().getString( R.string.weather_preferences_units_key); final String unitsPreferenceValue = sharedPreferences.getString(keyPreference, ""); final String celsius = this.getResources().getString( @@ -216,34 +273,37 @@ public class WeatherInformationOverviewFragment extends ListFragment implements } - // 2. Update current data on display. - final WeatherData weatherData = this.mWeatherServicePersistenceFile.getWeatherData(); - - if (weatherData != null) { - this.updateWeatherData(weatherData); + // 2. Update forecast weather data on display. + final ForecastWeatherData forecastWeatherData = this.mWeatherServicePersistenceFile + .getForecastWeatherData(); + final CurrentWeatherData currentWeatherData = this.mWeatherServicePersistenceFile + .getCurrentWeatherData(); + if ((forecastWeatherData != null) && (currentWeatherData != null)) { + final WeatherData weatherData = new WeatherData(forecastWeatherData, currentWeatherData); + this.updateForecastWeatherData(weatherData); } // 3. If language changed, try to retrieve new data for new language // (new strings with the chosen language) - keyPreference = this.getResources().getString( - R.string.weather_preferences_language_key); - final String languagePreferenceValue = sharedPreferences.getString( - keyPreference, ""); - if (!languagePreferenceValue.equals(this.mLanguage)) { - this.mLanguage = languagePreferenceValue; - this.getWeather(); - } + // keyPreference = this.getResources().getString( + // R.string.weather_preferences_language_key); + // final String languagePreferenceValue = sharedPreferences.getString( + // keyPreference, ""); + // if (!languagePreferenceValue.equals(this.mLanguage)) { + // this.mLanguage = languagePreferenceValue; + // this.getWeather(); + // } } public class WeatherTask extends AsyncTask { private static final String TAG = "WeatherTask"; - private final WeatherHTTPClient weatherHTTPClient; - private final WeatherService weatherService; + private final CustomHTTPClient weatherHTTPClient; + private final WeatherServiceParser weatherService; private final DialogFragment newFragment; - public WeatherTask(final WeatherHTTPClient weatherHTTPClient, - final WeatherService weatherService) { + public WeatherTask(final CustomHTTPClient weatherHTTPClient, + final WeatherServiceParser weatherService) { this.weatherHTTPClient = weatherHTTPClient; this.weatherService = weatherService; this.newFragment = ProgressDialogFragment.newInstance( @@ -270,11 +330,11 @@ public class WeatherInformationOverviewFragment extends ListFragment implements Log.e(TAG, "doInBackground exception: ", e); } catch (final URISyntaxException e) { Log.e(TAG, "doInBackground exception: ", e); + } catch (final JsonParseException e) { + Log.e(TAG, "doInBackground exception: ", e); } catch (final IOException e) { // logger infrastructure swallows UnknownHostException :/ Log.e(TAG, "doInBackground exception: " + e.getMessage(), e); - } catch (final JSONException e) { - Log.e(TAG, "doInBackground exception: ", e); } finally { this.weatherHTTPClient.close(); } @@ -315,39 +375,58 @@ public class WeatherInformationOverviewFragment extends ListFragment implements private WeatherData doInBackgroundThrowable(final Object... params) throws ClientProtocolException, MalformedURLException, - URISyntaxException, IOException, JSONException { - final SharedPreferences sharedPreferences = PreferenceManager - .getDefaultSharedPreferences(WeatherInformationOverviewFragment.this - .getActivity()); + URISyntaxException, JsonParseException, IOException { + // final SharedPreferences sharedPreferences = PreferenceManager + // .getDefaultSharedPreferences(WeatherInformationOverviewFragment.this + // .getActivity()); + // + // final String keyPreference = + // WeatherInformationOverviewFragment.this + // .getActivity().getString( + // R.string.weather_preferences_language_key); + // final String languagePreferenceValue = + // sharedPreferences.getString(keyPreference, ""); + + // 1. Coordinates + final GeocodingData geocodingData = (GeocodingData) params[0]; - final String keyPreference = WeatherInformationOverviewFragment.this - .getActivity().getString( - R.string.weather_preferences_language_key); - final String languagePreferenceValue = sharedPreferences.getString(keyPreference, ""); - final GeocodingData geocodingData = (GeocodingData) params[0]; - final String urlAPICoord = WeatherInformationOverviewFragment.this.getResources() - .getString(R.string.uri_api_coord); + final Calendar now = Calendar.getInstance(); final String APIVersion = WeatherInformationOverviewFragment.this.getResources() .getString(R.string.api_version); - String url = this.weatherService.createURIAPICoord(geocodingData.getLatitude(), - geocodingData.getLongitude(), urlAPICoord, APIVersion, languagePreferenceValue); - - - final String jsonData = this.weatherHTTPClient.retrieveJSONDataFromAPI(new URL(url)); - - - final WeatherData weatherData = this.weatherService.retrieveDataFromJPOS(jsonData); + // 2. Forecast + String urlAPI = WeatherInformationOverviewFragment.this.getResources() + .getString(R.string.uri_api_weather_forecast); + String url = this.weatherService.createURIAPIForecastWeather(urlAPI, APIVersion, + geocodingData.getLatitude(), geocodingData.getLongitude(), "14"); + String jsonData = this.weatherHTTPClient.retrieveDataAsString(new URL(url)); + final ForecastWeatherData forecastWeatherData = this.weatherService + .retrieveForecastWeatherDataFromJPOS(jsonData); + final Iterator iterator = + forecastWeatherData.getList().iterator(); + while (iterator.hasNext()) { + final de.example.exampletdd.model.forecastweather.List forecast = iterator.next(); + + final Long forecastUNIXDate = (Long) forecast.getDt(); + final Calendar forecastCalendar = Calendar.getInstance(); + forecastCalendar.setTimeInMillis(forecastUNIXDate * 1000L); + if (now.compareTo(forecastCalendar) == 1) { + iterator.remove(); + } + } - final String icon = weatherData.getWeather().getIcon(); - final String urlAPIicon = WeatherInformationOverviewFragment.this - .getResources().getString(R.string.uri_api_icon); - url = this.weatherService.createURIAPIicon(icon, urlAPIicon); - final byte[] iconData = this.weatherHTTPClient - .retrieveDataFromAPI(new URL(url)).toByteArray(); - weatherData.setIconData(iconData); + // 3. Today + urlAPI = WeatherInformationOverviewFragment.this.getResources().getString( + R.string.uri_api_weather_today); + url = this.weatherService.createURIAPITodayWeather(urlAPI, APIVersion, + geocodingData.getLatitude(), geocodingData.getLongitude()); + jsonData = this.weatherHTTPClient.retrieveDataAsString(new URL(url)); + final CurrentWeatherData currentWeatherData = this.weatherService + .retrieveCurrentWeatherDataFromJPOS(jsonData); + currentWeatherData.setDate(now.getTime()); + final WeatherData weatherData = new WeatherData(forecastWeatherData, currentWeatherData); return weatherData; } @@ -355,24 +434,29 @@ public class WeatherInformationOverviewFragment extends ListFragment implements private void onPostExecuteThrowable(final WeatherData weatherData) throws FileNotFoundException, IOException { WeatherInformationOverviewFragment.this.mWeatherServicePersistenceFile - .storeWeatherData(weatherData); + .storeForecastWeatherData(weatherData.getForecastWeatherData()); + WeatherInformationOverviewFragment.this.mWeatherServicePersistenceFile + .storeCurrentWeatherData(weatherData.getCurrentWeatherData()); - WeatherInformationOverviewFragment.this.updateWeatherData(weatherData); + WeatherInformationOverviewFragment.this.updateForecastWeatherData(weatherData); } } - private List createEmptyEntriesList() { - final List entries = new ArrayList(); - final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d", Locale.getDefault()); + private class WeatherData { + private final ForecastWeatherData forecastWeatherData; + private final CurrentWeatherData currentWeatherData; + + private WeatherData(final ForecastWeatherData forecastWeatherData, final CurrentWeatherData currentWeatherData) { + this.forecastWeatherData = forecastWeatherData; + this.currentWeatherData = currentWeatherData; + } - final Calendar now = Calendar.getInstance(); - for (int i = 0; i<15; i++) { - final Date day = now.getTime(); - entries.add(i, new WeatherOverviewEntry(dateFormat.format(day), - null, null, null, null)); - now.add(Calendar.DAY_OF_MONTH, 1); + private ForecastWeatherData getForecastWeatherData() { + return this.forecastWeatherData; } - return entries; + private CurrentWeatherData getCurrentWeatherData() { + return this.currentWeatherData; + } } } diff --git a/src/de/example/exampletdd/fragment/overview/WeatherOverviewAdapter.java b/src/de/example/exampletdd/fragment/overview/WeatherOverviewAdapter.java index 7f101d5..e053181 100644 --- a/src/de/example/exampletdd/fragment/overview/WeatherOverviewAdapter.java +++ b/src/de/example/exampletdd/fragment/overview/WeatherOverviewAdapter.java @@ -30,17 +30,12 @@ public class WeatherOverviewAdapter extends ArrayAdapter { final WeatherOverviewEntry entry = this.getItem(position); - // Setting the text view + // Setting date viewHolder.dateView.setText(entry.getDate()); - String maxTemp = ""; - if (entry.getMaxTemp() != null) { - maxTemp = entry.getMaxTemp() + "º"; - } - String minTemp = ""; - if (entry.getMinTemp() != null) { - minTemp = "/" + entry.getMinTemp() + "º"; - } - viewHolder.temperatureView.setText(maxTemp + minTemp); + + // Setting temperature max/min + viewHolder.temperatureView.setText(entry.getMaxTemp() + "/" + entry.getMinTemp()); + // Set image view viewHolder.pictureView.setImageBitmap(entry.getPicture()); diff --git a/src/de/example/exampletdd/fragment/overview/WeatherOverviewEntry.java b/src/de/example/exampletdd/fragment/overview/WeatherOverviewEntry.java index 2d2c710..3dfd92d 100644 --- a/src/de/example/exampletdd/fragment/overview/WeatherOverviewEntry.java +++ b/src/de/example/exampletdd/fragment/overview/WeatherOverviewEntry.java @@ -4,15 +4,13 @@ import android.graphics.Bitmap; public class WeatherOverviewEntry { private final String date; - private final String temperature; private final String maxTemp; private final String minTemp; private final Bitmap picture; - public WeatherOverviewEntry(final String date, final String temperature, - final String maxTemp, final String minTemp, final Bitmap picture) { + public WeatherOverviewEntry(final String date, final String maxTemp, final String minTemp, + final Bitmap picture) { this.date = date; - this.temperature = temperature; this.maxTemp = maxTemp; this.minTemp = minTemp; this.picture = picture; @@ -22,10 +20,6 @@ public class WeatherOverviewEntry { return this.date; } - public String getTemperature() { - return this.temperature; - } - public String getMaxTemp() { return this.maxTemp; } diff --git a/src/de/example/exampletdd/fragment/specific/WeatherInformationSpecificDataFragment.java b/src/de/example/exampletdd/fragment/specific/WeatherInformationSpecificDataFragment.java index 831adaf..19ea58f 100644 --- a/src/de/example/exampletdd/fragment/specific/WeatherInformationSpecificDataFragment.java +++ b/src/de/example/exampletdd/fragment/specific/WeatherInformationSpecificDataFragment.java @@ -25,27 +25,36 @@ import android.widget.ListView; import de.example.exampletdd.R; import de.example.exampletdd.activityinterface.GetWeather; import de.example.exampletdd.fragment.ErrorDialogFragment; -import de.example.exampletdd.model.WeatherData; +import de.example.exampletdd.model.currentweather.CurrentWeatherData; +import de.example.exampletdd.model.forecastweather.ForecastWeatherData; import de.example.exampletdd.service.WeatherServicePersistenceFile; public class WeatherInformationSpecificDataFragment extends Fragment implements GetWeather { private boolean mIsFahrenheit; - private String mLanguage; + private long mChosenDay; private WeatherServicePersistenceFile mWeatherServicePersistenceFile; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); + final Bundle extras = this.getActivity().getIntent().getExtras(); + + if (extras != null) { + this.mChosenDay = extras.getLong("CHOSEN_DAY", 0); + } else { + this.mChosenDay = 0; + } + this.mWeatherServicePersistenceFile = new WeatherServicePersistenceFile( this.getActivity()); - final SharedPreferences sharedPreferences = PreferenceManager - .getDefaultSharedPreferences(this.getActivity()); - final String keyPreference = this.getResources().getString( - R.string.weather_preferences_language_key); - this.mLanguage = sharedPreferences.getString( - keyPreference, ""); + // final SharedPreferences sharedPreferences = PreferenceManager + // .getDefaultSharedPreferences(this.getActivity()); + // final String keyPreference = this.getResources().getString( + // R.string.weather_preferences_language_key); + // this.mLanguage = sharedPreferences.getString( + // keyPreference, ""); } @Override @@ -74,14 +83,21 @@ public class WeatherInformationSpecificDataFragment extends Fragment implements if (savedInstanceState != null) { // Restore state - final WeatherData weatherData = (WeatherData) savedInstanceState - .getSerializable("weatherData"); - try { - this.mWeatherServicePersistenceFile.storeWeatherData(weatherData); - } catch (final IOException e) { - final DialogFragment newFragment = ErrorDialogFragment - .newInstance(R.string.error_dialog_generic_error); - newFragment.show(this.getFragmentManager(), "errorDialog"); + final ForecastWeatherData forecastWeatherData = (ForecastWeatherData) savedInstanceState + .getSerializable("ForecastWeatherData"); + final CurrentWeatherData currentWeatherData = (CurrentWeatherData) savedInstanceState + .getSerializable("CurrentWeatherData"); + + if ((forecastWeatherData != null) && (currentWeatherData != null)) { + try { + this.mWeatherServicePersistenceFile + .storeForecastWeatherData(forecastWeatherData); + this.mWeatherServicePersistenceFile.storeCurrentWeatherData(currentWeatherData); + } catch (final IOException e) { + final DialogFragment newFragment = ErrorDialogFragment + .newInstance(R.string.error_dialog_generic_error); + newFragment.show(this.getFragmentManager(), "errorDialog"); + } } } } @@ -90,26 +106,44 @@ public class WeatherInformationSpecificDataFragment extends Fragment implements public void onSaveInstanceState(final Bundle savedInstanceState) { // Save state - final WeatherData weatherData = this.mWeatherServicePersistenceFile.getWeatherData(); + final ForecastWeatherData forecastWeatherData = this.mWeatherServicePersistenceFile + .getForecastWeatherData(); + final CurrentWeatherData currentWeatherData = this.mWeatherServicePersistenceFile + .getCurrentWeatherData(); - if (weatherData != null) { - savedInstanceState.putSerializable("weatherData", weatherData); + if ((forecastWeatherData != null) && (currentWeatherData != null)) { + savedInstanceState.putSerializable("ForecastWeatherData", forecastWeatherData); + savedInstanceState.putSerializable("CurrentWeatherData", currentWeatherData); } super.onSaveInstanceState(savedInstanceState); } @Override - public void getWeather() { - final WeatherData weatherData = this.mWeatherServicePersistenceFile.getWeatherData(); + public void getWeatherByDay(final int chosenDay) { + if (chosenDay == 0) { + final CurrentWeatherData currentWeatherData = this.mWeatherServicePersistenceFile + .getCurrentWeatherData(); - if (weatherData != null) { - this.updateWeatherData(weatherData); + if (currentWeatherData != null) { + this.updateCurrentWeatherData(currentWeatherData); + } + } else { + final ForecastWeatherData forecastWeatherData = this.mWeatherServicePersistenceFile + .getForecastWeatherData(); + if (forecastWeatherData != null) { + this.updateForecastWeatherData(forecastWeatherData, chosenDay); + } } } - public void updateWeatherData(final WeatherData weatherData) { + @Override + public void getRemoteWeatherInformation() { + // Nothing to do. + } + + public void updateCurrentWeatherData(final CurrentWeatherData currentWeatherData) { final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.getDefault()); tempFormatter.applyPattern("#####.#####"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss Z", Locale.getDefault()); @@ -124,41 +158,61 @@ public class WeatherInformationSpecificDataFragment extends Fragment implements final WeatherSpecificDataAdapter adapter = new WeatherSpecificDataAdapter(this.getActivity(), R.layout.weather_data_entry_list); - if (weatherData.getWeather() != null) { - entries.set(0, new WeatherSpecificDataEntry(this.getString(R.string.text_field_description), weatherData.getWeather() - .getDescription())); - double conversion = weatherData.getMain().getTemp(); + if (currentWeatherData.getWeather().size() > 0) { + entries.set(0, new WeatherSpecificDataEntry(this.getString(R.string.text_field_description), + currentWeatherData.getWeather().get(0).getDescription())); + } + + if (currentWeatherData.getMain().getTemp() != null) { + double conversion = (Double) currentWeatherData.getMain().getTemp(); conversion = conversion - tempUnits; - entries.set(1, new WeatherSpecificDataEntry(this.getString(R.string.text_field_tem), tempFormatter.format(conversion))); - conversion = weatherData.getMain().getMaxTemp(); + entries.set(1, new WeatherSpecificDataEntry(this.getString(R.string.text_field_tem), + tempFormatter.format(conversion))); + } + + if (currentWeatherData.getMain().getTemp_max() != null) { + double conversion = (Double) currentWeatherData.getMain().getTemp_max(); conversion = conversion - tempUnits; - entries.set(2, new WeatherSpecificDataEntry(this.getString(R.string.text_field_tem_max), tempFormatter.format(conversion))); - conversion = weatherData.getMain().getMinTemp(); + entries.set(2, new WeatherSpecificDataEntry( + this.getString(R.string.text_field_tem_max), tempFormatter.format(conversion))); + } + + if (currentWeatherData.getMain().getTemp_max() != null) { + double conversion = (Double) currentWeatherData.getMain().getTemp_min(); conversion = conversion - tempUnits; - entries.set(3, new WeatherSpecificDataEntry(this.getString(R.string.text_field_tem_min), tempFormatter.format(conversion))); + entries.set(3, new WeatherSpecificDataEntry( + this.getString(R.string.text_field_tem_min), tempFormatter.format(conversion))); } - if (weatherData.getSystem() != null) { - long unixTime = weatherData.getSystem().getSunRiseTime(); - Date unixDate = new Date(unixTime * 1000L); - String dateFormatUnix = dateFormat.format(unixDate); - entries.set(4, new WeatherSpecificDataEntry(this.getString(R.string.text_field_sun_rise), dateFormatUnix)); - unixTime = weatherData.getSystem().getSunSetTime(); - unixDate = new Date(unixTime * 1000L); - dateFormatUnix = dateFormat.format(unixDate); - entries.set(5, new WeatherSpecificDataEntry(this.getString(R.string.text_field_sun_set), dateFormatUnix)); + if (currentWeatherData.getSys().getSunrise() != null) { + final long unixTime = (Long) currentWeatherData.getSys().getSunrise(); + final Date unixDate = new Date(unixTime * 1000L); + final String dateFormatUnix = dateFormat.format(unixDate); + entries.set(4, + new WeatherSpecificDataEntry(this.getString(R.string.text_field_sun_rise), + dateFormatUnix)); } - if (weatherData.getClouds() != null) { - final double cloudiness = weatherData.getClouds().getCloudiness(); - entries.set(6, new WeatherSpecificDataEntry(this.getString(R.string.text_field_cloudiness), tempFormatter.format(cloudiness))); + if (currentWeatherData.getSys().getSunset() != null) { + final long unixTime = (Long) currentWeatherData.getSys().getSunset(); + final Date unixDate = new Date(unixTime * 1000L); + final String dateFormatUnix = dateFormat.format(unixDate); + entries.set(5, new WeatherSpecificDataEntry( + this.getString(R.string.text_field_sun_set), dateFormatUnix)); } - if (weatherData.getWeather().getIcon() != null) { + if (currentWeatherData.getClouds().getAll() != null) { + final double cloudiness = (Double) currentWeatherData.getClouds().getAll(); + entries.set(6, + new WeatherSpecificDataEntry(this.getString(R.string.text_field_cloudiness), + tempFormatter.format(cloudiness))); + } + + if (currentWeatherData.getIconData() != null) { final Bitmap icon = BitmapFactory.decodeByteArray( - weatherData.getIconData(), 0, - weatherData.getIconData().length); + currentWeatherData.getIconData(), 0, + currentWeatherData.getIconData().length); final ImageView imageIcon = (ImageView) this.getActivity() .findViewById(R.id.weather_picture); imageIcon.setImageBitmap(icon); @@ -171,6 +225,70 @@ public class WeatherInformationSpecificDataFragment extends Fragment implements listWeatherView.setAdapter(adapter); } + public void updateForecastWeatherData(final ForecastWeatherData forecastWeatherData, + final int chosenDay) { + final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale + .getDefault()); + tempFormatter.applyPattern("#####.#####"); + final double tempUnits = this.mIsFahrenheit ? 0 : 273.15; + + final List entries = this.createEmptyEntriesList(); + final ListView listWeatherView = (ListView) this.getActivity().findViewById( + R.id.weather_data_list_view); + final WeatherSpecificDataAdapter adapter = new WeatherSpecificDataAdapter( + this.getActivity(), R.layout.weather_data_entry_list); + + + final int forecastSize = forecastWeatherData.getList().size(); + if (chosenDay > forecastSize) { + // Nothing to do. + return; + } + + + final de.example.exampletdd.model.forecastweather.List forecast = forecastWeatherData + .getList().get((chosenDay - 1)); + + if (forecast.getWeather().size() > 0) { + entries.set(0, + new WeatherSpecificDataEntry(this.getString(R.string.text_field_description), + forecast.getWeather().get(0).getDescription())); + } + + if (forecast.getTemp().getDay() != null) { + double conversion = (Double) forecast.getTemp().getDay(); + conversion = conversion - tempUnits; + entries.set(1, new WeatherSpecificDataEntry(this.getString(R.string.text_field_tem), + tempFormatter.format(conversion))); + } + + if (forecast.getTemp().getMax() != null) { + double conversion = (Double) forecast.getTemp().getMax(); + conversion = conversion - tempUnits; + entries.set(2, new WeatherSpecificDataEntry( + this.getString(R.string.text_field_tem_max), tempFormatter.format(conversion))); + } + + if (forecast.getTemp().getMin() != null) { + double conversion = (Double) forecast.getTemp().getMin(); + conversion = conversion - tempUnits; + entries.set(3, new WeatherSpecificDataEntry( + this.getString(R.string.text_field_tem_min), tempFormatter.format(conversion))); + } + + + if (forecast.getClouds() != null) { + final double cloudiness = (Double) forecast.getClouds(); + entries.set(6, + new WeatherSpecificDataEntry(this.getString(R.string.text_field_cloudiness), + tempFormatter.format(cloudiness))); + } + + listWeatherView.setAdapter(null); + adapter.addAll(entries); + listWeatherView.setAdapter(adapter); + } + @Override public void onResume() { super.onResume(); @@ -179,7 +297,7 @@ public class WeatherInformationSpecificDataFragment extends Fragment implements .getDefaultSharedPreferences(this.getActivity()); // 1. Update units of measurement. - String keyPreference = this.getResources().getString( + final String keyPreference = this.getResources().getString( R.string.weather_preferences_units_key); final String unitsPreferenceValue = sharedPreferences.getString(keyPreference, ""); final String celsius = this.getResources().getString( @@ -191,24 +309,33 @@ public class WeatherInformationSpecificDataFragment extends Fragment implements } - // 2. Update current data on display. - final WeatherData weatherData = this.mWeatherServicePersistenceFile.getWeatherData(); + // 2. Update weather data on display. + if (this.mChosenDay == 0) { + final CurrentWeatherData currentWeatherData = this.mWeatherServicePersistenceFile + .getCurrentWeatherData(); - if (weatherData != null) { - this.updateWeatherData(weatherData); + if (currentWeatherData != null) { + this.updateCurrentWeatherData(currentWeatherData); + } + } else { + final ForecastWeatherData forecastWeatherData = this.mWeatherServicePersistenceFile + .getForecastWeatherData(); + if (forecastWeatherData != null) { + this.updateForecastWeatherData(forecastWeatherData, (int) this.mChosenDay); + } } // 3. If language changed, try to retrieve new data for new language // (new strings with the chosen language) - keyPreference = this.getResources().getString( - R.string.weather_preferences_language_key); - final String languagePreferenceValue = sharedPreferences.getString( - keyPreference, ""); - if (!languagePreferenceValue.equals(this.mLanguage)) { - this.mLanguage = languagePreferenceValue; - this.getWeather(); - } + // keyPreference = this.getResources().getString( + // R.string.weather_preferences_language_key); + // final String languagePreferenceValue = sharedPreferences.getString( + // keyPreference, ""); + // if (!languagePreferenceValue.equals(this.mLanguage)) { + // this.mLanguage = languagePreferenceValue; + // this.getWeather(); + // } } private List createEmptyEntriesList() { diff --git a/src/de/example/exampletdd/httpclient/Consts.java b/src/de/example/exampletdd/httpclient/Consts.java new file mode 100644 index 0000000..614849f --- /dev/null +++ b/src/de/example/exampletdd/httpclient/Consts.java @@ -0,0 +1,51 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ + +package de.example.exampletdd.httpclient; + +import java.nio.charset.Charset; + +/** + * Commons constants. + * + * @since 4.2 + */ +public final class Consts { + + public static final int CR = 13; // + public static final int LF = 10; // + public static final int SP = 32; // + public static final int HT = 9; // + + public static final Charset UTF_8 = Charset.forName("UTF-8"); + public static final Charset ASCII = Charset.forName("US-ASCII"); + public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); + + private Consts() { + } + +} diff --git a/src/de/example/exampletdd/httpclient/ContentType.java b/src/de/example/exampletdd/httpclient/ContentType.java new file mode 100644 index 0000000..8c02532 --- /dev/null +++ b/src/de/example/exampletdd/httpclient/ContentType.java @@ -0,0 +1,248 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ + +package de.example.exampletdd.httpclient; + +import java.nio.charset.Charset; +import java.nio.charset.UnsupportedCharsetException; +import java.util.Locale; + +import org.apache.http.Header; +import org.apache.http.HeaderElement; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.ParseException; +import org.apache.http.message.BasicHeaderValueParser; + +/** + * Content type information consisting of a MIME type and an optional charset. + *

+ * This class makes no attempts to verify validity of the MIME type. + * The input parameters of the {@link #create(String, String)} method, however, may not + * contain characters <">, <;>, <,> reserved by the HTTP specification. + * + * @since 4.2 + */ + +public final class ContentType { + + // constants + public static final ContentType APPLICATION_ATOM_XML = create( + "application/atom+xml", Consts.ISO_8859_1); + public static final ContentType APPLICATION_FORM_URLENCODED = create( + "application/x-www-form-urlencoded", Consts.ISO_8859_1); + public static final ContentType APPLICATION_JSON = create( + "application/json", Consts.UTF_8); + public static final ContentType APPLICATION_OCTET_STREAM = create( + "application/octet-stream", (Charset) null); + public static final ContentType APPLICATION_SVG_XML = create( + "application/svg+xml", Consts.ISO_8859_1); + public static final ContentType APPLICATION_XHTML_XML = create( + "application/xhtml+xml", Consts.ISO_8859_1); + public static final ContentType APPLICATION_XML = create( + "application/xml", Consts.ISO_8859_1); + public static final ContentType MULTIPART_FORM_DATA = create( + "multipart/form-data", Consts.ISO_8859_1); + public static final ContentType TEXT_HTML = create( + "text/html", Consts.ISO_8859_1); + public static final ContentType TEXT_PLAIN = create( + "text/plain", Consts.ISO_8859_1); + public static final ContentType TEXT_XML = create( + "text/xml", Consts.ISO_8859_1); + public static final ContentType WILDCARD = create( + "*/*", (Charset) null); + + // defaults + public static final ContentType DEFAULT_TEXT = TEXT_PLAIN; + public static final ContentType DEFAULT_BINARY = APPLICATION_OCTET_STREAM; + + private final String mimeType; + private final Charset charset; + + /** + * Given a MIME type and a character set, constructs a ContentType. + * @param mimeType The MIME type to use for the ContentType header. + * @param charset The optional character set to use with the ContentType header. + * @throws UnsupportedCharsetException + * If no support for the named charset is available in this Java virtual machine + */ + ContentType(final String mimeType, final Charset charset) { + this.mimeType = mimeType; + this.charset = charset; + } + + public String getMimeType() { + return this.mimeType; + } + + public Charset getCharset() { + return this.charset; + } + + /** + * Converts a ContentType to a string which can be used as a ContentType header. + * If a charset is provided by the ContentType, it will be included in the string. + */ + @Override + public String toString() { + final StringBuilder buf = new StringBuilder(); + buf.append(this.mimeType); + if (this.charset != null) { + buf.append("; charset="); + buf.append(this.charset); + } + return buf.toString(); + } + + private static boolean valid(final String s) { + for (int i = 0; i < s.length(); i++) { + final char ch = s.charAt(i); + if ((ch == '"') || (ch == ',') || (ch == ';')) { + return false; + } + } + return true; + } + + /** + * Creates a new instance of {@link ContentType}. + * + * @param mimeType MIME type. It may not be null or empty. It may not contain + * characters <">, <;>, <,> reserved by the HTTP specification. + * @param charset charset. + * @return content type + */ + public static ContentType create(final String mimeType, final Charset charset) { + if (mimeType == null) { + throw new IllegalArgumentException("MIME type may not be null"); + } + final String type = mimeType.trim().toLowerCase(Locale.US); + if (type.length() == 0) { + throw new IllegalArgumentException("MIME type may not be empty"); + } + if (!valid(type)) { + throw new IllegalArgumentException("MIME type may not contain reserved characters"); + } + return new ContentType(type, charset); + } + + /** + * Creates a new instance of {@link ContentType} without a charset. + * + * @param mimeType MIME type. It may not be null or empty. It may not contain + * characters <">, <;>, <,> reserved by the HTTP specification. + * @return content type + */ + public static ContentType create(final String mimeType) { + return new ContentType(mimeType, (Charset) null); + } + + /** + * Creates a new instance of {@link ContentType}. + * + * @param mimeType MIME type. It may not be null or empty. It may not contain + * characters <">, <;>, <,> reserved by the HTTP specification. + * @param charset charset. It may not contain characters <">, <;>, <,> reserved by the HTTP + * specification. This parameter is optional. + * @return content type + */ + public static ContentType create( + final String mimeType, final String charset) throws UnsupportedCharsetException { + return create(mimeType, charset != null ? Charset.forName(charset) : null); + } + + private static ContentType create(final HeaderElement helem) { + final String mimeType = helem.getName(); + String charset = null; + final NameValuePair param = helem.getParameterByName("charset"); + if (param != null) { + charset = param.getValue(); + } + return create(mimeType, charset); + } + + /** + * Parses textual representation of Content-Type value. + * + * @param s text + * @return content type + * @throws ParseException if the given text does not represent a valid + * Content-Type value. + */ + public static ContentType parse( + final String s) throws ParseException, UnsupportedCharsetException { + if (s == null) { + throw new IllegalArgumentException("Content type may not be null"); + } + final HeaderElement[] elements = BasicHeaderValueParser.parseElements(s, null); + if (elements.length > 0) { + return create(elements[0]); + } else { + throw new ParseException("Invalid content type: " + s); + } + } + + /** + * Extracts Content-Type value from {@link HttpEntity} exactly as + * specified by the Content-Type header of the entity. Returns null + * if not specified. + * + * @param entity HTTP entity + * @return content type + * @throws ParseException if the given text does not represent a valid + * Content-Type value. + */ + public static ContentType get( + final HttpEntity entity) throws ParseException, UnsupportedCharsetException { + if (entity == null) { + return null; + } + final Header header = entity.getContentType(); + if (header != null) { + final HeaderElement[] elements = header.getElements(); + if (elements.length > 0) { + return create(elements[0]); + } + } + return null; + } + + /** + * Extracts Content-Type value from {@link HttpEntity} or returns default value + * if not explicitly specified. + * + * @param entity HTTP entity + * @return content type + * @throws ParseException if the given text does not represent a valid + * Content-Type value. + */ + public static ContentType getOrDefault(final HttpEntity entity) throws ParseException { + final ContentType contentType = get(entity); + return contentType != null ? contentType : DEFAULT_TEXT; + } + +} diff --git a/src/de/example/exampletdd/httpclient/CustomHTTPClient.java b/src/de/example/exampletdd/httpclient/CustomHTTPClient.java new file mode 100644 index 0000000..14d0b85 --- /dev/null +++ b/src/de/example/exampletdd/httpclient/CustomHTTPClient.java @@ -0,0 +1,123 @@ +package de.example.exampletdd.httpclient; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URISyntaxException; +import java.net.URL; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.methods.HttpGet; + +import android.net.http.AndroidHttpClient; + +public class CustomHTTPClient { + private final AndroidHttpClient httpClient; + + public CustomHTTPClient(final AndroidHttpClient httpClient) { + this.httpClient = httpClient; + } + + public String retrieveDataAsString(final URL url) + throws URISyntaxException, ClientProtocolException, IOException { + + final ResponseHandler handler = new ResponseHandler() { + @Override + public String handleResponse( + final HttpResponse response) + throws UnsupportedEncodingException, IOException { + + if (response != null) { + final HttpEntity entity = response.getEntity(); + if (entity != null) { + final ContentType contentType = ContentType.getOrDefault(entity); + final ByteArrayOutputStream buffer = CustomHTTPClient.this + .sortResponse(response); + return new String(buffer.toByteArray(), contentType.getCharset()); + } + + throw new IOException("There is no entity"); + } + + throw new IOException("There is no response"); + } + }; + + final HttpGet httpGet = new HttpGet(); + httpGet.setURI(url.toURI()); + + return this.httpClient.execute(httpGet, handler); + } + + public ByteArrayOutputStream retrieveRawData(final URL url) + throws URISyntaxException, ClientProtocolException, IOException { + final ResponseHandler handler = new ResponseHandler() { + + @Override + public ByteArrayOutputStream handleResponse( + final HttpResponse response) + throws UnsupportedEncodingException, IOException { + + if (response != null) { + final HttpEntity entity = response.getEntity(); + if (entity != null) { + return CustomHTTPClient.this.sortResponse(response); + } + + throw new IOException("There is no entity"); + } + + throw new IOException("There is no response"); + } + }; + + final HttpGet httpGet = new HttpGet(); + httpGet.setURI(url.toURI()); + + return this.httpClient.execute(httpGet, handler); + } + + public ByteArrayOutputStream sortResponse(final HttpResponse httpResponse) + throws IOException { + + if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + final HttpEntity entity = httpResponse.getEntity(); + if (entity != null) { + try { + return this.readInputStream(entity.getContent()); + } finally { + entity.consumeContent(); + } + } + } + + throw new IOException("Unexpected response code: " + + httpResponse.getStatusLine().getStatusCode()); + } + + public void close() { + this.httpClient.close(); + } + + private ByteArrayOutputStream readInputStream (final InputStream inputStream) throws IOException { + final ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); + final int bufferSize = 1024; + final byte[] buffer = new byte[bufferSize]; + + try { + int len = 0; + while ((len = inputStream.read(buffer)) != -1) { + byteBuffer.write(buffer, 0, len); + } + }finally { + inputStream.close(); + } + + return byteBuffer; + } +} diff --git a/src/de/example/exampletdd/httpclient/WeatherHTTPClient.java b/src/de/example/exampletdd/httpclient/WeatherHTTPClient.java deleted file mode 100644 index de36985..0000000 --- a/src/de/example/exampletdd/httpclient/WeatherHTTPClient.java +++ /dev/null @@ -1,126 +0,0 @@ -package de.example.exampletdd.httpclient; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.URISyntaxException; -import java.net.URL; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.ResponseHandler; -import org.apache.http.client.methods.HttpGet; - -import android.net.http.AndroidHttpClient; - -public class WeatherHTTPClient { - private final AndroidHttpClient httpClient; - - public WeatherHTTPClient(final AndroidHttpClient httpClient) { - this.httpClient = httpClient; - } - - public String retrieveJSONDataFromAPI(final URL url) - throws URISyntaxException, ClientProtocolException, IOException { - - final ResponseHandler handler = new ResponseHandler() { - @Override - public String handleResponse( - final HttpResponse response) - throws UnsupportedEncodingException, IOException { - - if (response != null) { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - // Not receiving encoding :( - // final String contentEncoding = entity - // .getContentEncoding() - // .getValue(); - final ByteArrayOutputStream buffer = WeatherHTTPClient.this - .sortResponse(response); - return new String(buffer.toByteArray(), "UTF-8"); - } - - throw new IOException("There is no entity"); - } - - throw new IOException("There is no response"); - } - }; - - final HttpGet httpGet = new HttpGet(); - httpGet.setURI(url.toURI()); - - return this.httpClient.execute(httpGet, handler); - } - - public ByteArrayOutputStream retrieveDataFromAPI(final URL url) - throws URISyntaxException, ClientProtocolException, IOException { - final ResponseHandler handler = new ResponseHandler() { - - @Override - public ByteArrayOutputStream handleResponse( - final HttpResponse response) - throws UnsupportedEncodingException, IOException { - - if (response != null) { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - return WeatherHTTPClient.this.sortResponse(response); - } - - throw new IOException("There is no entity"); - } - - throw new IOException("There is no response"); - } - }; - - final HttpGet httpGet = new HttpGet(); - httpGet.setURI(url.toURI()); - - return this.httpClient.execute(httpGet, handler); - } - - public ByteArrayOutputStream sortResponse(final HttpResponse httpResponse) - throws IOException { - - if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { - final HttpEntity entity = httpResponse.getEntity(); - if (entity != null) { - try { - return this.readInputStream(entity.getContent()); - } finally { - entity.consumeContent(); - } - } - } - - throw new IOException("Unexpected response code: " - + httpResponse.getStatusLine().getStatusCode()); - } - - public void close() { - this.httpClient.close(); - } - - private ByteArrayOutputStream readInputStream (final InputStream inputStream) throws IOException { - final ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); - final int bufferSize = 1024; - final byte[] buffer = new byte[bufferSize]; - - try { - int len = 0; - while ((len = inputStream.read(buffer)) != -1) { - byteBuffer.write(buffer, 0, len); - } - }finally { - inputStream.close(); - } - - return byteBuffer; - } -} diff --git a/src/de/example/exampletdd/model/WeatherData.java b/src/de/example/exampletdd/model/WeatherData.java deleted file mode 100644 index d198e4b..0000000 --- a/src/de/example/exampletdd/model/WeatherData.java +++ /dev/null @@ -1,482 +0,0 @@ -package de.example.exampletdd.model; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.Date; - - -public class WeatherData implements Serializable { - private static final long serialVersionUID = -3521472950666173278L; - private final Main main; - private final Wind wind; - private final Rain rain; - private final Coord coord; - private final DataReceivingTime dataReceivingTime; - private final StationName stationName; - private final System system; - private final Clouds clouds; - private final Weather weather; - private byte[] iconData; - private final Date date; - - - public static class Builder { - //Optional parameters - private Main mMain; - private Wind mWind; - private Rain mRain; - private Coord mCoord; - private DataReceivingTime mDataReceivingTime; - private StationName mStationName; - private System mSystem; - private Clouds mClouds; - private Weather mWeather; - private Date mDate; - - - public Builder setMain(final Main main) { - this.mMain = main; - return this; - } - - public Builder setWind(final Wind wind) { - this.mWind = wind; - return this; - } - - public Builder setRain(final Rain rain) { - this.mRain = rain; - return this; - } - - public Builder setCoord(final Coord coord) { - this.mCoord = coord; - return this; - } - - public Builder setDataReceivingTime( - final DataReceivingTime dataReceivingTime) { - this.mDataReceivingTime = dataReceivingTime; - return this; - } - - public Builder setStationName(final StationName stationName) { - this.mStationName = stationName; - return this; - } - - public Builder setSystem(final System system) { - this.mSystem = system; - return this; - } - - public Builder setClouds(final Clouds clouds) { - this.mClouds = clouds; - return this; - } - - public Builder setWeather(final Weather weather) { - this.mWeather = weather; - return this; - } - - public Builder setDate(final Date date) { - this.mDate = date; - return this; - } - - public WeatherData build() { - return new WeatherData(this); - } - } - - private WeatherData(final Builder builder) { - this.main = builder.mMain; - this.wind = builder.mWind; - this.rain = builder.mRain; - this.coord = builder.mCoord; - this.dataReceivingTime = builder.mDataReceivingTime; - this.stationName = builder.mStationName; - this.system = builder.mSystem; - this.clouds = builder.mClouds; - this.weather = builder.mWeather; - this.date = builder.mDate; - } - - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("WeatherData [main=").append(main) - .append(", wind=").append(wind).append(", rain=").append(rain) - .append(", coord=").append(coord).append(", dataReceivingTime=") - .append(dataReceivingTime).append(", stationName=").append(stationName) - .append(", system=").append(system).append(", clouds=") - .append(clouds).append(", weather=").append(weather) - .append(", iconData=").append(Arrays.toString(iconData)) - .append(", date=").append(date).append("]"); - return builder.toString(); - } - - public Main getMain() { - return this.main; - } - - public Wind getWind() { - return this.wind; - } - - public Rain getRain() { - return this.rain; - } - - public Coord getCoord() { - return this.coord; - } - - public DataReceivingTime getDataReceivingTime() { - return this.dataReceivingTime; - } - - public StationName getStationName() { - return this.stationName; - } - - public System getSystem() { - return this.system; - } - - public Clouds getClouds() { - return this.clouds; - } - - public Weather getWeather() { - return this.weather; - } - - public void setIconData(final byte[] iconData) { - this.iconData = iconData; - } - - public byte[] getIconData() { - return this.iconData; - } - - public Date getDate() { - return this.date; - } - - public static class Main implements Serializable { - private static final long serialVersionUID = -1632181871917583409L; - private final double temp; - // Minimum temperature - private final double minTemp; - // Maximum temperature - private final double maxTemp; - // Humidity in % - private final double humidity; - // Atmospheric pressure in kPa - private final double pressure; - - public Main(final double temp, final double minTemp, final double maxTemp, - final double humidity, final double pressure) { - this.temp = temp; - this.minTemp = minTemp; - this.maxTemp = maxTemp; - this.humidity = humidity; - this.pressure = pressure; - } - - public double getTemp() { - return this.temp; - } - - public double getMinTemp() { - return this.minTemp; - } - - public double getMaxTemp() { - return this.maxTemp; - } - - public double getHumidity() { - return this.humidity; - } - - public double getPressure() { - return this.pressure; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Main [temp=").append(this.temp) - .append(", minTemp=").append(this.minTemp) - .append(", maxTemp=").append(this.maxTemp) - .append(", humidity=").append(this.humidity) - .append(", pressure=").append(this.pressure).append("]"); - return builder.toString(); - } - } - - public static class Wind implements Serializable { - private static final long serialVersionUID = -5960066625859236765L; - // Wind speed in mps - private final double speed; - // Wind direction in degrees (meteorological) - private final double deg; - // speed of wind gust - private final double gust; - // Wind direction - private final double var_beg; - // Wind direction - private final double var_end; - - public Wind(final double speed, final double deg, final double gust, - final double var_beg, final double var_end) { - this.speed = speed; - this.deg = deg; - this.gust = gust; - this.var_beg = var_beg; - this.var_end = var_end; - } - - public double getSpeed() { - return this.speed; - } - - public double getDeg() { - return this.deg; - } - - public double getGust() { - return this.gust; - } - - public double getVar_beg() { - return this.var_beg; - } - - public double getVar_end() { - return this.var_end; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Wind [speed=").append(this.speed).append(", deg=") - .append(this.deg).append(", gust=").append(this.gust) - .append(", var_beg=").append(this.var_beg) - .append(", var_end=").append(this.var_end).append("]"); - return builder.toString(); - } - } - - public static class Rain implements Serializable { - private static final long serialVersionUID = 8975457888483866531L; - // Period - private final String time; - // Precipitation volume for period - private final double ammount; - - public Rain(final String time, final double ammount) { - this.time = time; - this.ammount = ammount; - } - - public String getTime() { - return this.time; - } - - public double getAmmount() { - return this.ammount; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Rain [time=").append(this.time) - .append(", ammount=").append(this.ammount).append("]"); - return builder.toString(); - } - - } - - public static class Coord implements Serializable { - private static final long serialVersionUID = 1462850471835376903L; - // City location - private final double longitude; - private final double latitude; - - public Coord(final double longitude, final double latitude) { - this.longitude = longitude; - this.latitude = latitude; - } - - public double getLongitude() { - return this.longitude; - } - - public double getLatitude() { - return this.latitude; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Coord [longitude=").append(this.longitude) - .append(", latitude=").append(this.latitude).append("]"); - return builder.toString(); - } - } - - public static class DataReceivingTime implements Serializable { - private static final long serialVersionUID = 1953087163647283008L; - // Time of data receiving in unixtime GMT - private final double time; - - public DataReceivingTime(final double time) { - this.time = time; - } - - public double getTime() { - return this.time; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("DataReceivingTime [time=").append(this.time) - .append("]"); - return builder.toString(); - } - } - - public static class StationName implements Serializable { - private static final long serialVersionUID = -1064381425887709851L; - private final String name; - - public StationName(final String name) { - this.name = name; - } - - public String getName() { - return this.name; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("StationName [name=").append(this.name).append("]"); - return builder.toString(); - } - } - - public static class System implements Serializable { - private static final long serialVersionUID = 6066763201061358078L; - private final String country; - // Unixtime GMT - private final long sunRiseTime; - // Unixtime GMT - private final long sunSetTime; - private final double message; - - public System(final String country, final long sunRiseTime, - final long sunSetTime, final double message) { - this.country = country; - this.sunRiseTime = sunRiseTime; - this.sunSetTime = sunSetTime; - this.message = message; - } - - public String getCountry() { - return this.country; - } - - public long getSunRiseTime() { - return this.sunRiseTime; - } - - public long getSunSetTime() { - return this.sunSetTime; - } - - public double getMessage() { - return this.message; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("System [country=").append(this.country) - .append(", sunRiseTime=").append(this.sunRiseTime) - .append(", sunSetTime=").append(this.sunSetTime) - .append(", message=").append(this.message).append("]"); - return builder.toString(); - } - } - - public static class Clouds implements Serializable { - private static final long serialVersionUID = 8787321588449154348L; - // Cloudiness in % - private final double cloudiness; - - public Clouds(final double cloudiness) { - this.cloudiness = cloudiness; - } - - public double getCloudiness() { - return this.cloudiness; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Clouds [cloudiness=").append(this.cloudiness) - .append("]"); - return builder.toString(); - } - } - - public static class Weather implements Serializable { - private static final long serialVersionUID = 6386458126182895773L; - private final int weatherId; - private final String main; - private final String description; - private final String icon; - - public Weather(final int weatherId, final String main, - final String description, final String icon) { - this.weatherId = weatherId; - this.main = main; - this.description = description; - this.icon = icon; - } - - public int getWeatherId() { - return this.weatherId; - } - - public String getMain() { - return this.main; - } - - public String getDescription() { - return this.description; - } - - public String getIcon() { - return this.icon; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Weather [weatherId=").append(this.weatherId) - .append(", main=").append(this.main) - .append(", description=").append(this.description) - .append(", icon=").append(this.icon).append("]"); - return builder.toString(); - } - } -} diff --git a/src/de/example/exampletdd/model/currentweather/Clouds.java b/src/de/example/exampletdd/model/currentweather/Clouds.java new file mode 100644 index 0000000..8da14c3 --- /dev/null +++ b/src/de/example/exampletdd/model/currentweather/Clouds.java @@ -0,0 +1,22 @@ +package de.example.exampletdd.model.currentweather; + +import java.io.Serializable; + +public class Clouds implements Serializable { + private static final long serialVersionUID = 3034435739326030899L; + private Number all; + + public Number getAll(){ + return this.all; + } + public void setAll(final Number all){ + this.all = all; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Clouds [all=").append(this.all).append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/currentweather/Coord.java b/src/de/example/exampletdd/model/currentweather/Coord.java new file mode 100644 index 0000000..9eececd --- /dev/null +++ b/src/de/example/exampletdd/model/currentweather/Coord.java @@ -0,0 +1,30 @@ +package de.example.exampletdd.model.currentweather; + +import java.io.Serializable; + +public class Coord implements Serializable { + private static final long serialVersionUID = 7151637605146377486L; + private Number lat; + private Number lon; + + public Number getLat(){ + return this.lat; + } + public void setLat(final Number lat){ + this.lat = lat; + } + public Number getLon(){ + return this.lon; + } + public void setLon(final Number lon){ + this.lon = lon; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Coord [lat=").append(this.lat).append(", lon=").append(this.lon) + .append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/currentweather/CurrentWeatherData.java b/src/de/example/exampletdd/model/currentweather/CurrentWeatherData.java new file mode 100644 index 0000000..d6d042c --- /dev/null +++ b/src/de/example/exampletdd/model/currentweather/CurrentWeatherData.java @@ -0,0 +1,139 @@ +package de.example.exampletdd.model.currentweather; + +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +/** + * Auto generated by: http://jsongen.byingtondesign.com/ + * (with my own modifications) + * + */ +public class CurrentWeatherData implements Serializable { + private static final long serialVersionUID = -730690341739860818L; + private String base; + private Clouds clouds; + private Number cod; + private Coord coord; + private Number dt; + private Number id; + private Main main; + private String name; + private Rain rain; + private Snow snow; + private Sys sys; + private List weather; + private Wind wind; + private byte[] iconData; + private Date date; + + public String getBase(){ + return this.base; + } + public void setBase(final String base){ + this.base = base; + } + public Clouds getClouds(){ + return this.clouds; + } + public void setClouds(final Clouds clouds){ + this.clouds = clouds; + } + + public Number getCod() { + return this.cod; + } + + public void setCod(final Number cod) { + this.cod = cod; + } + public Coord getCoord(){ + return this.coord; + } + public void setCoord(final Coord coord){ + this.coord = coord; + } + public Number getDt(){ + return this.dt; + } + public void setDt(final Number dt){ + this.dt = dt; + } + public Number getId(){ + return this.id; + } + public void setId(final Number id){ + this.id = id; + } + public Main getMain(){ + return this.main; + } + public void setMain(final Main main){ + this.main = main; + } + public String getName(){ + return this.name; + } + public void setName(final String name){ + this.name = name; + } + public Rain getRain(){ + return this.rain; + } + public void setRain(final Rain rain){ + this.rain = rain; + } + public Snow getSnow() { + return this.snow; + } + public void setSnow(final Snow snow) { + this.snow = snow; + } + public Sys getSys(){ + return this.sys; + } + public void setSys(final Sys sys){ + this.sys = sys; + } + public List getWeather(){ + return this.weather; + } + public void setWeather(final List weather){ + this.weather = weather; + } + public Wind getWind(){ + return this.wind; + } + public void setWind(final Wind wind){ + this.wind = wind; + } + + public byte[] getIconData() { + return this.iconData; + } + + public void setIconData(final byte[] iconData) { + this.iconData = iconData; + } + + public Date getDate() { + return this.date; + } + + public void setDate(final Date date) { + this.date = date; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("CurrentWeatherData [base=").append(this.base).append(", clouds=") + .append(this.clouds).append(", cod=").append(this.cod).append(", coord=") + .append(this.coord).append(", dt=").append(this.dt).append(", id=").append(this.id) + .append(", main=").append(this.main).append(", name=").append(this.name) + .append(", rain=").append(this.rain).append(", snow=").append(this.snow) + .append(", sys=").append(this.sys).append(", weather=").append(this.weather) + .append(", wind=").append(this.wind).append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/currentweather/Main.java b/src/de/example/exampletdd/model/currentweather/Main.java new file mode 100644 index 0000000..397f71b --- /dev/null +++ b/src/de/example/exampletdd/model/currentweather/Main.java @@ -0,0 +1,73 @@ +package de.example.exampletdd.model.currentweather; + +import java.io.Serializable; + +public class Main implements Serializable { + private static final long serialVersionUID = -6000879164436289447L; + private Number grnd_level; + private Number humidity; + private Number pressure; + private Number sea_level; + private Number temp; + private Number temp_max; + private Number temp_min; + + public Number getGrnd_level() { + return this.grnd_level; + } + + public void setGrnd_level(final Number grnd_level) { + this.grnd_level = grnd_level; + } + + public Number getHumidity(){ + return this.humidity; + } + public void setHumidity(final Number humidity){ + this.humidity = humidity; + } + public Number getPressure(){ + return this.pressure; + } + public void setPressure(final Number pressure){ + this.pressure = pressure; + } + + public Number getSea_level() { + return this.sea_level; + } + + public void setSea_level(final Number sea_level) { + this.sea_level = sea_level; + } + + public Number getTemp(){ + return this.temp; + } + public void setTemp(final Number temp){ + this.temp = temp; + } + public Number getTemp_max(){ + return this.temp_max; + } + public void setTemp_max(final Number temp_max){ + this.temp_max = temp_max; + } + public Number getTemp_min(){ + return this.temp_min; + } + public void setTemp_min(final Number temp_min){ + this.temp_min = temp_min; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Main [grnd_level=").append(this.grnd_level).append(", humidity=") + .append(this.humidity).append(", pressure=").append(this.pressure) + .append(", sea_level=").append(this.sea_level).append(", temp=").append(this.temp) + .append(", temp_max=").append(this.temp_max).append(", temp_min=") + .append(this.temp_min).append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/currentweather/Rain.java b/src/de/example/exampletdd/model/currentweather/Rain.java new file mode 100644 index 0000000..0e151ef --- /dev/null +++ b/src/de/example/exampletdd/model/currentweather/Rain.java @@ -0,0 +1,23 @@ +package de.example.exampletdd.model.currentweather; + +import java.io.Serializable; + +public class Rain implements Serializable { + private static final long serialVersionUID = 1318464783605029435L; + private Number three; + + public Number get3h(){ + return this.three; + } + + public void set3h(final Number threeh) { + this.three = threeh; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Rain [three=").append(this.three).append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/currentweather/Snow.java b/src/de/example/exampletdd/model/currentweather/Snow.java new file mode 100644 index 0000000..5174763 --- /dev/null +++ b/src/de/example/exampletdd/model/currentweather/Snow.java @@ -0,0 +1,23 @@ +package de.example.exampletdd.model.currentweather; + +import java.io.Serializable; + +public class Snow implements Serializable { + private static final long serialVersionUID = 6769716772818311879L; + private Number three; + + public Number get3h() { + return this.three; + } + + public void set3h(final Number threeh) { + this.three = threeh; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Snow [three=").append(this.three).append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/currentweather/Sys.java b/src/de/example/exampletdd/model/currentweather/Sys.java new file mode 100644 index 0000000..3e20bef --- /dev/null +++ b/src/de/example/exampletdd/model/currentweather/Sys.java @@ -0,0 +1,46 @@ +package de.example.exampletdd.model.currentweather; + +import java.io.Serializable; + + +public class Sys implements Serializable { + private static final long serialVersionUID = 5333083785731053139L; + private String country; + private Number message; + private Number sunrise; + private Number sunset; + + public String getCountry(){ + return this.country; + } + public void setCountry(final String country){ + this.country = country; + } + public Number getMessage(){ + return this.message; + } + public void setMessage(final Number message){ + this.message = message; + } + public Number getSunrise(){ + return this.sunrise; + } + public void setSunrise(final Number sunrise){ + this.sunrise = sunrise; + } + public Number getSunset(){ + return this.sunset; + } + public void setSunset(final Number sunset){ + this.sunset = sunset; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Sys [country=").append(this.country).append(", message=") + .append(this.message).append(", sunrise=").append(this.sunrise).append(", sunset=") + .append(this.sunset).append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/currentweather/Weather.java b/src/de/example/exampletdd/model/currentweather/Weather.java new file mode 100644 index 0000000..fc44d20 --- /dev/null +++ b/src/de/example/exampletdd/model/currentweather/Weather.java @@ -0,0 +1,45 @@ +package de.example.exampletdd.model.currentweather; + +import java.io.Serializable; + +public class Weather implements Serializable { + private static final long serialVersionUID = -34336548786316655L; + private String description; + private String icon; + private Number id; + private String main; + + public String getDescription(){ + return this.description; + } + public void setDescription(final String description){ + this.description = description; + } + public String getIcon(){ + return this.icon; + } + public void setIcon(final String icon){ + this.icon = icon; + } + public Number getId(){ + return this.id; + } + public void setId(final Number id){ + this.id = id; + } + public String getMain(){ + return this.main; + } + public void setMain(final String main){ + this.main = main; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Weather [description=").append(this.description).append(", icon=") + .append(this.icon).append(", id=").append(this.id).append(", main=") + .append(this.main).append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/currentweather/Wind.java b/src/de/example/exampletdd/model/currentweather/Wind.java new file mode 100644 index 0000000..4edc55d --- /dev/null +++ b/src/de/example/exampletdd/model/currentweather/Wind.java @@ -0,0 +1,30 @@ +package de.example.exampletdd.model.currentweather; + +import java.io.Serializable; + +public class Wind implements Serializable { + private static final long serialVersionUID = 5495842422633674631L; + private Number deg; + private Number speed; + + public Number getDeg(){ + return this.deg; + } + public void setDeg(final Number deg){ + this.deg = deg; + } + public Number getSpeed(){ + return this.speed; + } + public void setSpeed(final Number speed){ + this.speed = speed; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Wind [deg=").append(this.deg).append(", speed=").append(this.speed) + .append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/forecastweather/City.java b/src/de/example/exampletdd/model/forecastweather/City.java new file mode 100644 index 0000000..904ff5d --- /dev/null +++ b/src/de/example/exampletdd/model/forecastweather/City.java @@ -0,0 +1,53 @@ +package de.example.exampletdd.model.forecastweather; + +import java.io.Serializable; + + +public class City implements Serializable { + private static final long serialVersionUID = 3079687975077030704L; + private Coord coord; + private String country; + private Number id; + private String name; + private Number population; + + public Coord getCoord(){ + return this.coord; + } + public void setCoord(final Coord coord){ + this.coord = coord; + } + public String getCountry(){ + return this.country; + } + public void setCountry(final String country){ + this.country = country; + } + public Number getId(){ + return this.id; + } + public void setId(final Number id){ + this.id = id; + } + public String getName(){ + return this.name; + } + public void setName(final String name){ + this.name = name; + } + public Number getPopulation(){ + return this.population; + } + public void setPopulation(final Number population){ + this.population = population; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("City [coord=").append(this.coord).append(", country=").append(this.country) + .append(", id=").append(this.id).append(", name=").append(this.name) + .append(", population=").append(this.population).append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/forecastweather/Coord.java b/src/de/example/exampletdd/model/forecastweather/Coord.java new file mode 100644 index 0000000..fcfee58 --- /dev/null +++ b/src/de/example/exampletdd/model/forecastweather/Coord.java @@ -0,0 +1,30 @@ +package de.example.exampletdd.model.forecastweather; + +import java.io.Serializable; + +public class Coord implements Serializable { + private static final long serialVersionUID = 8069257976701986700L; + private Number lat; + private Number lon; + + public Number getLat(){ + return this.lat; + } + public void setLat(final Number lat){ + this.lat = lat; + } + public Number getLon(){ + return this.lon; + } + public void setLon(final Number lon){ + this.lon = lon; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Coord [lat=").append(this.lat).append(", lon=").append(this.lon) + .append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/forecastweather/ForecastWeatherData.java b/src/de/example/exampletdd/model/forecastweather/ForecastWeatherData.java new file mode 100644 index 0000000..1b9cef7 --- /dev/null +++ b/src/de/example/exampletdd/model/forecastweather/ForecastWeatherData.java @@ -0,0 +1,62 @@ +package de.example.exampletdd.model.forecastweather; + +import java.io.Serializable; +import java.util.List; + +/** + * Auto generated by: http://jsongen.byingtondesign.com/ + * (with my own modifications) + * + */ +public class ForecastWeatherData implements Serializable { + private static final long serialVersionUID = 5095443678019686190L; + private City city; + private Number cnt; + private Number cod; + private List list; + private Number message; + + public City getCity(){ + return this.city; + } + public void setCity(final City city){ + this.city = city; + } + public Number getCnt(){ + return this.cnt; + } + public void setCnt(final Number cnt){ + this.cnt = cnt; + } + + public Number getCod() { + return this.cod; + } + + public void setCod(final Number cod) { + this.cod = cod; + } + + public List getList() { + return this.list; + } + + public void setList(final List list) { + this.list = list; + } + public Number getMessage(){ + return this.message; + } + public void setMessage(final Number message){ + this.message = message; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("ForecastWeatherData [city=").append(this.city).append(", cnt=") + .append(this.cnt).append(", cod=").append(this.cod).append(", list=") + .append(this.list).append(", message=").append(this.message).append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/forecastweather/List.java b/src/de/example/exampletdd/model/forecastweather/List.java new file mode 100644 index 0000000..2104579 --- /dev/null +++ b/src/de/example/exampletdd/model/forecastweather/List.java @@ -0,0 +1,93 @@ +package de.example.exampletdd.model.forecastweather; + +import java.io.Serializable; + + +public class List implements Serializable { + private static final long serialVersionUID = 838468273188666785L; + private Number clouds; + private Number deg; + private Number dt; + private Number humidity; + private Number pressure; + private Number rain; + private Number snow; + private Number speed; + private Temp temp; + private java.util.List weather; + + public Number getClouds(){ + return this.clouds; + } + public void setClouds(final Number clouds){ + this.clouds = clouds; + } + public Number getDeg(){ + return this.deg; + } + public void setDeg(final Number deg){ + this.deg = deg; + } + public Number getDt(){ + return this.dt; + } + public void setDt(final Number dt){ + this.dt = dt; + } + public Number getHumidity(){ + return this.humidity; + } + public void setHumidity(final Number humidity){ + this.humidity = humidity; + } + public Number getPressure(){ + return this.pressure; + } + public void setPressure(final Number pressure){ + this.pressure = pressure; + } + public Number getRain(){ + return this.rain; + } + public void setRain(final Number rain){ + this.rain = rain; + } + public Number getSnow() { + return this.snow; + } + public void setSnow(final Number snow) { + this.snow = snow; + } + public Number getSpeed(){ + return this.speed; + } + public void setSpeed(final Number speed){ + this.speed = speed; + } + public Temp getTemp(){ + return this.temp; + } + public void setTemp(final Temp temp){ + this.temp = temp; + } + + public java.util.List getWeather() { + return this.weather; + } + + public void setWeather(final java.util.List weather) { + this.weather = weather; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("List [clouds=").append(this.clouds).append(", deg=").append(this.deg) + .append(", dt=").append(this.dt).append(", humidity=").append(this.humidity) + .append(", pressure=").append(this.pressure).append(", rain=").append(this.rain) + .append(", snow=").append(this.snow).append(", speed=").append(this.speed) + .append(", temp=").append(this.temp).append(", weather=").append(this.weather) + .append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/forecastweather/Temp.java b/src/de/example/exampletdd/model/forecastweather/Temp.java new file mode 100644 index 0000000..e4b1a7a --- /dev/null +++ b/src/de/example/exampletdd/model/forecastweather/Temp.java @@ -0,0 +1,60 @@ +package de.example.exampletdd.model.forecastweather; + +import java.io.Serializable; + +public class Temp implements Serializable { + private static final long serialVersionUID = -7614799035018271127L; + private Number day; + private Number eve; + private Number max; + private Number min; + private Number morn; + private Number night; + + public Number getDay(){ + return this.day; + } + public void setDay(final Number day){ + this.day = day; + } + public Number getEve(){ + return this.eve; + } + public void setEve(final Number eve){ + this.eve = eve; + } + public Number getMax(){ + return this.max; + } + public void setMax(final Number max){ + this.max = max; + } + public Number getMin(){ + return this.min; + } + public void setMin(final Number min){ + this.min = min; + } + public Number getMorn(){ + return this.morn; + } + public void setMorn(final Number morn){ + this.morn = morn; + } + public Number getNight(){ + return this.night; + } + public void setNight(final Number night){ + this.night = night; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Temp [day=").append(this.day).append(", eve=").append(this.eve) + .append(", max=").append(this.max).append(", min=").append(this.min) + .append(", morn=").append(this.morn).append(", night=").append(this.night) + .append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/model/forecastweather/Weather.java b/src/de/example/exampletdd/model/forecastweather/Weather.java new file mode 100644 index 0000000..f0de236 --- /dev/null +++ b/src/de/example/exampletdd/model/forecastweather/Weather.java @@ -0,0 +1,45 @@ +package de.example.exampletdd.model.forecastweather; + +import java.io.Serializable; + +public class Weather implements Serializable { + private static final long serialVersionUID = -5066357704517363241L; + private String description; + private String icon; + private Number id; + private String main; + + public String getDescription(){ + return this.description; + } + public void setDescription(final String description){ + this.description = description; + } + public String getIcon(){ + return this.icon; + } + public void setIcon(final String icon){ + this.icon = icon; + } + public Number getId(){ + return this.id; + } + public void setId(final Number id){ + this.id = id; + } + public String getMain(){ + return this.main; + } + public void setMain(final String main){ + this.main = main; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Weather [description=").append(this.description).append(", icon=") + .append(this.icon).append(", id=").append(this.id).append(", main=") + .append(this.main).append("]"); + return builder.toString(); + } +} diff --git a/src/de/example/exampletdd/parser/IJPOSWeatherParser.java b/src/de/example/exampletdd/parser/IJPOSWeatherParser.java index 184a6c7..db6e2df 100644 --- a/src/de/example/exampletdd/parser/IJPOSWeatherParser.java +++ b/src/de/example/exampletdd/parser/IJPOSWeatherParser.java @@ -1,11 +1,17 @@ package de.example.exampletdd.parser; -import org.json.JSONException; +import java.io.IOException; -import de.example.exampletdd.model.WeatherData; +import com.fasterxml.jackson.core.JsonParseException; + +import de.example.exampletdd.model.currentweather.CurrentWeatherData; +import de.example.exampletdd.model.forecastweather.ForecastWeatherData; public interface IJPOSWeatherParser { - WeatherData retrieveWeatherFromJPOS(final String jsonData) throws JSONException; + public CurrentWeatherData retrieveCurrentWeatherDataFromJPOS(final String jsonData) + throws JsonParseException, IOException; + public ForecastWeatherData retrieveForecastWeatherDataFromJPOS(final String jsonData) + throws JsonParseException, IOException; } diff --git a/src/de/example/exampletdd/parser/JPOSWeatherParser.java b/src/de/example/exampletdd/parser/JPOSWeatherParser.java index 21c0a1c..56cc9e2 100644 --- a/src/de/example/exampletdd/parser/JPOSWeatherParser.java +++ b/src/de/example/exampletdd/parser/JPOSWeatherParser.java @@ -1,78 +1,405 @@ package de.example.exampletdd.parser; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; +import java.io.IOException; +import java.util.ArrayList; -import de.example.exampletdd.model.WeatherData; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; + +import de.example.exampletdd.model.currentweather.Clouds; +import de.example.exampletdd.model.currentweather.Coord; +import de.example.exampletdd.model.currentweather.CurrentWeatherData; +import de.example.exampletdd.model.currentweather.Main; +import de.example.exampletdd.model.currentweather.Rain; +import de.example.exampletdd.model.currentweather.Sys; +import de.example.exampletdd.model.currentweather.Wind; +import de.example.exampletdd.model.forecastweather.City; +import de.example.exampletdd.model.forecastweather.ForecastWeatherData; +import de.example.exampletdd.model.forecastweather.Temp; public class JPOSWeatherParser implements IJPOSWeatherParser { @Override - public WeatherData retrieveWeatherFromJPOS(final String jsonData) throws JSONException { - final JSONObject jsonWeatherData = new JSONObject(jsonData); - - // TODO: return always objects. Using null values the app will be able - // to find out if there is or not data. In case of null value will - // not show anything on GUI (empty textbox for example) - - JSONObject jsonObject = jsonWeatherData.getJSONObject("coord"); - final double longitude = jsonObject.getDouble("lon"); - final double latitude = jsonObject.getDouble("lat"); - final WeatherData.Coord coord = new WeatherData.Coord(longitude, - latitude); - - jsonObject = jsonWeatherData.getJSONObject("sys"); - final long sunRiseTime = jsonObject.getLong("sunrise"); - final long sunSetTime = jsonObject.getLong("sunset"); - final double message = jsonObject.getDouble("message"); - final String country = jsonObject.getString("country"); - final WeatherData.System system = new WeatherData.System(country, - sunRiseTime, sunSetTime, message); - - // TODO: array of WeatherData.Weather :( - final JSONArray jsonArray = jsonWeatherData.getJSONArray("weather"); - jsonObject = jsonArray.getJSONObject(0); - - final int id = jsonObject.getInt("id"); - final String mainWeather = jsonObject.getString("main"); - final String description = jsonObject.getString("description"); - final String icon = jsonObject.getString("icon"); - final WeatherData.Weather weather = new WeatherData.Weather(id, - mainWeather, description, icon); - - jsonObject = jsonWeatherData.getJSONObject("main"); - final double temp = jsonObject.getDouble("temp"); - final double minTemp = jsonObject.optDouble("temp_min", 0); - - final double maxTemp = jsonObject.optDouble("temp_max", 0); - final double humidity = jsonObject.getDouble("humidity"); - final double pressure = jsonObject.getDouble("pressure"); - final WeatherData.Main main = new WeatherData.Main(temp, minTemp, - maxTemp, humidity, pressure); - - jsonObject = jsonWeatherData.getJSONObject("wind"); - final double speed = jsonObject.getDouble("speed"); - final double deg = jsonObject.getDouble("deg"); - final double gust = jsonObject.optDouble("gust", 0); - final double var_beg = jsonObject.optDouble("var_beg", 0); - final double var_end = jsonObject.optDouble("var_end", 0); - final WeatherData.Wind wind = new WeatherData.Wind(speed, deg, gust, - var_beg, var_end); - - jsonObject = jsonWeatherData.getJSONObject("clouds"); - final double cloudiness = jsonObject.getDouble("all"); - final WeatherData.Clouds clouds = new WeatherData.Clouds(cloudiness); - - final double time = jsonObject.optDouble("time", 0); - final WeatherData.DataReceivingTime dataReceivingTime = - new WeatherData.DataReceivingTime(time); - - - return new WeatherData.Builder().setCoord(coord).setSystem(system) - .setWeather(weather).setMain(main).setWind(wind) - .setClouds(clouds).setDataReceivingTime(dataReceivingTime) - .build(); + public CurrentWeatherData retrieveCurrentWeatherDataFromJPOS(final String jsonData) + throws JsonParseException, IOException { + final JsonFactory f = new JsonFactory(); + + final CurrentWeatherData currentWeatherData = new CurrentWeatherData(); + currentWeatherData.setClouds(new Clouds()); + currentWeatherData.setCoord(new Coord()); + currentWeatherData.setMain(new Main()); + currentWeatherData.setRain(new Rain()); + currentWeatherData.setSys(new Sys()); + currentWeatherData + .setWeather(new ArrayList()); + currentWeatherData.setWind(new Wind()); + final JsonParser jParser = f.createParser(jsonData); + + this.getCurrentWeatherData(currentWeatherData, jParser); + + return currentWeatherData; + } + + @Override + public ForecastWeatherData retrieveForecastWeatherDataFromJPOS(final String jsonData) + throws JsonParseException, IOException { + final JsonFactory f = new JsonFactory(); + + final ForecastWeatherData forecastWeatherData = new ForecastWeatherData(); + forecastWeatherData + .setList(new ArrayList(15)); + final City city = new City(); + city.setCoord(new de.example.exampletdd.model.forecastweather.Coord()); + forecastWeatherData.setCity(city); + final JsonParser jParser = f.createParser(jsonData); + + this.getForecastWeatherData(forecastWeatherData, jParser); + + return forecastWeatherData; + } + + private void getCurrentWeatherData(final CurrentWeatherData currentWeatherData, + final JsonParser jParser) throws JsonParseException, IOException { + if (jParser.nextToken() == JsonToken.START_OBJECT) { + + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String fieldname = jParser.getCurrentName(); + final JsonToken nextToken = jParser.nextToken(); + if (nextToken == JsonToken.START_OBJECT) { + this.getCurrentWeatherDataObjects(currentWeatherData, jParser, fieldname); + } + if (nextToken == JsonToken.START_ARRAY) { + JsonToken tokenNext = jParser.nextToken(); + while (tokenNext != JsonToken.END_ARRAY) { + if (tokenNext == JsonToken.START_OBJECT) { + this.getCurrentWeatherDataObjects(currentWeatherData, jParser, fieldname); + } + tokenNext = jParser.nextToken(); + } + } + if ((nextToken == JsonToken.VALUE_NUMBER_INT) + || (nextToken == JsonToken.VALUE_STRING)) { + this.getCurrentWeatherDataObjects(currentWeatherData, jParser, fieldname); + } + } + } + } + + private void getCurrentWeatherDataObjects(final CurrentWeatherData currentWeatherData, + final JsonParser jParser, final String fieldname) throws JsonParseException, + IOException { + if (fieldname == "coord") { + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + jParser.nextToken(); // move to value + if ("lon".equals(namefield)) { + currentWeatherData.getCoord().setLon(jParser.getDoubleValue()); + } + if ("lat".equals(namefield)) { + currentWeatherData.getCoord().setLat(jParser.getDoubleValue()); + } + } + } + if (fieldname == "sys") { + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + jParser.nextToken(); // move to value + if ("message".equals(namefield)) { + currentWeatherData.getSys().setMessage(jParser.getDoubleValue()); + } + if ("country".equals(namefield)) { + currentWeatherData.getSys().setCountry(jParser.getValueAsString()); + } + if ("sunrise".equals(namefield)) { + currentWeatherData.getSys().setSunrise(jParser.getValueAsLong()); + } + if ("sunset".equals(namefield)) { + currentWeatherData.getSys().setSunset(jParser.getValueAsLong()); + } + } + } + if (fieldname == "weather") { + final de.example.exampletdd.model.currentweather.Weather weather = new de.example.exampletdd.model.currentweather.Weather(); + currentWeatherData.getWeather().add(weather); + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + jParser.nextToken(); // move to value + if ("id".equals(namefield)) { + weather.setId(jParser.getIntValue()); + } + if ("main".equals(namefield)) { + weather.setMain(jParser.getText()); + } + if ("description".equals(namefield)) { + weather.setDescription(jParser.getText()); + } + if ("icon".equals(namefield)) { + weather.setIcon(jParser.getText()); + } + + } + } + if (fieldname == "base") { + currentWeatherData.setBase(jParser.getText()); + } + if (fieldname == "main") { + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + jParser.nextToken(); // move to value + if ("temp".equals(namefield)) { + currentWeatherData.getMain().setTemp(jParser.getDoubleValue()); + } + if ("temp_min".equals(namefield)) { + currentWeatherData.getMain().setTemp_min(jParser.getDoubleValue()); + } + if ("temp_max".equals(namefield)) { + currentWeatherData.getMain().setTemp_max(jParser.getDoubleValue()); + } + if ("pressure".equals(namefield)) { + currentWeatherData.getMain().setPressure(jParser.getDoubleValue()); + } + if ("sea_level".equals(namefield)) { + currentWeatherData.getMain().setSea_level(jParser.getDoubleValue()); + } + if ("grnd_level".equals(namefield)) { + currentWeatherData.getMain().setGrnd_level(jParser.getDoubleValue()); + } + if ("humidity".equals(namefield)) { + currentWeatherData.getMain().setHumidity(jParser.getDoubleValue()); + } + } + } + if (fieldname == "wind") { + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + jParser.nextToken(); // move to value + if ("speed".equals(namefield)) { + currentWeatherData.getWind().setSpeed(jParser.getDoubleValue()); + } + if ("deg".equals(namefield)) { + currentWeatherData.getWind().setDeg(jParser.getDoubleValue()); + } + } + } + if (fieldname == "clouds") { + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + jParser.nextToken(); // move to value + if ("all".equals(namefield)) { + currentWeatherData.getClouds().setAll(jParser.getDoubleValue()); + } + } + } + if (fieldname == "dt") { + currentWeatherData.setDt(jParser.getLongValue()); + } + if (fieldname == "rain") { + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + jParser.nextToken(); // move to value + if ("3h".equals(namefield)) { + currentWeatherData.getRain().set3h(jParser.getDoubleValue()); + } + } + } + if (fieldname == "snow") { + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + jParser.nextToken(); // move to value + if ("3h".equals(namefield)) { + currentWeatherData.getSnow().set3h(jParser.getDoubleValue()); + } + } + } + if (fieldname == "id") { + currentWeatherData.setId(jParser.getLongValue()); + } + if (fieldname == "name") { + currentWeatherData.setName(jParser.getText()); + } + if (fieldname == "cod") { + currentWeatherData.setCod(jParser.getIntValue()); + } } + private void getForecastWeatherData(final ForecastWeatherData forecastWeatherData, + final JsonParser jParser) throws JsonParseException, IOException { + if (jParser.nextToken() == JsonToken.START_OBJECT) { + + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String fieldname = jParser.getCurrentName(); + final JsonToken nextToken = jParser.nextToken(); + if (nextToken == JsonToken.START_OBJECT) { + this.getForecastWeatherDataObjects(forecastWeatherData, jParser, fieldname); + } + if (nextToken == JsonToken.START_ARRAY) { + JsonToken tokenNext = jParser.nextToken(); + while (tokenNext != JsonToken.END_ARRAY) { + if (tokenNext == JsonToken.START_OBJECT) { + this.getForecastWeatherDataObjects(forecastWeatherData, jParser, fieldname); + } + tokenNext = jParser.nextToken(); + } + } + if ((nextToken == JsonToken.VALUE_NUMBER_INT) + || (nextToken == JsonToken.VALUE_STRING)) { + this.getForecastWeatherDataObjects(forecastWeatherData, jParser, fieldname); + } + } + } + } + + private void getForecastWeatherDataObjects(final ForecastWeatherData forecastWeatherData, + final JsonParser jParser, final String fieldname) throws JsonParseException, + IOException { + + if (fieldname == "cod") { + final String stringCod = jParser.getText(); + forecastWeatherData.setCod(Long.valueOf(stringCod)); + } + if (fieldname == "message") { + forecastWeatherData.setMessage(jParser.getDoubleValue()); + } + if (fieldname == "city") { + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + final JsonToken nextToken = jParser.nextToken(); // move to + // value + if ("id".equals(namefield)) { + forecastWeatherData.getCity().setId(jParser.getLongValue()); + } + if ("name".equals(namefield)) { + forecastWeatherData.getCity().setName(jParser.getText()); + } + if ("coord".equals(namefield)) { + if (nextToken == JsonToken.START_OBJECT) { + this.getForecastWeatherDataObjects(forecastWeatherData, jParser, namefield); + } + } + if ("country".equals(namefield)) { + forecastWeatherData.getCity().setCountry(jParser.getText()); + } + if ("population".equals(namefield)) { + forecastWeatherData.getCity().setPopulation(jParser.getLongValue()); + } + } + } + if (fieldname == "cnt") { + forecastWeatherData.setCnt(jParser.getIntValue()); + } + if (fieldname == "coord") { + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + jParser.nextToken(); // move to value + if ("lon".equals(namefield)) { + forecastWeatherData.getCity().getCoord().setLon(jParser.getDoubleValue()); + } + if ("lat".equals(namefield)) { + forecastWeatherData.getCity().getCoord().setLat(jParser.getDoubleValue()); + } + } + } + if (fieldname == "list") { + final de.example.exampletdd.model.forecastweather.List list = new de.example.exampletdd.model.forecastweather.List(); + list.setTemp(new Temp()); + list.setWeather(new ArrayList()); + forecastWeatherData.getList().add(list); + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + final JsonToken nextToken = jParser.nextToken(); // move to + // value + if ("dt".equals(namefield)) { + list.setDt(jParser.getLongValue()); + } + if ("temp".equals(namefield)) { + if (nextToken == JsonToken.START_OBJECT) { + this.getForecastWeatherDataObjects(forecastWeatherData, jParser, namefield); + } + } + if ("pressure".equals(namefield)) { + list.setPressure(jParser.getDoubleValue()); + } + if ("humidity".equals(namefield)) { + list.setHumidity(jParser.getDoubleValue()); + } + if ("weather".equals(namefield)) { + if (nextToken == JsonToken.START_ARRAY) { + JsonToken tokenNext = jParser.nextToken(); + while (tokenNext != JsonToken.END_ARRAY) { + if (tokenNext == JsonToken.START_OBJECT) { + this.getForecastWeatherDataObjects(forecastWeatherData, jParser, + namefield); + } + tokenNext = jParser.nextToken(); + } + } + } + if ("speed".equals(namefield)) { + list.setSpeed(jParser.getDoubleValue()); + } + if ("deg".equals(namefield)) { + list.setDeg(jParser.getDoubleValue()); + } + if ("clouds".equals(namefield)) { + list.setClouds(jParser.getDoubleValue()); + } + if ("rain".equals(namefield)) { + list.setRain(jParser.getDoubleValue()); + } + } + } + if (fieldname == "temp") { + final de.example.exampletdd.model.forecastweather.List list = forecastWeatherData + .getList().get( + (forecastWeatherData.getList().size() - 1)); + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + jParser.nextToken(); // move to value + if ("day".equals(namefield)) { + list.getTemp().setDay(jParser.getDoubleValue()); + } + if ("min".equals(namefield)) { + list.getTemp().setMin(jParser.getDoubleValue()); + } + if ("max".equals(namefield)) { + list.getTemp().setMax(jParser.getDoubleValue()); + } + if ("night".equals(namefield)) { + list.getTemp().setNight(jParser.getDoubleValue()); + } + if ("eve".equals(namefield)) { + list.getTemp().setEve(jParser.getDoubleValue()); + } + if ("morn".equals(namefield)) { + list.getTemp().setMorn(jParser.getDoubleValue()); + } + } + } + if (fieldname == "weather") { + final de.example.exampletdd.model.forecastweather.List list = forecastWeatherData + .getList().get( + (forecastWeatherData.getList().size() - 1)); + final de.example.exampletdd.model.forecastweather.Weather weather = new de.example.exampletdd.model.forecastweather.Weather(); + while (jParser.nextToken() != JsonToken.END_OBJECT) { + final String namefield = jParser.getCurrentName(); + jParser.nextToken(); // move to value + + if ("id".equals(namefield)) { + weather.setId(jParser.getIntValue()); + } + if ("main".equals(namefield)) { + weather.setMain(jParser.getText()); + } + if ("description".equals(namefield)) { + weather.setDescription(jParser.getText()); + } + if ("icon".equals(namefield)) { + weather.setIcon(jParser.getText()); + } + } + list.getWeather().add(weather); + } + } } diff --git a/src/de/example/exampletdd/service/WeatherService.java b/src/de/example/exampletdd/service/WeatherService.java deleted file mode 100644 index 2d9c363..0000000 --- a/src/de/example/exampletdd/service/WeatherService.java +++ /dev/null @@ -1,58 +0,0 @@ -package de.example.exampletdd.service; - -import java.text.MessageFormat; -import java.util.Locale; - -import org.json.JSONException; - -import de.example.exampletdd.model.WeatherData; -import de.example.exampletdd.parser.IJPOSWeatherParser; - -public class WeatherService { - private final IJPOSWeatherParser JPOSWeatherParser; - - public WeatherService(final IJPOSWeatherParser JPOSWeatherParser) { - this.JPOSWeatherParser = JPOSWeatherParser; - } - - public WeatherData retrieveDataFromJPOS(final String jsonData) throws JSONException { - return this.JPOSWeatherParser.retrieveWeatherFromJPOS(jsonData); - } - - public String createURIAPICoord(final double latitude, - final double longitude, final String urlAPI, - final String APIVersion, final String language) { - - final MessageFormat formatURIAPI = new MessageFormat(urlAPI, - Locale.ENGLISH); - final Object[] values = new Object[4]; - values[0] = APIVersion; - values[1] = latitude; - values[2] = longitude; - values[3] = language; - - return formatURIAPI.format(values); - } - - public String createURIAPICityCountry(final String cityCountry, - final String urlAPI, final String APIVersion, final String units) { - - final MessageFormat formatURIAPI = new MessageFormat(urlAPI, Locale.ENGLISH); - final Object[] values = new Object[3]; - values[0] = APIVersion; - values[1] = cityCountry; - values[2] = units; - - return formatURIAPI.format(values); - } - - public String createURIAPIicon(final String icon, final String urlAPI) { - - final MessageFormat formatURIAPI = new MessageFormat(urlAPI, Locale.ENGLISH); - final Object[] values = new Object[1]; - values[0] = icon; - - return formatURIAPI.format(values); - } - -} diff --git a/src/de/example/exampletdd/service/WeatherServiceParser.java b/src/de/example/exampletdd/service/WeatherServiceParser.java new file mode 100644 index 0000000..9b95e08 --- /dev/null +++ b/src/de/example/exampletdd/service/WeatherServiceParser.java @@ -0,0 +1,64 @@ +package de.example.exampletdd.service; + +import java.io.IOException; +import java.text.MessageFormat; +import java.util.Locale; + +import com.fasterxml.jackson.core.JsonParseException; + +import de.example.exampletdd.model.currentweather.CurrentWeatherData; +import de.example.exampletdd.model.forecastweather.ForecastWeatherData; +import de.example.exampletdd.parser.IJPOSWeatherParser; + +public class WeatherServiceParser { + private final IJPOSWeatherParser JPOSWeatherParser; + + public WeatherServiceParser(final IJPOSWeatherParser JPOSWeatherParser) { + this.JPOSWeatherParser = JPOSWeatherParser; + } + + public CurrentWeatherData retrieveCurrentWeatherDataFromJPOS(final String jsonData) + throws JsonParseException, IOException { + return this.JPOSWeatherParser.retrieveCurrentWeatherDataFromJPOS(jsonData); + } + + public ForecastWeatherData retrieveForecastWeatherDataFromJPOS(final String jsonData) + throws JsonParseException, IOException { + return this.JPOSWeatherParser.retrieveForecastWeatherDataFromJPOS(jsonData); + } + + public String createURIAPIForecastWeather(final String urlAPI, final String APIVersion, + final double latitude, final double longitude, final String resultsNumber) { + + final MessageFormat formatURIAPI = new MessageFormat(urlAPI, Locale.ENGLISH); + final Object[] values = new Object[4]; + values[0] = APIVersion; + values[1] = latitude; + values[2] = longitude; + values[3] = resultsNumber; + + return formatURIAPI.format(values); + } + + public String createURIAPITodayWeather(final String urlAPI, final String APIVersion, + final double latitude, final double longitude) { + + final MessageFormat formatURIAPI = new MessageFormat(urlAPI, Locale.ENGLISH); + final Object[] values = new Object[3]; + values[0] = APIVersion; + values[1] = latitude; + values[2] = longitude; + + return formatURIAPI.format(values); + } + + public String createURIAPIicon(final String icon, final String urlAPI) { + + final MessageFormat formatURIAPI = new MessageFormat(urlAPI, Locale.ENGLISH); + final Object[] values = new Object[1]; + values[0] = icon; + + return formatURIAPI.format(values); + } + +} diff --git a/src/de/example/exampletdd/service/WeatherServicePersistenceFile.java b/src/de/example/exampletdd/service/WeatherServicePersistenceFile.java index e23c5de..fded6e7 100644 --- a/src/de/example/exampletdd/service/WeatherServicePersistenceFile.java +++ b/src/de/example/exampletdd/service/WeatherServicePersistenceFile.java @@ -11,11 +11,13 @@ import java.io.StreamCorruptedException; import android.content.Context; import android.util.Log; import de.example.exampletdd.model.GeocodingData; -import de.example.exampletdd.model.WeatherData; +import de.example.exampletdd.model.currentweather.CurrentWeatherData; +import de.example.exampletdd.model.forecastweather.ForecastWeatherData; public class WeatherServicePersistenceFile { private static final String TAG = "WeatherServicePersistenceFile"; - private static final String WEATHER_DATA_FILE = "weatherdata.file"; + private static final String CURRENT_WEATHER_DATA_FILE = "current_weatherdata.file"; + private static final String FORECAST_WEATHER_DATA_FILE = "forecast_weatherdata.file"; private static final String WEATHER_GEOCODING_FILE = "weathergeocoding.file"; private final Context context; @@ -80,16 +82,16 @@ public class WeatherServicePersistenceFile { this.context.deleteFile(WEATHER_GEOCODING_FILE); } - public void storeWeatherData(final WeatherData weatherData) + public void storeCurrentWeatherData(final CurrentWeatherData currentWeatherData) throws FileNotFoundException, IOException { final OutputStream persistenceFile = this.context.openFileOutput( - WEATHER_DATA_FILE, Context.MODE_PRIVATE); + CURRENT_WEATHER_DATA_FILE, Context.MODE_PRIVATE); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(persistenceFile); - oos.writeObject(weatherData); + oos.writeObject(currentWeatherData); } finally { if (oos != null) { oos.close(); @@ -97,11 +99,11 @@ public class WeatherServicePersistenceFile { } } - public WeatherData getWeatherData() { - WeatherData weatherData = null; + public CurrentWeatherData getCurrentWeatherData() { + CurrentWeatherData currentWeatherData = null; try { - weatherData = getWeatherDataThrowable(); + currentWeatherData = this.getCurrentWeatherDataThrowable(); } catch (final StreamCorruptedException e) { Log.e(TAG, "getWeatherData exception: ", e); } catch (final FileNotFoundException e) { @@ -112,20 +114,20 @@ public class WeatherServicePersistenceFile { Log.e(TAG, "getWeatherData exception: ", e); } - return weatherData; + return currentWeatherData; } - private WeatherData getWeatherDataThrowable() + private CurrentWeatherData getCurrentWeatherDataThrowable() throws StreamCorruptedException, FileNotFoundException, IOException, ClassNotFoundException { final InputStream persistenceFile = this.context.openFileInput( - WEATHER_DATA_FILE); + CURRENT_WEATHER_DATA_FILE); ObjectInputStream ois = null; try { ois = new ObjectInputStream(persistenceFile); - return (WeatherData) ois.readObject(); + return (CurrentWeatherData) ois.readObject(); } finally { if (ois != null) { ois.close(); @@ -133,7 +135,62 @@ public class WeatherServicePersistenceFile { } } - public void removeWeatherData() { - this.context.deleteFile(WEATHER_DATA_FILE); + public void removeCurrentWeatherData() { + this.context.deleteFile(CURRENT_WEATHER_DATA_FILE); + } + + public void storeForecastWeatherData(final ForecastWeatherData forecastWeatherData) + throws FileNotFoundException, IOException { + final OutputStream persistenceFile = this.context.openFileOutput(FORECAST_WEATHER_DATA_FILE, + Context.MODE_PRIVATE); + + ObjectOutputStream oos = null; + try { + oos = new ObjectOutputStream(persistenceFile); + + oos.writeObject(forecastWeatherData); + } finally { + if (oos != null) { + oos.close(); + } + } + } + + public ForecastWeatherData getForecastWeatherData() { + ForecastWeatherData forecastWeatherData = null; + + try { + forecastWeatherData = this.getForecastWeatherDataThrowable(); + } catch (final StreamCorruptedException e) { + Log.e(TAG, "getWeatherData exception: ", e); + } catch (final FileNotFoundException e) { + Log.e(TAG, "getWeatherData exception: ", e); + } catch (final IOException e) { + Log.e(TAG, "getWeatherData exception: ", e); + } catch (final ClassNotFoundException e) { + Log.e(TAG, "getWeatherData exception: ", e); + } + + return forecastWeatherData; + } + + private ForecastWeatherData getForecastWeatherDataThrowable() throws StreamCorruptedException, + FileNotFoundException, IOException, ClassNotFoundException { + final InputStream persistenceFile = this.context.openFileInput(FORECAST_WEATHER_DATA_FILE); + + ObjectInputStream ois = null; + try { + ois = new ObjectInputStream(persistenceFile); + + return (ForecastWeatherData) ois.readObject(); + } finally { + if (ois != null) { + ois.close(); + } + } + } + + public void removeForecastWeatherData() { + this.context.deleteFile(FORECAST_WEATHER_DATA_FILE); } }