├── .gitignore ├── Readme.md ├── .travis.yml ├── lib ├── .gitignore ├── src │ ├── main │ │ └── java │ │ │ └── org │ │ │ └── bitpipeline │ │ │ └── lib │ │ │ └── owm │ │ │ ├── ForecastWeatherData.java │ │ │ ├── WeatherStatusResponse.java │ │ │ ├── StatusWeatherData.java │ │ │ ├── LocalizedWeatherData.java │ │ │ ├── AbstractOwmResponse.java │ │ │ ├── WeatherHistoryCityResponse.java │ │ │ ├── WeatherHistoryStationResponse.java │ │ │ ├── AbstractWeatherData.java │ │ │ ├── WeatherForecastResponse.java │ │ │ ├── OwmClient.java │ │ │ ├── SampledWeatherData.java │ │ │ └── WeatherData.java │ └── test │ │ └── java │ │ └── org │ │ └── bitpipeline │ │ └── lib │ │ └── owm │ │ ├── ForecastWeatherDataTest.java │ │ ├── CalcTimePartExtratTest.java │ │ ├── WeatherDataTest.java │ │ └── OwmClientTest.java └── pom.xml └── resources └── code_formatters └── eclipse.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | Migrated to [GitLab](https://gitlab.com/BitPipeline/Libraries/owmClient). 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - openjdk7 4 | - oraclejdk7 5 | before_script: "cd lib" 6 | -------------------------------------------------------------------------------- /lib/.gitignore: -------------------------------------------------------------------------------- 1 | # eclipse stuff 2 | .classpath 3 | .settings 4 | .project 5 | 6 | # intellij stuff 7 | .idea/ 8 | units.iml 9 | 10 | # build artifacts 11 | target/ 12 | 13 | -------------------------------------------------------------------------------- /lib/src/main/java/org/bitpipeline/lib/owm/ForecastWeatherData.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import org.json.JSONObject; 19 | 20 | /** 21 | * @author mtavares */ 22 | public class ForecastWeatherData extends LocalizedWeatherData { 23 | static private final String DATETIME_KEY_NAME = "dt"; 24 | 25 | private long calcDateTime = Long.MIN_VALUE; 26 | 27 | /** 28 | * @param json json container with the forecast data */ 29 | public ForecastWeatherData (JSONObject json) { 30 | super (json); 31 | this.calcDateTime = json.optLong (ForecastWeatherData.DATETIME_KEY_NAME, Long.MIN_VALUE); 32 | } 33 | 34 | public long getCalcDateTime () { 35 | return this.calcDateTime; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /lib/src/test/java/org/bitpipeline/lib/owm/ForecastWeatherDataTest.java: -------------------------------------------------------------------------------- 1 | package org.bitpipeline.lib.owm; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.json.JSONException; 6 | import org.json.JSONObject; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.mockito.Mock; 10 | import org.mockito.runners.MockitoJUnitRunner; 11 | 12 | import static org.mockito.Mockito.*; 13 | 14 | /** 15 | * Unit tests for {@link ForecastWeatherData} 16 | * 17 | * @author cs4r 18 | * 19 | */ 20 | @RunWith(MockitoJUnitRunner.class) 21 | public class ForecastWeatherDataTest { 22 | 23 | private static final String DATETIME_KEY_NAME = "dt"; 24 | private static final long DESIRED_DATETIME = 123456; 25 | 26 | @Mock 27 | private JSONObject jsonObject; 28 | 29 | @Test 30 | public void testGetCalcDateTimeWhenDateTimeIsPresentReturns123456() 31 | throws JSONException { 32 | when(jsonObject.optLong(DATETIME_KEY_NAME, Long.MIN_VALUE)).thenReturn( 33 | DESIRED_DATETIME); 34 | assertEquals(DESIRED_DATETIME, getDateTimeFromForecastWeatherData()); 35 | } 36 | 37 | @Test 38 | public void testGetCalcDateTimeWhenDateTimeIsNotPresentReturnsLongMinValue() { 39 | when(jsonObject.optLong(DATETIME_KEY_NAME, Long.MIN_VALUE)).thenReturn( 40 | Long.MIN_VALUE); 41 | assertEquals(Long.MIN_VALUE, getDateTimeFromForecastWeatherData()); 42 | } 43 | 44 | private long getDateTimeFromForecastWeatherData() { 45 | return new ForecastWeatherData(jsonObject).getCalcDateTime(); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /lib/src/main/java/org/bitpipeline/lib/owm/WeatherStatusResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Collections; 20 | import java.util.List; 21 | 22 | import org.json.JSONArray; 23 | import org.json.JSONObject; 24 | 25 | /** 26 | * 27 | * @author mtavares */ 28 | public class WeatherStatusResponse extends AbstractOwmResponse { 29 | private final List status; 30 | 31 | /** A parser for a weather status query response 32 | * @param json The JSON obejct built from the OWM response */ 33 | public WeatherStatusResponse (JSONObject json) { 34 | super (json); 35 | JSONArray jsonWeatherStatus = json.optJSONArray (AbstractOwmResponse.JSON_LIST); 36 | if (jsonWeatherStatus == null) { 37 | this.status = Collections.emptyList (); 38 | } else { 39 | this.status = new ArrayList (jsonWeatherStatus.length ()); 40 | for (int i = 0; i getWeatherStatus () { 53 | return this.status; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /lib/src/main/java/org/bitpipeline/lib/owm/StatusWeatherData.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import org.json.JSONObject; 19 | 20 | public class StatusWeatherData extends LocalizedWeatherData { 21 | private static final String JSON_ID = "id"; 22 | private static final String JSON_NAME = "name"; 23 | private static final String JSON_STATION = "station"; 24 | 25 | static public class Station { 26 | private static final String JSON_ZOOM = "zoom"; 27 | 28 | private final int zoom; 29 | 30 | public Station (JSONObject json) { 31 | this.zoom = json.optInt (Station.JSON_ZOOM, Integer.MIN_VALUE); 32 | } 33 | 34 | public boolean hasZoom () { 35 | return this.zoom != Integer.MIN_VALUE; 36 | } 37 | public int getZoom () { 38 | return this.zoom; 39 | } 40 | } 41 | private final long id; 42 | private final String name; 43 | private final Station station; 44 | 45 | public StatusWeatherData (JSONObject json) { 46 | super (json); 47 | this.id = json.optLong (StatusWeatherData.JSON_ID, Long.MIN_VALUE); 48 | this.name = json.optString (StatusWeatherData.JSON_NAME); 49 | JSONObject stationJson = json.optJSONObject (StatusWeatherData.JSON_STATION); 50 | this.station = stationJson != null ? new Station (stationJson) : null; 51 | } 52 | 53 | public boolean hasId () { 54 | return this.id != Long.MIN_VALUE; 55 | } 56 | public long getId () { 57 | return this.id; 58 | } 59 | 60 | public boolean hasName () { 61 | return this.name != null && this.name.length () > 0; 62 | } 63 | public String getName () { 64 | return this.name; 65 | } 66 | 67 | public boolean hasStation () { 68 | return this.station != null; 69 | } 70 | public Station getStation () { 71 | return this.station; 72 | } 73 | } -------------------------------------------------------------------------------- /lib/src/test/java/org/bitpipeline/lib/owm/CalcTimePartExtratTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import static org.junit.Assert.assertEquals; 19 | import static org.junit.Assert.assertNotNull; 20 | 21 | import org.junit.Test; 22 | 23 | /** 24 | * 25 | * @author mtavares */ 26 | public class CalcTimePartExtratTest { 27 | static final private String CALC_TIME = "find = 0.0131 fetch = 0.0056 total=0.0186"; 28 | 29 | @Test 30 | public void testGetValueStrFromCalcTimePart () { 31 | String findValue = AbstractOwmResponse.getValueStrFromCalcTimePart (CalcTimePartExtratTest.CALC_TIME, "find"); 32 | assertNotNull (findValue); 33 | assertEquals ("0.0131", findValue); 34 | 35 | String fetchValue = AbstractOwmResponse.getValueStrFromCalcTimePart (CalcTimePartExtratTest.CALC_TIME, "fetch"); 36 | assertNotNull (fetchValue); 37 | assertEquals ("0.0056", fetchValue); 38 | 39 | String totalValue = AbstractOwmResponse.getValueStrFromCalcTimePart (CalcTimePartExtratTest.CALC_TIME, "total"); 40 | assertNotNull (totalValue); 41 | assertEquals ("0.0186", totalValue); 42 | } 43 | 44 | @Test 45 | public void testGetValueFromCalcTimeStr () { 46 | double findValue = AbstractOwmResponse.getValueFromCalcTimeStr (CalcTimePartExtratTest.CALC_TIME, "find"); 47 | assertNotNull (findValue); 48 | assertEquals (0.0131d, findValue, 0.00001d); 49 | 50 | double fetchValue = AbstractOwmResponse.getValueFromCalcTimeStr (CalcTimePartExtratTest.CALC_TIME, "fetch"); 51 | assertNotNull (fetchValue); 52 | assertEquals (0.0056d, fetchValue, 0.00001d); 53 | 54 | double totalValue = AbstractOwmResponse.getValueFromCalcTimeStr (CalcTimePartExtratTest.CALC_TIME, "total"); 55 | assertNotNull (totalValue); 56 | assertEquals (0.0186d, totalValue, 0.00001d); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /lib/src/main/java/org/bitpipeline/lib/owm/LocalizedWeatherData.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import org.json.JSONObject; 19 | 20 | public class LocalizedWeatherData extends WeatherData { 21 | private static final String JSON_URL = "url"; 22 | private static final String JSON_COORD = "coord"; 23 | private static final String JSON_DISTANCE = "distance"; 24 | 25 | public static class GeoCoord { 26 | private static final String JSON_LAT = "lat"; 27 | private static final String JSON_LON = "lon"; 28 | 29 | private float latitude; 30 | private float longitude; 31 | 32 | GeoCoord (JSONObject json) { 33 | this.latitude = (float) json.optDouble (GeoCoord.JSON_LAT); 34 | this.longitude = (float) json.optDouble (GeoCoord.JSON_LON); 35 | } 36 | 37 | public boolean hasLatitude () { 38 | return this.latitude != Float.NaN; 39 | } 40 | public float getLatitude () { 41 | return latitude; 42 | } 43 | 44 | public boolean hasLongitude () { 45 | return this.longitude != Float.NaN; 46 | } 47 | public float getLongitude () { 48 | return longitude; 49 | } 50 | } 51 | 52 | private final String url; 53 | private final GeoCoord coord ; 54 | private final float distance; 55 | 56 | public LocalizedWeatherData (JSONObject json) { 57 | super (json); 58 | 59 | this.url = json.optString (LocalizedWeatherData.JSON_URL); 60 | this.distance = (float) json.optDouble (LocalizedWeatherData.JSON_DISTANCE, Double.NaN); 61 | 62 | JSONObject jsonCoord = json.optJSONObject (LocalizedWeatherData.JSON_COORD); 63 | this.coord = jsonCoord != null ? new GeoCoord (jsonCoord) : null; 64 | } 65 | 66 | public boolean hasUrl () { 67 | return this.url != null && this.url.length () > 0; 68 | } 69 | public String getUrl () { 70 | return this.url; 71 | } 72 | 73 | public boolean hasCoord () { 74 | return this.coord != null; 75 | } 76 | public GeoCoord getCoord () { 77 | return this.coord; 78 | } 79 | 80 | public boolean hasDistance () { 81 | return !Float.isNaN (this.distance); 82 | } 83 | public float getDistance () { 84 | return this.distance; 85 | } 86 | } -------------------------------------------------------------------------------- /lib/src/main/java/org/bitpipeline/lib/owm/AbstractOwmResponse.java: -------------------------------------------------------------------------------- 1 | package org.bitpipeline.lib.owm; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | import org.json.JSONObject; 7 | 8 | abstract class AbstractOwmResponse { 9 | static private final String JSON_COD = "cod"; 10 | static private final String JSON_MESSAGE = "message"; 11 | static protected final String JSON_CALCTIME = "calctime"; 12 | static private final String JSON_CALCTIME_TOTAL = "total"; 13 | static protected final String JSON_LIST = "list"; 14 | 15 | 16 | private final int code; 17 | private final String message; 18 | private final float calctime; 19 | 20 | public AbstractOwmResponse (JSONObject json) { 21 | this.code = json.optInt (AbstractOwmResponse.JSON_COD, Integer.MIN_VALUE); 22 | this.message = json.optString (AbstractOwmResponse.JSON_MESSAGE); 23 | String calcTimeStr = json.optString (AbstractOwmResponse.JSON_CALCTIME); 24 | float calcTimeTotal = Float.NaN; 25 | if (calcTimeStr.length () > 0) { 26 | try { 27 | calcTimeTotal = Float.valueOf (calcTimeStr); 28 | } catch (NumberFormatException nfe) { // So.. it's not a number.. let's see if we can still find it's value. 29 | String totalCalcTimeStr = AbstractOwmResponse.getValueStrFromCalcTimePart (calcTimeStr, AbstractOwmResponse.JSON_CALCTIME_TOTAL); 30 | if (totalCalcTimeStr != null) { 31 | try { 32 | calcTimeTotal = Float.valueOf (totalCalcTimeStr); 33 | } catch (NumberFormatException nfe2) { 34 | calcTimeTotal = Float.NaN; 35 | } 36 | } 37 | } 38 | } 39 | this.calctime = calcTimeTotal; 40 | } 41 | 42 | public boolean hasCode () { 43 | return this.code != Integer.MIN_VALUE; 44 | } 45 | public int getCode () { 46 | return this.code; 47 | } 48 | 49 | public boolean hasMessage () { 50 | return this.message != null && this.message.length () > 0; 51 | } 52 | public String getMessage () { 53 | return this.message; 54 | } 55 | 56 | public boolean hasCalcTime () { 57 | return !Double.isNaN (this.calctime); 58 | } 59 | public double getCalcTime () { 60 | return this.calctime; 61 | } 62 | 63 | static String getValueStrFromCalcTimePart (final String calcTimeStr, final String part) { 64 | Pattern keyValuePattern = Pattern.compile (part + "\\s*=\\s*([\\d\\.]*)"); 65 | Matcher matcher = keyValuePattern.matcher (calcTimeStr); 66 | if (matcher.find () && matcher.groupCount () == 1) { 67 | return matcher.group (1); 68 | } 69 | return null; 70 | } 71 | 72 | static float getValueFromCalcTimeStr (final String calcTimeStr, final String part) { 73 | if (calcTimeStr == null || calcTimeStr.length () == 0) 74 | return Float.NaN; 75 | float value = Float.NaN; 76 | String valueStr = AbstractOwmResponse.getValueStrFromCalcTimePart (calcTimeStr, part); 77 | if (valueStr != null) { 78 | try { 79 | value = Float.valueOf (valueStr); 80 | } catch (NumberFormatException nfe) { 81 | value = Float.NaN; 82 | } 83 | } 84 | return value; 85 | } 86 | 87 | 88 | } 89 | -------------------------------------------------------------------------------- /lib/src/main/java/org/bitpipeline/lib/owm/WeatherHistoryCityResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Collections; 20 | import java.util.List; 21 | 22 | import org.json.JSONArray; 23 | import org.json.JSONObject; 24 | 25 | /** 26 | * 27 | * @author mtavares */ 28 | public class WeatherHistoryCityResponse extends AbstractOwmResponse { 29 | static private final String JSON_CALCTIME_FETCH = "fetch"; 30 | static private final String JSON_CALCTIME_FIND = "find"; 31 | static private final String JSON_CITY_ID = "city_id"; 32 | 33 | private final double calctimeFind; 34 | private final double calctimeFetch; 35 | private final int cityId; 36 | private final List history; 37 | 38 | /** A weather history city response parser 39 | * @param json the JSON object built with the response for the city weather history */ 40 | public WeatherHistoryCityResponse (JSONObject json) { 41 | super (json); 42 | 43 | String calcTimeStr = json.optString (AbstractOwmResponse.JSON_CALCTIME); 44 | this.calctimeFind = AbstractOwmResponse.getValueFromCalcTimeStr (calcTimeStr, WeatherHistoryCityResponse.JSON_CALCTIME_FIND); 45 | this.calctimeFetch = AbstractOwmResponse.getValueFromCalcTimeStr (calcTimeStr, WeatherHistoryCityResponse.JSON_CALCTIME_FETCH); 46 | this.cityId = json.optInt (WeatherHistoryCityResponse.JSON_CITY_ID, Integer.MIN_VALUE); 47 | 48 | JSONArray jsonHistory = json.optJSONArray (AbstractOwmResponse.JSON_LIST); 49 | if (jsonHistory == null) { 50 | this.history = Collections.emptyList (); 51 | } else { 52 | this.history = new ArrayList (jsonHistory.length ()); 53 | for (int i = 0; i getHistory () { 88 | return this.history; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /lib/src/main/java/org/bitpipeline/lib/owm/WeatherHistoryStationResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Collections; 20 | import java.util.List; 21 | 22 | import org.json.JSONArray; 23 | import org.json.JSONObject; 24 | 25 | /** 26 | * 27 | * @author mtavares */ 28 | public class WeatherHistoryStationResponse extends AbstractOwmResponse { 29 | static private final String JSON_CALCTIME_TICK = "tick"; 30 | static private final String JSON_STATION_ID = "station_id"; 31 | static private final String JSON_TYPE = "type"; 32 | 33 | private final float calctimeTick; 34 | private final int stationId; 35 | private final OwmClient.HistoryType type; 36 | private final List history; 37 | 38 | /** 39 | * @param json a JSON object built from the response */ 40 | public WeatherHistoryStationResponse (JSONObject json) { 41 | super (json); 42 | 43 | this.stationId = json.optInt (WeatherHistoryStationResponse.JSON_STATION_ID, Integer.MIN_VALUE); 44 | 45 | OwmClient.HistoryType typeValue = null; 46 | String typeStr = json.optString (WeatherHistoryStationResponse.JSON_TYPE); 47 | if (typeStr != null && typeStr.length () > 0) { 48 | try { 49 | typeValue = OwmClient.HistoryType.valueOf (typeStr.trim ().toUpperCase ()); 50 | } catch (IllegalArgumentException e) { 51 | typeValue = OwmClient.HistoryType.UNKNOWN; 52 | } 53 | } 54 | this.type = typeValue; 55 | 56 | if (this.type == OwmClient.HistoryType.TICK) { 57 | String calcTimeStr = json.optString (AbstractOwmResponse.JSON_CALCTIME); 58 | this.calctimeTick = AbstractOwmResponse.getValueFromCalcTimeStr (calcTimeStr, WeatherHistoryStationResponse.JSON_CALCTIME_TICK); 59 | } else { 60 | this.calctimeTick = Float.NaN; 61 | } 62 | 63 | JSONArray jsonHistory = json.optJSONArray (AbstractOwmResponse.JSON_LIST); 64 | if (jsonHistory == null) { 65 | this.history = Collections.emptyList (); 66 | } else { 67 | this.history = new ArrayList (jsonHistory.length ()); 68 | switch (this.type) { 69 | case TICK: 70 | for (int i = 0; i getHistory () { 118 | return this.history; 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /lib/src/main/java/org/bitpipeline/lib/owm/AbstractWeatherData.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import org.json.JSONObject; 19 | 20 | /** 21 | * 22 | * @author mtavares */ 23 | abstract public class AbstractWeatherData { 24 | protected static final String JSON_DATE_TIME = "dt"; 25 | protected static final String JSON_MAIN = "main"; 26 | protected static final String JSON_WIND = "wind"; 27 | protected static final String JSON_RAIN = "rain"; 28 | protected static final String JSON_SNOW = "snow"; 29 | 30 | 31 | static abstract public class Main { 32 | protected static final String JSON_TEMP = "temp"; 33 | protected static final String JSON_TEMP_MIN = "temp_min"; 34 | protected static final String JSON_TEMP_MAX = "temp_max"; 35 | protected static final String JSON_HUMIDITY = "humidity"; 36 | protected static final String JSON_PRESSURE = "pressure"; 37 | 38 | abstract public float getTemp (); 39 | abstract public float getTempMin (); 40 | abstract public float getTempMax (); 41 | abstract public float getPressure (); 42 | abstract public float getHumidity (); 43 | } 44 | 45 | static abstract public class Wind { 46 | protected static final String JSON_SPEED = "speed"; 47 | protected static final String JSON_DEG = "deg"; 48 | protected static final String JSON_GUST = "gust"; 49 | protected static final String JSON_VAR_BEG = "var_beg"; 50 | protected static final String JSON_VAR_END = "var_end"; 51 | 52 | abstract public float getSpeed (); 53 | abstract public int getDeg (); 54 | abstract public float getGust (); 55 | abstract public int getVarBeg (); 56 | abstract public int getVarEnd (); 57 | } 58 | 59 | private final long dateTime; 60 | 61 | public AbstractWeatherData (JSONObject json) { 62 | this.dateTime = json.optLong (WeatherData.JSON_DATE_TIME, Long.MIN_VALUE); 63 | } 64 | 65 | public long getDateTime () { 66 | return this.dateTime; 67 | } 68 | 69 | /** Get the temperature of this weather report 70 | * @return Float.NaN if the report doesn't have temperature data; the value of the temperature in Kelvin otherwise. */ 71 | abstract public float getTemp (); 72 | 73 | /** Get the humidity of this weather report 74 | * @return Float.NaN if the report doesn't have humidity data; the value of the humidity in percentage to condensation point otherwise. */ 75 | abstract public float getHumidity (); 76 | 77 | /** Get the atmospheric pressure of this weather report 78 | * @return Float.NaN if the report doesn't have pressure data; the value of the pressure in hectopascal otherwise. */ 79 | abstract public float getPressure (); 80 | 81 | /** Get the average wind speed of this weather report 82 | * @return Float.NaN if the report doesn't have wind speed data; the value of the wind speed in metre per second otherwise. */ 83 | abstract public float getWindSpeed (); 84 | 85 | /** Get the wind gust speed of this weather report 86 | * @return Float.NaN if the report doesn't have wind gust speed data; the value of the wind gust speed in metre per second otherwise. */ 87 | abstract public float getWindGust (); 88 | 89 | /** Get the average wind direction of this weather report 90 | * @return Integer.MIN_VALUE if the report doesn't have wind direction data; the degree of the wind direction otherwise. */ 91 | abstract public int getWindDeg (); 92 | 93 | /** Get the rain amount of this weather report 94 | * @return Integer.MIN_VALUE if the report doesn't have rain data; the amount of rain in mm per hour otherwise. */ 95 | abstract public int getRain (); 96 | 97 | /** Get the snow amount of this weather report 98 | * @return Integer.MIN_VALUE if the report doesn't have snow data; the amount of snow in mm per hour otherwise. */ 99 | abstract public int getSnow (); 100 | 101 | /** Get the amount of precipitation in this weather report 102 | * @return Integer.MIN_VALUE if the report doesn't have precipitation data; the amount of precipitation in mm per hour otherwise. */ 103 | abstract public int getPrecipitation (); 104 | } 105 | -------------------------------------------------------------------------------- /lib/src/test/java/org/bitpipeline/lib/owm/WeatherDataTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import static org.junit.Assert.assertEquals; 19 | import static org.junit.Assert.assertFalse; 20 | import static org.junit.Assert.assertNotNull; 21 | import static org.junit.Assert.assertTrue; 22 | 23 | import java.util.List; 24 | 25 | 26 | import org.bitpipeline.lib.owm.WeatherData.Clouds.CloudDescription; 27 | import org.bitpipeline.lib.owm.WeatherData.WeatherCondition; 28 | import org.bitpipeline.lib.owm.LocalizedWeatherData.GeoCoord; 29 | import org.json.JSONException; 30 | import org.json.JSONObject; 31 | import org.junit.Test; 32 | 33 | /** 34 | * @author mtavares */ 35 | public class WeatherDataTest { 36 | @Test 37 | public void testWeatherDataParsing_Point () throws JSONException { 38 | JSONObject weatherDatajson = new JSONObject (TestData.CURRENT_WEATHER_POINT); 39 | StatusWeatherData weather = new StatusWeatherData (weatherDatajson); 40 | 41 | assertNotNull (weather); 42 | assertEquals (5106529, weather.getId ()); 43 | assertEquals ("Woodbridge", weather.getName ()); 44 | assertEquals (1359818400, weather.getDateTime ()); 45 | 46 | assertTrue (weather.hasCoord ()); 47 | GeoCoord coord = weather.getCoord (); 48 | assertNotNull (coord); 49 | assertEquals (-74.284592f, coord.getLongitude (), 0.000001f); 50 | assertEquals (40.557598, coord.getLatitude (), 0.000001f); 51 | 52 | WeatherData.Main mainWeather = weather.getMain (); 53 | assertNotNull (mainWeather); 54 | assertTrue (mainWeather.hasTemp ()); 55 | assertEquals (267.97f, mainWeather.getTemp (), 0.001f); 56 | assertTrue (mainWeather.hasTempMin ()); 57 | assertEquals (267.15f, mainWeather.getTempMin (), 0.001f); 58 | assertTrue (mainWeather.hasTempMax ()); 59 | assertEquals (269.15f, mainWeather.getTempMax (), 0.001f); 60 | assertTrue (mainWeather.hasPressure ()); 61 | assertEquals (1026f, mainWeather.getPressure (), 0.1f); 62 | assertTrue (mainWeather.hasHumidity ()); 63 | assertEquals (45f, mainWeather.getHumidity (), 0.1f); 64 | 65 | assertTrue (weather.hasWind ()); 66 | WeatherData.Wind wind = weather.getWind (); 67 | assertNotNull (wind); 68 | assertTrue (wind.hasSpeed ()); 69 | assertEquals (3.1f, wind.getSpeed (), 0.01f); 70 | assertTrue (wind.hasDeg ()); 71 | assertEquals (260, wind.getDeg ()); 72 | assertFalse (wind.hasGust ()); 73 | assertFalse (wind.hasVarBeg ()); 74 | assertFalse (wind.hasVarEnd ()); 75 | 76 | assertTrue (weather.hasClouds ()); 77 | WeatherData.Clouds clouds = weather.getClouds (); 78 | assertNotNull (clouds); 79 | assertEquals (40, clouds.getAll ()); 80 | assertFalse (clouds.hasMeasures ()); 81 | 82 | assertFalse (weather.hasRain ()); 83 | assertFalse (weather.hasSnow ()); 84 | 85 | assertTrue (weather.hasWeatherConditions ()); 86 | List weatherConditions = weather.getWeatherConditions (); 87 | assertNotNull (weatherConditions); 88 | assertEquals (1, weatherConditions.size ()); 89 | WeatherCondition condition = weatherConditions.get (0); 90 | assertNotNull (condition); 91 | assertEquals (802, condition.getCode ().getId ()); 92 | assertEquals (WeatherCondition.ConditionCode.SCATTERED_CLOUDS, condition.getCode ()); 93 | assertEquals ("Clouds", condition.getMain ()); 94 | assertEquals ("scattered clouds", condition.getDescription ()); 95 | assertEquals ("03d", condition.getIconName ()); 96 | } 97 | 98 | @Test 99 | public void testWeatherDataParsing_City () throws JSONException { 100 | JSONObject weatherDatajson = new JSONObject (TestData.CURRENT_WEATHER_CITY); 101 | StatusWeatherData weather = new StatusWeatherData (weatherDatajson); 102 | 103 | assertTrue (weather.hasClouds ()); 104 | WeatherData.Clouds clouds = weather.getClouds (); 105 | assertNotNull (clouds); 106 | assertFalse (clouds.hasAll ()); 107 | assertTrue (clouds.hasConditions ()); 108 | List conditions = clouds.getConditions (); 109 | assertNotNull (conditions); 110 | assertEquals (2, conditions.size ()); 111 | CloudDescription cloudDescription = conditions.get (0); 112 | assertNotNull (cloudDescription); 113 | assertTrue (cloudDescription.hasDistance ()); 114 | assertTrue (cloudDescription.hasSkyCondition ()); 115 | assertFalse (cloudDescription.hasCumulus ()); 116 | assertEquals (91, cloudDescription.getDistance ()); 117 | assertEquals (CloudDescription.SkyCondition.BKN, cloudDescription.getSkyCondition ()); 118 | 119 | cloudDescription = conditions.get (1); 120 | assertNotNull (cloudDescription); 121 | assertTrue (cloudDescription.hasDistance ()); 122 | assertTrue (cloudDescription.hasSkyCondition ()); 123 | assertTrue (cloudDescription.hasCumulus ()); 124 | assertEquals (305, cloudDescription.getDistance ()); 125 | assertEquals (CloudDescription.SkyCondition.OVC, cloudDescription.getSkyCondition ()); 126 | assertEquals (CloudDescription.Cumulus.CB, cloudDescription.getCumulus ()); 127 | } 128 | 129 | // TODO test with invalid data. 130 | } 131 | -------------------------------------------------------------------------------- /lib/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 21 | 4.0.0 22 | 23 | org.bitpipeline.lib 24 | owm-lib 25 | OpenWeatherMap library 26 | 28 | 2.1.3-SNAPSHOT 29 | jar 30 | 31 | 32 | 33 | J. Miguel P. Tavares 34 | migtavares@gmail.com 35 | migtavares 36 | http://www.bitpipeline.eu 37 | +1 38 | 39 | developer 40 | 41 | 42 | 43 | 44 | 45 | BitPipeline 46 | http://www.bitpipeline.eu 47 | 48 | 49 | 50 | 1.6 51 | UTF-8 52 | 53 | 54 | 55 | 56 | org.json 57 | json 58 | 20070829 59 | provided 60 | 61 | 62 | org.apache.httpcomponents 63 | httpclient 64 | 4.2.3 65 | provided 66 | 67 | 68 | 69 | junit 70 | junit 71 | 4.11 72 | test 73 | 74 | 75 | org.mockito 76 | mockito-all 77 | 1.9.5 78 | test 79 | 80 | 81 | 82 | 83 | 84 | ossrh 85 | https://oss.sonatype.org/content/repositories/snapshots 86 | 87 | 88 | ossrh 89 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 90 | 91 | 92 | 93 | 94 | 95 | 96 | org.apache.maven.plugins 97 | maven-compiler-plugin 98 | 3.1 99 | 100 | ${compileSource} 101 | ${compileSource} 102 | ${project.build.sourceEncoding} 103 | 104 | 105 | 106 | 107 | org.apache.maven.plugins 108 | maven-pmd-plugin 109 | 3.1 110 | 111 | false 112 | ${project.build.sourceEncoding} 113 | ${compileSource} 114 | true 115 | 5 116 | 150 117 | true 118 | 119 | 120 | 121 | verify 122 | 123 | pmd 124 | check 125 | cpd 126 | cpd-check 127 | 128 | 129 | 130 | 131 | 132 | 133 | org.codehaus.mojo 134 | cobertura-maven-plugin 135 | 2.5.2 136 | 137 | 138 | html 139 | 140 | 141 | 142 | 143 | cobertura-exec 144 | package 145 | 146 | cobertura 147 | 148 | 149 | 150 | 151 | 152 | 153 | org.apache.maven.plugins 154 | maven-javadoc-plugin 155 | 2.9.1 156 | 157 | false 158 | 159 | 160 | 161 | 162 | jar 163 | 164 | 165 | 166 | 167 | 168 | 169 | org.apache.maven.plugins 170 | maven-source-plugin 171 | 2.4 172 | 173 | false 174 | 175 | 176 | 177 | 178 | jar-no-fork 179 | 180 | 181 | 182 | 183 | 184 | 185 | org.apache.maven.plugins 186 | maven-gpg-plugin 187 | 1.5 188 | 189 | 190 | sign-artifacts 191 | verify 192 | 193 | sign 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | -------------------------------------------------------------------------------- /lib/src/main/java/org/bitpipeline/lib/owm/WeatherForecastResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Collections; 20 | import java.util.List; 21 | 22 | import org.json.JSONArray; 23 | import org.json.JSONObject; 24 | 25 | /** 26 | * 27 | * @author mtavares */ 28 | public class WeatherForecastResponse extends AbstractOwmResponse { 29 | static public class City { 30 | static private final String JSON_ID = "id"; 31 | static private final String JSON_COORD = "coord"; 32 | static private final String JSON_COUNTRY = "country"; 33 | static private final String JSON_NAME = "name"; 34 | static private final String JSON_DT_CALC = "dt_calc"; 35 | static private final String JSON_STATIONS_COUNT = "stations_count"; 36 | 37 | private final int id; 38 | private final LocalizedWeatherData.GeoCoord coord; 39 | private final String country; 40 | private final String name; 41 | private final long dtCalc; 42 | private final int stationsCount; 43 | 44 | public City (JSONObject json) { 45 | this.id = json.optInt (City.JSON_ID, Integer.MIN_VALUE); 46 | JSONObject jsonCoord = json.optJSONObject (City.JSON_COORD); 47 | if (jsonCoord != null) 48 | this.coord = new LocalizedWeatherData.GeoCoord (jsonCoord); 49 | else 50 | this.coord = null; 51 | this.country = json.optString (City.JSON_COUNTRY); 52 | this.name = json.optString (City.JSON_NAME); 53 | this.dtCalc = json.optLong (City.JSON_DT_CALC, Long.MIN_VALUE); 54 | this.stationsCount = json.optInt (City.JSON_STATIONS_COUNT, Integer.MIN_VALUE); 55 | } 56 | 57 | public boolean hasId () { 58 | return this.id != Integer.MIN_VALUE; 59 | } 60 | public int getId () { 61 | return this.id; 62 | } 63 | 64 | public boolean hasCoordinates () { 65 | return this.coord != null; 66 | } 67 | public LocalizedWeatherData.GeoCoord getCoordinates () { 68 | return this.coord; 69 | } 70 | 71 | public boolean hasCountryCode () { 72 | return this.country != null; 73 | } 74 | public String getCountryCode () { 75 | return this.country; 76 | } 77 | 78 | public boolean hasName () { 79 | return this.name != null; 80 | } 81 | public String getName () { 82 | return this.name; 83 | } 84 | 85 | public boolean hasDateTimeCalc () { 86 | return this.dtCalc != Long.MIN_VALUE; 87 | } 88 | public long getDateTimeCalc () { 89 | return this.dtCalc; 90 | } 91 | 92 | public boolean hasStationsCount () { 93 | return this.stationsCount != Integer.MIN_VALUE; 94 | } 95 | public int getStationsCount () { 96 | return this.stationsCount; 97 | } 98 | } 99 | 100 | public static class Sys { 101 | private static final String JSON_COUNTRY = "country"; 102 | private static final String JSON_POPULATION = "population"; 103 | 104 | private final String country; 105 | private final int population; 106 | 107 | public Sys (JSONObject json) { 108 | this.country = json.optString (Sys.JSON_COUNTRY); 109 | this.population = json.optInt (Sys.JSON_POPULATION, Integer.MIN_VALUE); 110 | } 111 | 112 | public boolean hasCountry () { 113 | return this.country != null && this.country.length () > 0; 114 | } 115 | public String getCountry () { 116 | return this.country; 117 | } 118 | 119 | public boolean hasPopulation () { 120 | return this.population != Integer.MIN_VALUE; 121 | } 122 | public int getPopulation () { 123 | return this.population; 124 | } 125 | } 126 | 127 | static private final String JSON_URL = "url"; 128 | static private final String JSON_CITY = "city"; 129 | static private final String JSON_UNITS = "units"; 130 | static private final String JSON_MODEL = "model"; 131 | private static final String JSON_SYS = "sys"; 132 | 133 | private final String url; 134 | private final City city; 135 | private final String units; 136 | private final String model; 137 | private final Sys sys; 138 | private final List forecasts; 139 | 140 | /** A weather forecast response parser 141 | * @param json the json object with the weather forecast response */ 142 | public WeatherForecastResponse (JSONObject json) { 143 | super (json); 144 | this.url = json.optString (WeatherForecastResponse.JSON_URL); 145 | JSONObject jsonCity = json.optJSONObject (WeatherForecastResponse.JSON_CITY); 146 | if (jsonCity != null) 147 | this.city = new City (jsonCity); 148 | else 149 | this.city = null; 150 | this.units = json.optString (WeatherForecastResponse.JSON_UNITS); 151 | this.model = json.optString (WeatherForecastResponse.JSON_MODEL); 152 | 153 | JSONObject jsonSys = json.optJSONObject (WeatherForecastResponse.JSON_SYS); 154 | this.sys = jsonSys != null ? new Sys (jsonSys) : null; 155 | 156 | JSONArray jsonForecasts = json.optJSONArray (AbstractOwmResponse.JSON_LIST); 157 | if (jsonForecasts != null) { 158 | this.forecasts = new ArrayList (jsonForecasts.length ()); 159 | for (int i = 0; i 0; 170 | } 171 | public String getUrl () { 172 | return this.url; 173 | } 174 | 175 | public boolean hasCity () { 176 | return this.city != null; 177 | } 178 | public City getCity () { 179 | return this.city; 180 | } 181 | 182 | public boolean hasUnits () { 183 | return this.units != null && this.units.length () > 0; 184 | } 185 | public String getUnits () { 186 | return this.units; 187 | } 188 | 189 | public boolean hasModel () { 190 | return this.model != null && this.model.length () > 0; 191 | } 192 | public String getModel () { 193 | return this.model; 194 | } 195 | 196 | public boolean hasSys () { 197 | return this.sys != null; 198 | } 199 | public Sys getSys () { 200 | return this.sys; 201 | } 202 | 203 | public boolean hasForecasts () { 204 | return this.forecasts != null && !this.forecasts.isEmpty (); 205 | } 206 | public List getForecasts () { 207 | return this.forecasts; 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /lib/src/test/java/org/bitpipeline/lib/owm/OwmClientTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import static org.junit.Assert.assertEquals; 19 | import static org.junit.Assert.assertFalse; 20 | import static org.junit.Assert.assertNotNull; 21 | import static org.junit.Assert.assertTrue; 22 | import static org.mockito.Matchers.any; 23 | import static org.mockito.Mockito.mock; 24 | import static org.mockito.Mockito.when; 25 | 26 | import java.io.IOException; 27 | import java.util.List; 28 | import java.util.UUID; 29 | 30 | import org.apache.http.Header; 31 | import org.apache.http.HttpResponse; 32 | import org.apache.http.HttpVersion; 33 | import org.apache.http.client.HttpClient; 34 | import org.apache.http.client.methods.HttpGet; 35 | import org.apache.http.entity.StringEntity; 36 | import org.apache.http.message.BasicHttpResponse; 37 | import org.bitpipeline.lib.owm.OwmClient.HistoryType; 38 | import org.bitpipeline.lib.owm.WeatherForecastResponse.City; 39 | import org.json.JSONException; 40 | import org.junit.Test; 41 | import org.mockito.invocation.InvocationOnMock; 42 | import org.mockito.stubbing.Answer; 43 | 44 | /** 45 | * 46 | * @author mtavares */ 47 | public class OwmClientTest { 48 | 49 | private HttpClient createHttpClientThatRespondsWith (final String responseBody) throws IOException { 50 | HttpClient mockHttpClient = mock (HttpClient.class); 51 | when (mockHttpClient.execute (any (HttpGet.class))).then (new Answer() { 52 | @Override 53 | public HttpResponse answer (InvocationOnMock invocation) throws Throwable { 54 | HttpResponse response = new BasicHttpResponse (HttpVersion.HTTP_1_1, 200, "Ok"); 55 | response.setEntity (new StringEntity (responseBody)); 56 | return response; 57 | } 58 | }); 59 | return mockHttpClient; 60 | } 61 | 62 | private static void assertWeatherData (StatusWeatherData weatherData) { 63 | assertNotNull (weatherData); 64 | assertNotNull (weatherData.getName ()); 65 | assertFalse (weatherData.getId () == Long.MIN_VALUE); 66 | assertFalse (weatherData.getDateTime () == Long.MIN_VALUE); 67 | assertTrue (weatherData.hasMain ()); 68 | } 69 | 70 | private static void assertWeatherDataList (List weatherDataList, int maxData) { 71 | assertNotNull (weatherDataList); 72 | assertTrue (weatherDataList.size () <= maxData); 73 | for (StatusWeatherData weatherData : weatherDataList) { 74 | OwmClientTest.assertWeatherData (weatherData); 75 | } 76 | } 77 | 78 | private static void assertForecastWeatherData (ForecastWeatherData forecast) { 79 | assertNotNull (forecast); 80 | assertFalse (forecast.getDateTime () == Long.MIN_VALUE); 81 | assertFalse (forecast.getCalcDateTime () == Long.MIN_VALUE); 82 | assertTrue (forecast.hasMain ()); 83 | } 84 | 85 | private static void assertForecastWeatherDataList (List forecasts, int maxData) { 86 | assertNotNull (forecasts); 87 | assertTrue (forecasts.size () <= maxData); 88 | for (ForecastWeatherData weatherData : forecasts) { 89 | OwmClientTest.assertForecastWeatherData (weatherData); 90 | } 91 | } 92 | 93 | @Test 94 | public void testAPPIDHeaderRequest () throws IOException, JSONException { 95 | final String appid = UUID.randomUUID ().toString (); 96 | HttpClient mockHttpClient = mock (HttpClient.class); 97 | when (mockHttpClient.execute (any (HttpGet.class))).then (new Answer() { 98 | @Override 99 | public HttpResponse answer (InvocationOnMock invocation) throws Throwable { 100 | HttpGet httpGet = (HttpGet) invocation.getArguments ()[0]; 101 | Header[] headers = httpGet.getHeaders ("x-api-key"); 102 | assertNotNull (headers); 103 | assertEquals (1, headers.length); 104 | assertEquals (appid, headers[0].getValue ()); 105 | 106 | HttpResponse response = new BasicHttpResponse (HttpVersion.HTTP_1_1, 200, "Ok"); 107 | response.setEntity (new StringEntity (TestData.CURRENT_WEATHER_AROUND_CITY_COORD)); 108 | return response; 109 | } 110 | }); 111 | 112 | OwmClient owm = new OwmClient (mockHttpClient); 113 | owm.setAPPID (appid); 114 | owm.currentWeatherAtCity (55f, 37f, 10); 115 | } 116 | 117 | @Test 118 | public void testCurrentWeatherAroundPoint () throws IOException, JSONException { 119 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AROUND_POINT); 120 | OwmClient owm = new OwmClient (mockHttpClient); 121 | WeatherStatusResponse currentWeather = owm.currentWeatherAroundPoint (55f, 37f, 10); 122 | assertTrue (currentWeather.hasWeatherStatus ()); 123 | OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), 10); 124 | } 125 | 126 | @Test 127 | public void testCurrentWeatherAroundCity () throws IOException, JSONException { 128 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AROUND_CITY_COORD); 129 | OwmClient owm = new OwmClient (mockHttpClient); 130 | WeatherStatusResponse currentWeather = owm.currentWeatherAtCity (55f, 37f, 10); 131 | assertTrue (currentWeather.hasWeatherStatus ()); 132 | OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), 10); 133 | } 134 | 135 | @Test 136 | public void testCurrentWeatherInBoundingBox () throws IOException, JSONException { 137 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_IN_BBOX); 138 | OwmClient owm = new OwmClient (mockHttpClient); 139 | WeatherStatusResponse currentWeather = owm.currentWeatherInBoundingBox (12f, 32f, 15f, 37f); 140 | assertTrue (currentWeather.hasWeatherStatus ()); 141 | OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), Integer.MAX_VALUE); 142 | } 143 | 144 | @Test 145 | public void testCurrentWeatherAtCityBoundingBox () throws IOException, JSONException { 146 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_IN_CITY_BBOX); 147 | OwmClient owm = new OwmClient (mockHttpClient); 148 | WeatherStatusResponse currentWeather = owm.currentWeatherAtCityBoundingBox (12f, 32f, 15f, 37f); 149 | assertTrue (currentWeather.hasWeatherStatus ()); 150 | OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), Integer.MAX_VALUE); 151 | } 152 | 153 | @Test 154 | public void testCurrentWeatherInCircle () throws IOException, JSONException { 155 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_IN_CIRCLE); 156 | OwmClient owm = new OwmClient (mockHttpClient); 157 | WeatherStatusResponse currentWeather = owm.currentWeatherInCircle (55.5f, 37.5f, 40f); 158 | assertTrue (currentWeather.hasWeatherStatus ()); 159 | OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), Integer.MAX_VALUE); 160 | } 161 | 162 | @Test 163 | public void testCurrentWeatherAtCityInCircle () throws IOException, JSONException { 164 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_IN_CIRCLE); 165 | OwmClient owm = new OwmClient (mockHttpClient); 166 | WeatherStatusResponse currentWeather = owm.currentWeatherAtCityCircle (55.5f, 37.5f, 40f); 167 | assertTrue (currentWeather.hasWeatherStatus ()); 168 | OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), Integer.MAX_VALUE); 169 | } 170 | 171 | @Test 172 | public void testCurrentWeatherAtCityId () throws IOException, JSONException { 173 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AT_CITY_ID_MOSKOW); 174 | OwmClient owm = new OwmClient (mockHttpClient); 175 | StatusWeatherData weatherData = owm.currentWeatherAtCity (524901); 176 | assertEquals ("Moscow", weatherData.getName ()); 177 | assertEquals (524901, weatherData.getId ()); 178 | OwmClientTest.assertWeatherData (weatherData); 179 | } 180 | 181 | @Test 182 | public void testCurrentWeatherAtStationId () throws IOException, JSONException { 183 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AT_STATION_ID_9040); 184 | OwmClient owm = new OwmClient (mockHttpClient); 185 | StatusWeatherData weatherData = owm.currentWeatherAtStation (9040); 186 | assertEquals ("CT1AKV-10", weatherData.getName ()); 187 | assertEquals (9040, weatherData.getId ()); 188 | assertEquals (1360924205, weatherData.getDateTime ()); 189 | 190 | assertTrue (weatherData.hasMain ()); 191 | assertEquals ( 281.48f, weatherData.getMain ().getTemp (), 0.001f); 192 | assertEquals ( 99f, weatherData.getMain ().getHumidity (), 0.001f); 193 | assertEquals (1016f, weatherData.getMain ().getPressure (), 0.001f); 194 | 195 | assertTrue (weatherData.hasWind ()); 196 | assertEquals (0f, weatherData.getWind ().getSpeed (), 0.001f); 197 | assertEquals (0f, weatherData.getWind ().getGust (), 0.001f); 198 | assertEquals (0, weatherData.getWind ().getDeg ()); 199 | 200 | assertTrue (weatherData.hasRain ()); 201 | assertEquals (2, weatherData.getRainObj ().measurements ().size ()); 202 | assertEquals (0f, weatherData.getRainObj ().getMeasure (1), 0.001f); 203 | assertEquals (0f, weatherData.getRainObj ().getMeasure (24), 0.001f); 204 | assertEquals (0, weatherData.getRainObj ().getToday ()); 205 | 206 | assertTrue (weatherData.hasCoord ()); 207 | assertTrue (weatherData.getCoord ().hasLongitude ()); 208 | assertTrue (weatherData.getCoord ().hasLatitude ()); 209 | assertEquals (-8.7363f, weatherData.getCoord ().getLongitude (), 0.00001f); 210 | assertEquals (39.1862f, weatherData.getCoord ().getLatitude (), 0.00001f); 211 | 212 | assertTrue (weatherData.hasStation ()); 213 | assertEquals (7, weatherData.getStation ().getZoom ()); 214 | } 215 | 216 | @Test 217 | public void testCurrentWeatherAtCityName () throws IOException, JSONException { 218 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AT_CITY_NAME_LONDON); 219 | OwmClient owm = new OwmClient (mockHttpClient); 220 | WeatherStatusResponse currentWeather = owm.currentWeatherAtCity ("london"); 221 | assertTrue (currentWeather.hasWeatherStatus ()); 222 | OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), Integer.MAX_VALUE); 223 | for (StatusWeatherData weather : currentWeather.getWeatherStatus ()) { 224 | assertTrue ("london".equalsIgnoreCase (weather.getName ())); 225 | } 226 | } 227 | 228 | @Test 229 | public void testCurrentWeatherAtCityNameWithCountryCode () throws IOException, JSONException { 230 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AT_CITY_NAME_LONDON_COUNTRY_CODE_UK); 231 | OwmClient owm = new OwmClient (mockHttpClient); 232 | WeatherStatusResponse currentWeather = owm.currentWeatherAtCity ("london", "UK"); 233 | assertTrue (currentWeather.hasWeatherStatus ()); 234 | OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), Integer.MAX_VALUE); 235 | for (StatusWeatherData weather : currentWeather.getWeatherStatus ()) { 236 | assertTrue ("london".equalsIgnoreCase (weather.getName ())); 237 | } 238 | } 239 | 240 | @Test 241 | public void testForecastAtCityId () throws IOException, JSONException { 242 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.FORECAST_WEATHER_AT_CITY_ID_LISBON); 243 | OwmClient owm = new OwmClient (mockHttpClient); 244 | WeatherForecastResponse forecastResponse = owm.forecastWeatherAtCity (524901); 245 | City lisbon = forecastResponse.getCity (); 246 | assertNotNull (lisbon); 247 | assertTrue ("PT".equalsIgnoreCase (lisbon.getCountryCode ())); 248 | assertTrue ("Lisbon".equalsIgnoreCase (lisbon.getName ())); 249 | OwmClientTest.assertForecastWeatherDataList (forecastResponse.getForecasts (), Integer.MAX_VALUE); 250 | } 251 | 252 | @Test 253 | public void testForecastAtCityName () throws IOException, JSONException { 254 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.FORECAST_WEATHER_AT_CITY_NAME_LISBON); 255 | OwmClient owm = new OwmClient (mockHttpClient); 256 | WeatherForecastResponse forecastResponse = owm.forecastWeatherAtCity ("Lisbon"); 257 | City lisbon = forecastResponse.getCity (); 258 | assertNotNull (lisbon); 259 | assertTrue ("PT".equalsIgnoreCase (lisbon.getCountryCode ())); 260 | assertTrue ("Lisbon".equalsIgnoreCase (lisbon.getName ())); 261 | OwmClientTest.assertForecastWeatherDataList (forecastResponse.getForecasts (), Integer.MAX_VALUE); 262 | } 263 | 264 | @Test 265 | public void testHourHistoryWeatherAtCity () throws IOException, JSONException { 266 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.HISTORY_WEATHER_AT_CITY_ID); 267 | OwmClient owm = new OwmClient (mockHttpClient); 268 | WeatherHistoryCityResponse history = owm.historyWeatherAtCity (2885679, HistoryType.HOUR); 269 | assertEquals (0.0186d, history.getCalcTime (), 0.0001d); 270 | assertEquals (0.0056d, history.getCalcTimeFetch (), 0.0001d); 271 | assertEquals (0.0131d, history.getCalcTimeFind (), 0.0001d); 272 | assertEquals (2885679, history.getCityId ()); 273 | assertTrue (history.hasHistory ()); 274 | } 275 | 276 | @Test 277 | public void testTickHistoryWeatherAtStation () throws IOException, JSONException { 278 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.HISTORY_WEATHER_AT_STATION_ID_BY_TICK); 279 | OwmClient owm = new OwmClient (mockHttpClient); 280 | WeatherHistoryStationResponse history = owm.historyWeatherAtStation (9040, HistoryType.TICK); 281 | assertEquals (1.5991d, history.getCalcTime (), 0.0001d); 282 | assertEquals (0.0456d, history.getCalcTimeTick (), 0.0001d); 283 | assertEquals (9040, history.getStationId ()); 284 | assertEquals (OwmClient.HistoryType.TICK, history.getType ()); 285 | assertTrue (history.hasHistory ()); 286 | } 287 | 288 | @Test 289 | public void testHourlyHistoryWeatherAtStation () throws IOException, JSONException { 290 | HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.HISTORY_WEATHER_AT_STATION_ID_BY_HOUR); 291 | OwmClient owm = new OwmClient (mockHttpClient); 292 | WeatherHistoryStationResponse historyResponse = owm.historyWeatherAtStation (9040, HistoryType.HOUR); 293 | assertNotNull (historyResponse); 294 | List history = historyResponse.getHistory (); 295 | assertNotNull (history); 296 | assertTrue (history.size () == 14); 297 | AbstractWeatherData weather = history.get (0); 298 | assertNotNull (weather); 299 | assertEquals (289.26f, weather.getTemp (), 0.001f); 300 | assertEquals (1019f, weather.getPressure (), 0.01f); 301 | assertEquals (99f, weather.getHumidity (), 0.01f); 302 | // wind 303 | assertEquals (0f, weather.getWindSpeed (), 0.01f); 304 | assertEquals (0f, weather.getWindGust (), 0.01f); 305 | assertEquals (Integer.MIN_VALUE, weather.getWindDeg ()); 306 | // rain, snow and precipitation 307 | assertEquals (0, weather.getRain ()); 308 | assertEquals (Integer.MIN_VALUE, weather.getSnow ()); 309 | assertEquals (0, weather.getPrecipitation ()); 310 | } 311 | } 312 | -------------------------------------------------------------------------------- /lib/src/main/java/org/bitpipeline/lib/owm/OwmClient.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import java.io.IOException; 19 | import java.io.InputStream; 20 | import java.io.InputStreamReader; 21 | import java.io.Reader; 22 | import java.io.StringWriter; 23 | import java.util.Locale; 24 | 25 | import org.apache.http.HttpEntity; 26 | import org.apache.http.HttpResponse; 27 | import org.apache.http.StatusLine; 28 | import org.apache.http.client.HttpClient; 29 | import org.apache.http.client.methods.HttpGet; 30 | import org.apache.http.impl.client.DefaultHttpClient; 31 | import org.json.JSONException; 32 | import org.json.JSONObject; 33 | 34 | /** Implements a synchronous HTTP client to the Open Weather Map service described 35 | * in http://openweathermap.org/wiki/API/JSON_API 36 | * @author mtavares */ 37 | public class OwmClient { 38 | static private final String APPID_HEADER = "x-api-key"; 39 | 40 | static public enum HistoryType { 41 | UNKNOWN, 42 | TICK, HOUR, DAY 43 | } 44 | 45 | private String baseOwmUrl = "http://api.openweathermap.org/data/2.1/"; 46 | private String owmAPPID = null; 47 | 48 | private HttpClient httpClient; 49 | 50 | public OwmClient () { 51 | this.httpClient = new DefaultHttpClient (); 52 | } 53 | 54 | public OwmClient (HttpClient httpClient) { 55 | if (httpClient == null) 56 | throw new IllegalArgumentException ("Can't construct a OwmClient with a null HttpClient"); 57 | this.httpClient = httpClient; 58 | } 59 | 60 | /** 61 | * @param appid The APP ID provided by OpenWeatherMap */ 62 | public void setAPPID (String appid) { 63 | this.owmAPPID = appid; 64 | } 65 | 66 | /** Find current weather around a geographic point 67 | * @param lat is the latitude of the geographic point of interest (North/South coordinate) 68 | * @param lon is the longitude of the geographic point of interest (East/West coordinate) 69 | * @param cnt is the requested number of weather stations to retrieve (the 70 | * actual answer might be less than the requested). 71 | * @return the WeaherStatusResponse received 72 | * @throws JSONException if the response from the OWM server can't be parsed 73 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 74 | public WeatherStatusResponse currentWeatherAroundPoint (float lat, float lon, int cnt) throws IOException, JSONException { //, boolean cluster, OwmClient.Lang lang) { 75 | String subUrl = String.format (Locale.ROOT, "find/station?lat=%f&lon=%f&cnt=%d&cluster=yes", 76 | Float.valueOf (lat), Float.valueOf (lon), Integer.valueOf (cnt)); 77 | JSONObject response = doQuery (subUrl); 78 | return new WeatherStatusResponse (response); 79 | } 80 | 81 | /** Find current weather around a city coordinates 82 | * @param lat is the latitude of the geographic point of interest (North/South coordinate) 83 | * @param lon is the longitude of the geographic point of interest (East/West coordinate) 84 | * @param cnt is the requested number of weather stations to retrieve (the 85 | * actual answer might be less than the requested). 86 | * @return the WeaherStatusResponse received 87 | * @throws JSONException if the response from the OWM server can't be parsed 88 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 89 | public WeatherStatusResponse currentWeatherAtCity (float lat, float lon, int cnt) throws IOException, JSONException { //, boolean cluster, OwmClient.Lang lang) { 90 | String subUrl = String.format (Locale.ROOT, "find/city?lat=%f&lon=%f&cnt=%d&cluster=yes", 91 | Float.valueOf (lat), Float.valueOf (lon), Integer.valueOf (cnt)); 92 | JSONObject response = doQuery (subUrl); 93 | return new WeatherStatusResponse (response); 94 | } 95 | 96 | /** Find current weather within a bounding box 97 | * @param northLat is the latitude of the geographic top left point of the bounding box 98 | * @param westLon is the longitude of the geographic top left point of the bounding box 99 | * @param southLat is the latitude of the geographic bottom right point of the bounding box 100 | * @param eastLon is the longitude of the geographic bottom right point of the bounding box 101 | * @return the WeaherStatusResponse received 102 | * @throws JSONException if the response from the OWM server can't be parsed 103 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 104 | public WeatherStatusResponse currentWeatherInBoundingBox (float northLat, float westLon, float southLat, float eastLon) throws IOException, JSONException { //, boolean cluster, OwmClient.Lang lang) { 105 | String subUrl = String.format (Locale.ROOT, "find/station?bbox=%f,%f,%f,%f&cluster=yes", 106 | Float.valueOf (northLat), Float.valueOf (westLon), 107 | Float.valueOf (southLat), Float.valueOf (eastLon)); 108 | JSONObject response = doQuery (subUrl); 109 | return new WeatherStatusResponse (response); 110 | } 111 | 112 | /** Find current city weather within a bounding box 113 | * @param northLat is the latitude of the geographic top left point of the bounding box 114 | * @param westLon is the longitude of the geographic top left point of the bounding box 115 | * @param southLat is the latitude of the geographic bottom right point of the bounding box 116 | * @param eastLon is the longitude of the geographic bottom right point of the bounding box 117 | * @return the WeaherStatusResponse received 118 | * @throws JSONException if the response from the OWM server can't be parsed 119 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 120 | public WeatherStatusResponse currentWeatherAtCityBoundingBox (float northLat, float westLon, float southLat, float eastLon) throws IOException, JSONException { //, boolean cluster, OwmClient.Lang lang) { 121 | String subUrl = String.format (Locale.ROOT, "find/city?bbox=%f,%f,%f,%f&cluster=yes", 122 | Float.valueOf (northLat), Float.valueOf (westLon), 123 | Float.valueOf (southLat), Float.valueOf (eastLon)); 124 | JSONObject response = doQuery (subUrl); 125 | return new WeatherStatusResponse (response); 126 | } 127 | 128 | /** Find current weather within a circle 129 | * @param lat is the latitude of the geographic center of the circle (North/South coordinate) 130 | * @param lon is the longitude of the geographic center of the circle (East/West coordinate) 131 | * @param radius is the radius of the circle (in kilometres) 132 | * @return the WeaherStatusResponse received 133 | * @throws JSONException if the response from the OWM server can't be parsed 134 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 135 | public WeatherStatusResponse currentWeatherInCircle (float lat, float lon, float radius) throws IOException, JSONException { //, boolean cluster, OwmClient.Lang lang) { 136 | String subUrl = String.format (Locale.ROOT, "find/station?lat=%f&lon=%f&radius=%f&cluster=yes", 137 | Float.valueOf (lat), Float.valueOf (lon), Float.valueOf (radius)); 138 | JSONObject response = doQuery (subUrl); 139 | return new WeatherStatusResponse (response); 140 | } 141 | 142 | /** Find current city weather within a circle 143 | * @param lat is the latitude of the geographic center of the circle (North/South coordinate) 144 | * @param lon is the longitude of the geographic center of the circle (East/West coordinate) 145 | * @param radius is the radius of the circle (in kilometres) 146 | * @return the WeaherStatusResponse received 147 | * @throws JSONException if the response from the OWM server can't be parsed 148 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 149 | public WeatherStatusResponse currentWeatherAtCityCircle (float lat, float lon, float radius) throws IOException, JSONException { 150 | String subUrl = String.format (Locale.ROOT, "find/city?lat=%f&lon=%f&radius=%f&cluster=yes", 151 | Float.valueOf (lat), Float.valueOf (lon), Float.valueOf (radius)); 152 | JSONObject response = doQuery (subUrl); 153 | return new WeatherStatusResponse (response); 154 | } 155 | 156 | /** Find current city weather 157 | * @param cityId is the ID of the city 158 | * @return the StatusWeatherData received 159 | * @throws JSONException if the response from the OWM server can't be parsed 160 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 161 | public StatusWeatherData currentWeatherAtCity (int cityId) throws IOException, JSONException { 162 | String subUrl = String.format (Locale.ROOT, "weather/city/%d?type=json", Integer.valueOf (cityId)); 163 | JSONObject response = doQuery (subUrl); 164 | return new StatusWeatherData (response); 165 | } 166 | 167 | /** Find current station weather report 168 | * @param stationId is the ID of the station 169 | * @return the StatusWeatherData received 170 | * @throws JSONException if the response from the OWM server can't be parsed 171 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 172 | public StatusWeatherData currentWeatherAtStation (int stationId) throws IOException, JSONException { 173 | String subUrl = String.format (Locale.ROOT, "weather/station/%d?type=json", Integer.valueOf (stationId)); 174 | JSONObject response = doQuery (subUrl); 175 | return new StatusWeatherData (response); 176 | } 177 | 178 | /** Find current city weather 179 | * @param cityName is the name of the city 180 | * @return the StatusWeatherData received 181 | * @throws JSONException if the response from the OWM server can't be parsed 182 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 183 | public WeatherStatusResponse currentWeatherAtCity (String cityName) throws IOException, JSONException { 184 | String subUrl = String.format (Locale.ROOT, "find/name?q=%s", cityName); 185 | JSONObject response = doQuery (subUrl); 186 | return new WeatherStatusResponse (response); 187 | } 188 | 189 | /** Find current city weather 190 | * @param cityName is the name of the city 191 | * @param countryCode is the two letter country code 192 | * @return the StatusWeatherData received 193 | * @throws JSONException if the response from the OWM server can't be parsed 194 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 195 | public WeatherStatusResponse currentWeatherAtCity (String cityName, String countryCode) throws IOException, JSONException { 196 | String subUrl = String.format (Locale.ROOT, "find/name?q=%s,%s", cityName, countryCode.toUpperCase ()); 197 | JSONObject response = doQuery (subUrl); 198 | return new WeatherStatusResponse (response); 199 | } 200 | 201 | /** Get the weather forecast for a city 202 | * @param cityId is the ID of the city 203 | * @return the WeatherForecasteResponse received 204 | * @throws JSONException if the response from the OWM server can't be parsed 205 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 206 | public WeatherForecastResponse forecastWeatherAtCity (int cityId) throws JSONException, IOException { 207 | String subUrl = String.format (Locale.ROOT, "forecast/city/%d?type=json&units=metric", cityId); 208 | JSONObject response = doQuery (subUrl); 209 | return new WeatherForecastResponse (response); 210 | } 211 | 212 | /** Get the weather forecast for a city 213 | * @param cityName is the Name of the city 214 | * @return the WeatherForecasteResponse received 215 | * @throws JSONException if the response from the OWM server can't be parsed 216 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 217 | public WeatherForecastResponse forecastWeatherAtCity (String cityName) throws JSONException, IOException { 218 | String subUrl = String.format (Locale.ROOT, "forecast/city?q=%s&type=json&units=metric", cityName); 219 | JSONObject response = doQuery (subUrl); 220 | return new WeatherForecastResponse (response); 221 | } 222 | 223 | /** Get the weather history of a city. 224 | * @param cityId is the OWM city ID 225 | * @param type is the history type (frequency) to use. 226 | * @return the WeatherHistoricCityResponse received 227 | * @throws JSONException if the response from the OWM server can't be parsed 228 | * @throws IOException if there's some network error or the OWM server replies with a error. */ 229 | public WeatherHistoryCityResponse historyWeatherAtCity (int cityId, HistoryType type) throws JSONException, IOException { 230 | if (type == HistoryType.UNKNOWN) 231 | throw new IllegalArgumentException("Can't do a historic request for unknown type of history."); 232 | String subUrl = String.format (Locale.ROOT, "history/city/%d?type=%s", cityId, type); 233 | JSONObject response = doQuery (subUrl); 234 | return new WeatherHistoryCityResponse (response); 235 | } 236 | 237 | /** Get the weather history of a city. 238 | * @param stationId is the OWM station ID 239 | * @param type is the history type (frequency) to use. 240 | * @return the WeatherHistoryStationResponse received 241 | * @throws JSONException if the response from the OWM server can't be parsed 242 | * @throws IOException if there's some network error or the OWM server replies with a error.*/ 243 | public WeatherHistoryStationResponse historyWeatherAtStation (int stationId, HistoryType type) throws JSONException, IOException { 244 | if (type == HistoryType.UNKNOWN) 245 | throw new IllegalArgumentException("Can't do a historic request for unknown type of history."); 246 | String subUrl = String.format (Locale.ROOT, "history/station/%d?type=%s", stationId, type); 247 | JSONObject response = doQuery (subUrl); 248 | return new WeatherHistoryStationResponse (response); 249 | } 250 | 251 | private JSONObject doQuery (String subUrl) throws JSONException, IOException { 252 | String responseBody = null; 253 | HttpGet httpget = new HttpGet (this.baseOwmUrl + subUrl); 254 | if (this.owmAPPID != null) { 255 | httpget.addHeader (OwmClient.APPID_HEADER, this.owmAPPID); 256 | } 257 | 258 | HttpResponse response = this.httpClient.execute (httpget); 259 | InputStream contentStream = null; 260 | try { 261 | StatusLine statusLine = response.getStatusLine (); 262 | if (statusLine == null) { 263 | throw new IOException ( 264 | String.format ("Unable to get a response from OWM server")); 265 | } 266 | int statusCode = statusLine.getStatusCode (); 267 | if (statusCode < 200 && statusCode >= 300) { 268 | throw new IOException ( 269 | String.format ("OWM server responded with status code %d: %s", statusCode, statusLine)); 270 | } 271 | /* Read the response content */ 272 | HttpEntity responseEntity = response.getEntity (); 273 | contentStream = responseEntity.getContent (); 274 | Reader isReader = new InputStreamReader (contentStream); 275 | int contentSize = (int) responseEntity.getContentLength (); 276 | if (contentSize < 0) 277 | contentSize = 8*1024; 278 | StringWriter strWriter = new StringWriter (contentSize); 279 | char[] buffer = new char[8*1024]; 280 | int n = 0; 281 | while ((n = isReader.read(buffer)) != -1) { 282 | strWriter.write(buffer, 0, n); 283 | } 284 | responseBody = strWriter.toString (); 285 | contentStream.close (); 286 | } catch (IOException e) { 287 | throw e; 288 | } catch (RuntimeException re) { 289 | httpget.abort (); 290 | throw re; 291 | } finally { 292 | if (contentStream != null) 293 | contentStream.close (); 294 | } 295 | return new JSONObject (responseBody); 296 | } 297 | } 298 | -------------------------------------------------------------------------------- /lib/src/main/java/org/bitpipeline/lib/owm/SampledWeatherData.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import java.util.Collections; 19 | import java.util.HashMap; 20 | import java.util.Locale; 21 | import java.util.Map; 22 | import java.util.Set; 23 | 24 | import org.json.JSONObject; 25 | 26 | public class SampledWeatherData extends AbstractWeatherData { 27 | private static final String JSON_PRECIPITATION = "precipitation"; 28 | private static final String JSON_PRECIPITATION_V = "v"; 29 | 30 | static abstract class SampledValue { 31 | protected static final String JSON_VALUE = "v"; 32 | protected static final String JSON_COUNT = "c"; 33 | protected static final String JSON_MIN = "mi"; 34 | protected static final String JSON_MAX = "ma"; 35 | 36 | private final int count; 37 | 38 | protected SampledValue (JSONObject json) { 39 | this.count = json.optInt (SampledFValue.JSON_COUNT, Integer.MIN_VALUE); 40 | } 41 | 42 | public boolean hasCount () { 43 | return this.count != Integer.MIN_VALUE; 44 | } 45 | public int getCount () { 46 | return this.count; 47 | } 48 | 49 | abstract public boolean hasValue (); 50 | 51 | static public boolean hasSampledValue (SampledValue sampled) { 52 | return sampled != null && sampled.hasValue (); 53 | } 54 | } 55 | 56 | static class SampledFValue extends SampledValue { 57 | private final float value; 58 | private final float min; 59 | private final float max; 60 | 61 | public SampledFValue (JSONObject json) { 62 | super (json); 63 | this.value = (float) json.optDouble (SampledFValue.JSON_VALUE, Float.NaN); 64 | this.min = (float) json.optDouble (SampledFValue.JSON_MIN, Float.NaN); 65 | this.max = (float) json.optDouble (SampledFValue.JSON_MAX, Float.NaN); 66 | } 67 | 68 | public boolean hasValue () { 69 | return !Float.isNaN (this.value); 70 | } 71 | public float getValue () { 72 | return this.value; 73 | } 74 | 75 | public boolean hasMin () { 76 | return !Float.isNaN (this.min); 77 | } 78 | public float getMin () { 79 | return this.min; 80 | } 81 | 82 | public boolean hasMax () { 83 | return !Float.isNaN (this.max); 84 | } 85 | public float getMax () { 86 | return this.max; 87 | } 88 | 89 | static public SampledFValue createSampledFValueIfExisting (final JSONObject json, final String key) { 90 | JSONObject jsonSampledValue = json.optJSONObject (key); 91 | if (jsonSampledValue == null) 92 | return null; 93 | return new SampledFValue (jsonSampledValue); 94 | } 95 | 96 | static public float getSampledValue (SampledFValue sampled) { 97 | if (sampled != null && sampled.hasValue ()) 98 | return sampled.getValue (); 99 | return Float.NaN; 100 | } 101 | } 102 | 103 | static class SampledIValue extends SampledValue { 104 | private final int value; 105 | private final int min; 106 | private final int max; 107 | 108 | public SampledIValue (JSONObject json) { 109 | super (json); 110 | this.value = json.optInt (SampledIValue.JSON_VALUE, Integer.MIN_VALUE); 111 | this.min = json.optInt (SampledIValue.JSON_MIN, Integer.MIN_VALUE); 112 | this.max = json.optInt (SampledIValue.JSON_MAX, Integer.MIN_VALUE); 113 | } 114 | 115 | public boolean hasValue () { 116 | return this.value != Integer.MIN_VALUE; 117 | } 118 | public int getValue () { 119 | return this.value; 120 | } 121 | 122 | public boolean hasMin () { 123 | return this.min != Integer.MIN_VALUE; 124 | } 125 | public int getMin () { 126 | return this.min; 127 | } 128 | 129 | public boolean hasMax () { 130 | return this.max != Integer.MIN_VALUE; 131 | } 132 | public int getMax () { 133 | return this.max; 134 | } 135 | 136 | static public SampledIValue createSampledIValueIfExisting (final JSONObject json, final String key) { 137 | JSONObject jsonSampledValue = json.optJSONObject (key); 138 | if (jsonSampledValue == null) 139 | return null; 140 | return new SampledIValue (jsonSampledValue); 141 | } 142 | 143 | static public int getSampledValue (SampledIValue sampled) { 144 | if (sampled != null && sampled.hasValue ()) 145 | return sampled.getValue (); 146 | return Integer.MIN_VALUE; 147 | } 148 | } 149 | 150 | public static class Main extends AbstractWeatherData.Main{ 151 | private final SampledFValue temp; 152 | private final SampledFValue tempMin; 153 | private final SampledFValue tempMax; 154 | private final SampledFValue pressure; 155 | private final SampledFValue humidity; 156 | 157 | public Main (JSONObject json) { 158 | this.temp = SampledFValue.createSampledFValueIfExisting (json, Main.JSON_TEMP); 159 | this.tempMin = SampledFValue.createSampledFValueIfExisting (json, Main.JSON_TEMP_MIN); 160 | this.tempMax = SampledFValue.createSampledFValueIfExisting (json, Main.JSON_TEMP_MAX); 161 | this.pressure = SampledFValue.createSampledFValueIfExisting (json, Main.JSON_PRESSURE); 162 | this.humidity = SampledFValue.createSampledFValueIfExisting (json, Main.JSON_HUMIDITY); 163 | } 164 | 165 | public boolean hasTemp () { 166 | return SampledValue.hasSampledValue (this.temp); 167 | } 168 | public float getTemp () { 169 | return SampledFValue.getSampledValue (this.temp); 170 | } 171 | public SampledFValue getSampledTemp () { 172 | return this.temp; 173 | } 174 | 175 | public boolean hasTempMin () { 176 | return SampledValue.hasSampledValue (this.tempMin); 177 | } 178 | public float getTempMin () { 179 | return SampledFValue.getSampledValue (this.tempMin); 180 | } 181 | public SampledFValue getSampledTempMin () { 182 | return this.tempMin; 183 | } 184 | 185 | public boolean hasTempMax () { 186 | return SampledValue.hasSampledValue (this.tempMax); 187 | } 188 | public float getTempMax () { 189 | return SampledFValue.getSampledValue (this.tempMax); 190 | } 191 | public SampledFValue getSampledTempMax () { 192 | return this.tempMax; 193 | } 194 | 195 | public boolean hasPressure () { 196 | return SampledValue.hasSampledValue (this.pressure); 197 | } 198 | public float getPressure () { 199 | return SampledFValue.getSampledValue (this.pressure); 200 | } 201 | public SampledFValue getSampledPressure () { 202 | return this.pressure; 203 | } 204 | 205 | public boolean hasHumidity () { 206 | return SampledValue.hasSampledValue (this.humidity); 207 | } 208 | public float getHumidity () { 209 | return SampledFValue.getSampledValue (this.humidity); 210 | } 211 | public SampledFValue getSampledHumidity () { 212 | return this.humidity; 213 | } 214 | } 215 | 216 | public static class Wind extends AbstractWeatherData.Wind { 217 | private final SampledFValue speed; 218 | private final SampledIValue deg; 219 | private final SampledFValue gust; 220 | private final SampledIValue varBeg; 221 | private final SampledIValue varEnd; 222 | 223 | public Wind (JSONObject json) { 224 | this.speed = SampledFValue.createSampledFValueIfExisting (json, Wind.JSON_SPEED); 225 | this.deg = SampledIValue.createSampledIValueIfExisting (json, Wind.JSON_DEG); 226 | this.gust = SampledFValue.createSampledFValueIfExisting (json, Wind.JSON_GUST); 227 | this.varBeg = SampledIValue.createSampledIValueIfExisting (json, Wind.JSON_VAR_BEG); 228 | this.varEnd = SampledIValue.createSampledIValueIfExisting (json, Wind.JSON_VAR_END); 229 | } 230 | 231 | public boolean hasSpeed () { 232 | return SampledValue.hasSampledValue (this.speed); 233 | } 234 | public float getSpeed () { 235 | return SampledFValue.getSampledValue (this.speed); 236 | } 237 | public SampledFValue getSampledSpeed () { 238 | return this.speed; 239 | } 240 | 241 | public boolean hasDeg () { 242 | return SampledValue.hasSampledValue (this.deg); 243 | } 244 | public int getDeg () { 245 | return SampledIValue.getSampledValue (this.deg); 246 | } 247 | public SampledIValue getSampledDeg () { 248 | return this.deg; 249 | } 250 | 251 | public boolean hasGust () { 252 | return SampledValue.hasSampledValue (this.gust); 253 | } 254 | public float getGust () { 255 | return SampledFValue.getSampledValue (this.gust); 256 | } 257 | public SampledFValue getSampledGust () { 258 | return this.gust; 259 | } 260 | 261 | public boolean hasVarBeg () { 262 | return SampledValue.hasSampledValue (this.varBeg); 263 | } 264 | public int getVarBeg () { 265 | return SampledIValue.getSampledValue (this.varBeg); 266 | } 267 | public SampledIValue getSampledVarBeg () { 268 | return this.varBeg; 269 | } 270 | 271 | public boolean hasVarEnd () { 272 | return SampledValue.hasSampledValue (this.varEnd); 273 | } 274 | public int getVarEnd () { 275 | return SampledIValue.getSampledValue (this.varEnd); 276 | } 277 | public SampledIValue getSampledVarEnd () { 278 | return this.varEnd; 279 | } 280 | } 281 | 282 | private static class SampledTimedDetails { 283 | private Map measurements = null; 284 | 285 | SampledTimedDetails (JSONObject json) { 286 | for (int i=1; i<=24; i++) { 287 | JSONObject value = json.optJSONObject (String.format (Locale.ROOT, "%dh", i)); 288 | if (value != null) { 289 | putMeasure (i, new SampledIValue (value)); 290 | } 291 | } 292 | } 293 | 294 | public boolean hasMeasures () { 295 | return this.measurements != null && this.measurements.size () > 0; 296 | } 297 | private void putMeasure (int lastHours, SampledIValue value) { 298 | if (this.measurements == null) 299 | this.measurements = new HashMap (); 300 | this.measurements.put (Integer.valueOf (lastHours), value); 301 | } 302 | 303 | public SampledIValue getMeasure (int lastHours) { 304 | return this.measurements.get (Integer.valueOf (lastHours)); 305 | } 306 | public SampledIValue getMeasure (Integer lastHours) { 307 | return this.measurements.get (lastHours); 308 | } 309 | 310 | public Set measurements () { 311 | if (this.measurements == null) 312 | return Collections.emptySet (); 313 | return this.measurements.keySet (); 314 | } 315 | } 316 | 317 | public static class Precipitation extends SampledTimedDetails { 318 | private static final String JSON_TODAY = "today"; 319 | private final int today; 320 | 321 | public Precipitation (JSONObject json) { 322 | super (json); 323 | this.today = json.optInt (Precipitation.JSON_TODAY, Integer.MIN_VALUE); 324 | } 325 | 326 | public boolean hasToday () { 327 | return this.today != Integer.MIN_VALUE; 328 | } 329 | public int getToday () { 330 | return this.today; 331 | } 332 | } 333 | 334 | private final SampledFValue temp; 335 | private final SampledFValue pressure; 336 | private final SampledFValue humidity; 337 | private final Main main; 338 | private final Wind wind; 339 | private final Precipitation rain; 340 | private final Precipitation snow; 341 | private final SampledIValue precipitation; 342 | 343 | public SampledWeatherData (JSONObject json) { 344 | super (json); 345 | 346 | this.temp = SampledFValue.createSampledFValueIfExisting (json, Main.JSON_TEMP); 347 | this.pressure = SampledFValue.createSampledFValueIfExisting (json, Main.JSON_PRESSURE); 348 | this.humidity = SampledFValue.createSampledFValueIfExisting (json, Main.JSON_HUMIDITY); 349 | 350 | JSONObject jsonMain = json.optJSONObject (AbstractWeatherData.JSON_MAIN); 351 | this.main = jsonMain != null ? new Main (jsonMain) : null; 352 | 353 | JSONObject jsonWind = json.optJSONObject (AbstractWeatherData.JSON_WIND); 354 | this.wind = jsonWind != null ? new Wind (jsonWind) : null; 355 | 356 | JSONObject jsonRain = json.optJSONObject (AbstractWeatherData.JSON_RAIN); 357 | this.rain = jsonRain != null ? new Precipitation (jsonRain) : null; 358 | 359 | JSONObject jsonSnow = json.optJSONObject (AbstractWeatherData.JSON_SNOW); 360 | this.snow = jsonSnow != null ? new Precipitation (jsonSnow) : null; 361 | 362 | JSONObject jsonPrecipitation = json.optJSONObject (SampledWeatherData.JSON_PRECIPITATION); 363 | if (jsonPrecipitation != null) { 364 | JSONObject jsonPrecipitationValue = jsonPrecipitation.optJSONObject (SampledWeatherData.JSON_PRECIPITATION_V); 365 | this.precipitation = jsonPrecipitationValue != null ? new SampledIValue (jsonPrecipitationValue) : null; 366 | } else { 367 | this.precipitation = null; 368 | } 369 | } 370 | 371 | public boolean hasTemp () { 372 | return this.temp != null && this.temp.hasValue () 373 | || hasMain () && this.main.hasTemp (); 374 | } 375 | public float getTemp () { 376 | if (this.temp != null && this.temp.hasValue ()) 377 | return this.temp.getValue (); 378 | if (hasMain () && this.main.hasTemp ()) 379 | return this.main.getTemp (); 380 | return Float.NaN; 381 | } 382 | 383 | public boolean hasHumidity () { 384 | return this.humidity != null && this.humidity.hasValue () 385 | || hasMain () && this.main.hasHumidity (); 386 | 387 | } 388 | public float getHumidity () { 389 | if (this.humidity != null && this.humidity.hasValue ()) 390 | return this.humidity.getValue (); 391 | if (hasMain () && this.main.hasHumidity ()) 392 | return this.main.getHumidity (); 393 | return Float.NaN; 394 | } 395 | 396 | public boolean hasPressure () { 397 | return this.pressure != null && this.pressure.hasValue () 398 | || hasMain () && this.main.hasPressure (); 399 | } 400 | public float getPressure () { 401 | if (this.pressure != null && this.pressure.hasValue ()) 402 | return this.pressure.getValue (); 403 | if (hasMain () && this.main.hasPressure ()) 404 | return this.main.getPressure (); 405 | return Float.NaN; 406 | } 407 | 408 | public boolean hasMain () { 409 | return this.main != null; 410 | } 411 | public Main getMain () { 412 | return this.main; 413 | } 414 | 415 | public boolean hasWind () { 416 | return this.wind != null; 417 | } 418 | public Wind getWind () { 419 | return this.wind; 420 | } 421 | 422 | public boolean hasRain () { 423 | return this.rain != null; 424 | } 425 | public Precipitation getRainObj () { 426 | return this.rain; 427 | } 428 | 429 | public boolean hasSnow () { 430 | return this.snow != null; 431 | } 432 | public Precipitation getSnowObj () { 433 | return this.snow; 434 | } 435 | 436 | public boolean hasPrecipitationSample () { 437 | return this.precipitation != null; 438 | } 439 | public SampledIValue getPrecipitationObj () { 440 | return this.precipitation; 441 | } 442 | 443 | public float getWindSpeed () { 444 | if (hasWind () && this.wind.hasSpeed ()) 445 | return this.wind.getSpeed (); 446 | return Float.NaN; 447 | } 448 | 449 | public float getWindGust () { 450 | if (hasWind () && this.wind.hasGust ()) 451 | return this.wind.getGust (); 452 | return Float.NaN; 453 | } 454 | 455 | public int getWindDeg () { 456 | if (hasWind () && this.wind.hasDeg ()) 457 | return this.wind.getDeg (); 458 | return Integer.MIN_VALUE; 459 | } 460 | 461 | public int getRain () { 462 | if (!hasRain ()) 463 | return Integer.MIN_VALUE; 464 | 465 | SampledIValue lastHourRainReport = this.rain.getMeasure (1); 466 | if (lastHourRainReport != null && lastHourRainReport.hasValue ()) 467 | return lastHourRainReport.getValue (); 468 | return this.rain.getToday (); 469 | } 470 | 471 | public int getSnow () { 472 | if (!hasSnow ()) 473 | return Integer.MIN_VALUE; 474 | 475 | SampledIValue lastHourRainReport = this.rain.getMeasure (1); 476 | if (lastHourRainReport != null && lastHourRainReport.hasValue ()) 477 | return lastHourRainReport.getValue (); 478 | return this.rain.getToday (); 479 | } 480 | 481 | public int getPrecipitation () { 482 | if (hasPrecipitationSample () && this.precipitation.hasValue ()) 483 | return this.precipitation.getValue (); 484 | int precipitation = Integer.MIN_VALUE; 485 | if (hasRain ()) 486 | precipitation = getRain (); 487 | if (hasSnow ()) 488 | precipitation = precipitation != Integer.MIN_VALUE ? precipitation + getSnow () : getSnow (); 489 | return precipitation; 490 | } 491 | } -------------------------------------------------------------------------------- /lib/src/main/java/org/bitpipeline/lib/owm/WeatherData.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 J. Miguel P. Tavares 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***************************************************************************/ 16 | package org.bitpipeline.lib.owm; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Collections; 20 | import java.util.HashMap; 21 | import java.util.List; 22 | import java.util.Locale; 23 | import java.util.Map; 24 | import java.util.Set; 25 | 26 | import org.json.JSONArray; 27 | import org.json.JSONObject; 28 | 29 | public class WeatherData extends AbstractWeatherData { 30 | private static final String JSON_CLOUDS = "clouds"; 31 | private static final String JSON_WEATHER = "weather"; 32 | 33 | public static class Main extends AbstractWeatherData.Main { 34 | private final float temp; 35 | private final float tempMin; 36 | private final float tempMax; 37 | private final float pressure; 38 | private final float humidity; 39 | 40 | public Main (JSONObject json) { 41 | this.temp = (float) json.optDouble (Main.JSON_TEMP); 42 | this.tempMin = (float) json.optDouble (Main.JSON_TEMP_MIN); 43 | this.tempMax = (float) json.optDouble (Main.JSON_TEMP_MAX); 44 | this.pressure = (float) json.optDouble (Main.JSON_PRESSURE); 45 | this.humidity = (float) json.optDouble (Main.JSON_HUMIDITY); 46 | } 47 | 48 | public boolean hasTemp () { 49 | return !Float.isNaN (this.temp); 50 | } 51 | public float getTemp () { 52 | return this.temp; 53 | } 54 | 55 | public boolean hasTempMin () { 56 | return !Float.isNaN (this.tempMin); 57 | } 58 | public float getTempMin () { 59 | return this.tempMin; 60 | } 61 | 62 | public boolean hasTempMax () { 63 | return !Float.isNaN (this.tempMax); 64 | } 65 | public float getTempMax () { 66 | return this.tempMax; 67 | } 68 | 69 | public boolean hasPressure () { 70 | return !Float.isNaN (this.pressure); 71 | } 72 | public float getPressure () { 73 | return this.pressure; 74 | } 75 | 76 | public boolean hasHumidity () { 77 | return !Float.isNaN (this.humidity); 78 | } 79 | public float getHumidity () { 80 | return this.humidity; 81 | } 82 | } 83 | 84 | public static class Wind extends AbstractWeatherData.Wind { 85 | private final float speed; 86 | private final int deg; 87 | private final float gust; 88 | private final int varBeg; 89 | private final int varEnd; 90 | 91 | public Wind (JSONObject json) { 92 | this.speed = (float) json.optDouble (Wind.JSON_SPEED); 93 | this.deg = json.optInt (Wind.JSON_DEG, Integer.MIN_VALUE); 94 | this.gust = (float) json.optDouble (Wind.JSON_GUST); 95 | this.varBeg = json.optInt (Wind.JSON_VAR_BEG, Integer.MIN_VALUE); 96 | this.varEnd = json.optInt (Wind.JSON_VAR_END, Integer.MIN_VALUE); 97 | } 98 | 99 | public boolean hasSpeed () { 100 | return !Float.isNaN (this.speed); 101 | } 102 | public float getSpeed () { 103 | return this.speed; 104 | } 105 | 106 | public boolean hasDeg () { 107 | return this.deg != Integer.MIN_VALUE; 108 | } 109 | public int getDeg () { 110 | return this.deg; 111 | } 112 | 113 | public boolean hasGust () { 114 | return !Float.isNaN (this.gust); 115 | } 116 | public float getGust () { 117 | return this.gust; 118 | } 119 | 120 | public boolean hasVarBeg () { 121 | return this.varBeg != Integer.MIN_VALUE; 122 | } 123 | public int getVarBeg () { 124 | return this.varBeg; 125 | } 126 | 127 | public boolean hasVarEnd () { 128 | return this.varEnd != Integer.MIN_VALUE; 129 | } 130 | public int getVarEnd () { 131 | return this.varEnd; 132 | } 133 | } 134 | 135 | private static class TimedDetails { 136 | private Map measurements = null; 137 | 138 | TimedDetails () { 139 | } 140 | 141 | TimedDetails (JSONObject json) { 142 | for (int i=1; i<=24; i++) { 143 | String value = json.optString (String.format (Locale.ROOT, "%dh", i)); 144 | if (value.length () > 0) { 145 | try { 146 | putMeasure (i, Integer.valueOf (value)); 147 | } catch (NumberFormatException nfe) { 148 | continue; 149 | } 150 | } 151 | } 152 | } 153 | 154 | public boolean hasMeasures () { 155 | return this.measurements != null && this.measurements.size () > 0; 156 | } 157 | private void putMeasure (int lastHours, Integer value) { 158 | if (this.measurements == null) 159 | this.measurements = new HashMap (); 160 | this.measurements.put (Integer.valueOf (lastHours), value); 161 | } 162 | public int getMeasure (int lastHours) { 163 | return getMeasure (Integer.valueOf (lastHours)); 164 | } 165 | public int getMeasure (Integer lastHours) { 166 | if (this.measurements == null) 167 | return Integer.MIN_VALUE; 168 | Integer value = this.measurements.get (lastHours); 169 | return value != null? value.intValue () : Integer.MIN_VALUE; 170 | } 171 | public Set measurements () { 172 | if (this.measurements == null) 173 | return Collections.emptySet (); 174 | return this.measurements.keySet (); 175 | } 176 | } 177 | 178 | public static class Clouds extends TimedDetails { 179 | private static final String JSON_ALL = "all"; 180 | 181 | public static class CloudDescription { 182 | private static final String JSON_DISTANCE = "distance"; 183 | private static final String JSON_CONDITION = "condition"; 184 | private static final String JSON_CUMULUS = "cumulus"; 185 | 186 | public static enum SkyCondition { 187 | UNKNOWN ("unknown"), 188 | FEW ("few [12.5%, 25%]"), 189 | SCT ("scattered [37.5%, 50%]"), 190 | BKN ("broken sky [62%, 87.5%]"), 191 | OVC ("overcast {100%}"), 192 | VV ("vertical visibility"); 193 | 194 | private final String description; 195 | 196 | private SkyCondition (String description) { 197 | this.description = description; 198 | } 199 | 200 | public String getDescription () { 201 | return this.description; 202 | } 203 | } 204 | 205 | public static enum Cumulus { 206 | UNKNOWN ("unknown"), 207 | TCU ("towering cumulus"), 208 | CB ("cumulonimbus"), 209 | ACC ("altocumulus castellanus"); 210 | 211 | private final String description; 212 | 213 | private Cumulus (String description) { 214 | this.description = description; 215 | } 216 | 217 | public String getDescription () { 218 | return this.description; 219 | } 220 | } 221 | 222 | private SkyCondition skyCondition = null; 223 | private Cumulus cumulus = null; 224 | private final int distance; 225 | 226 | public CloudDescription (JSONObject json) { 227 | this.distance = json.optInt (CloudDescription.JSON_DISTANCE, Integer.MIN_VALUE); 228 | if (json.has (CloudDescription.JSON_CONDITION)) { 229 | try { 230 | this.skyCondition = SkyCondition.valueOf (json.optString (CloudDescription.JSON_CONDITION)); 231 | } catch (IllegalArgumentException e) { 232 | this.skyCondition = SkyCondition.UNKNOWN; 233 | } 234 | } 235 | if (json.has (CloudDescription.JSON_CUMULUS)) { 236 | try { 237 | this.cumulus = Cumulus.valueOf (json.optString (CloudDescription.JSON_CUMULUS)); 238 | } catch (IllegalArgumentException e) { 239 | this.cumulus = Cumulus.UNKNOWN; 240 | } 241 | } 242 | } 243 | 244 | public boolean hasDistance () { 245 | return this.distance != Integer.MIN_VALUE; 246 | } 247 | public int getDistance () { 248 | return this.distance; 249 | } 250 | 251 | public boolean hasSkyCondition () { 252 | return this.skyCondition != null; 253 | } 254 | public SkyCondition getSkyCondition () { 255 | return this.skyCondition; 256 | } 257 | 258 | public boolean hasCumulus () { 259 | return this.cumulus != null; 260 | } 261 | public Cumulus getCumulus () { 262 | return this.cumulus; 263 | } 264 | } 265 | 266 | private final int all; 267 | private final List conditions; 268 | 269 | public Clouds (JSONObject json) { 270 | super (json); 271 | this.all = json.optInt (Clouds.JSON_ALL, Integer.MIN_VALUE); 272 | this.conditions = Collections.emptyList (); 273 | } 274 | 275 | public Clouds (JSONArray jsonArray) { 276 | this.all = Integer.MIN_VALUE; 277 | this.conditions = new ArrayList (jsonArray.length ()); 278 | for (int i = 0; i < jsonArray.length (); i++) { 279 | JSONObject jsonCloudDescription = jsonArray.optJSONObject (i); 280 | if (jsonCloudDescription != null) 281 | this.conditions.add ( 282 | new CloudDescription (jsonCloudDescription)); 283 | } 284 | } 285 | 286 | public boolean hasAll () { 287 | return this.all != Integer.MIN_VALUE; 288 | } 289 | public int getAll () { 290 | return this.all; 291 | } 292 | 293 | public boolean hasConditions () { 294 | return this.conditions != null && !this.conditions.isEmpty (); 295 | } 296 | public List getConditions () { 297 | return this.conditions; 298 | } 299 | } 300 | 301 | public static class Precipitation extends TimedDetails { 302 | private static final String JSON_TODAY = "today"; 303 | private final int today; 304 | 305 | public Precipitation (JSONObject json) { 306 | super (json); 307 | this.today = json.optInt (Precipitation.JSON_TODAY, Integer.MIN_VALUE); 308 | } 309 | 310 | public boolean hasToday () { 311 | return this.today != Integer.MIN_VALUE; 312 | } 313 | public int getToday () { 314 | return this.today; 315 | } 316 | } 317 | 318 | public static class WeatherCondition { 319 | public static enum ConditionCode { 320 | UNKNOWN (Integer.MIN_VALUE), 321 | /* Thunderstorm */ 322 | THUNDERSTORM_WITH_LIGHT_RAIN (200), 323 | THUNDERSTORM_WITH_RAIN (201), 324 | THUNDERSTORM_WITH_HEAVY_RAIN (202), 325 | LIGHT_THUNDERSTORM (210), 326 | THUNDERSTORM (211), 327 | HEAVY_THUNDERSTORM (212), 328 | RAGGED_THUNDERSTORM (221), 329 | THUNDERSTORM_WITH_LIGHT_DRIZZLE (230), 330 | THUNDERSTORM_WITH_DRIZZLE (231), 331 | THUNDERSTORM_WITH_HEAVY_DRIZZLE (232), 332 | /* Drizzle */ 333 | LIGHT_INTENSITY_DRIZZLE (300), 334 | DRIZZLE (301), 335 | HEAVY_INTENSITY_DRIZZLE (302), 336 | LIGHT_INTENSITY_DRIZZLE_RAIN (310), 337 | DRIZZLE_RAIN (311), 338 | HEAVY_INTENSITY_DRIZZLE_RAIN (312), 339 | SHOWER_DRIZZLE (321), 340 | /* Rain */ 341 | LIGHT_RAIN (500), 342 | MODERATE_RAIN (501), 343 | HEAVY_INTENSITY_RAIN (502), 344 | VERY_HEAVY_RAIN (503), 345 | EXTREME_RAIN (504), 346 | FREEZING_RAIN (511), 347 | LIGHT_INTENSITY_SHOWER_RAIN (520), 348 | SHOWER_RAIN (521), 349 | HEAVY_INTENSITY_SHOWER_RAIN (522), 350 | /* Snow */ 351 | LIGHT_SNOW (600), 352 | SNOW (601), 353 | HEAVY_SNOW (602), 354 | SLEET (611), 355 | SHOWER_SNOW (621), 356 | /* Atmosphere */ 357 | MIST (701), 358 | SMOKE (711), 359 | HAZE (721), 360 | SAND_OR_DUST_WHIRLS (731), 361 | FOG (741), 362 | /* Clouds */ 363 | SKY_IS_CLEAR (800), 364 | FEW_CLOUDS (801), 365 | SCATTERED_CLOUDS (802), 366 | BROKEN_CLOUDS (803), 367 | OVERCAST_CLOUDS (804), 368 | /* Extreme */ 369 | TORNADO (900), 370 | TROPICAL_STORM (901), 371 | HURRICANE (902), 372 | COLD (903), 373 | HOT (904), 374 | WINDY (905), 375 | HAIL (906); 376 | 377 | private int id; 378 | private ConditionCode (int code) { 379 | this.id = code; 380 | } 381 | 382 | static public ConditionCode valueof (int id) { 383 | for (ConditionCode condition : ConditionCode.values ()) { 384 | if (condition.id == id) 385 | return condition; 386 | } 387 | return ConditionCode.UNKNOWN; 388 | } 389 | 390 | public int getId () { 391 | return this.id; 392 | } 393 | } 394 | 395 | private static final String JSON_ID = "id"; 396 | private static final String JSON_MAIN = "main"; 397 | private static final String JSON_DESCRIPTION = "description"; 398 | private static final String JSON_ICON = "icon"; 399 | 400 | private ConditionCode code = null; 401 | private String main = null; 402 | private String description = null; 403 | private String iconName = null; 404 | 405 | public WeatherCondition (JSONObject json) { 406 | this.code = ConditionCode.valueof (json.optInt (WeatherCondition.JSON_ID, Integer.MIN_VALUE)); 407 | this.main = json.optString (WeatherCondition.JSON_MAIN); 408 | this.description = json.optString (WeatherCondition.JSON_DESCRIPTION); 409 | this.iconName = json.optString (WeatherCondition.JSON_ICON); 410 | } 411 | 412 | public ConditionCode getCode () { 413 | return this.code; 414 | } 415 | 416 | public boolean hasMain () { 417 | return this.main != null && this.main.length () > 0; 418 | } 419 | public String getMain () { 420 | return this.main; 421 | } 422 | 423 | public boolean hasDescription () { 424 | return this.description != null && this.description.length () > 0; 425 | } 426 | public String getDescription () { 427 | return this.description; 428 | } 429 | 430 | public boolean hasIconName () { 431 | return this.iconName != null && this.iconName.length () > 0; 432 | } 433 | public String getIconName () { 434 | return this.iconName; 435 | } 436 | } 437 | 438 | 439 | private final Main main; 440 | private final Wind wind; 441 | private final Clouds clouds; 442 | private final Precipitation rain; 443 | private final Precipitation snow; 444 | private final List weatherConditions; 445 | 446 | public WeatherData (JSONObject json) { 447 | super (json); 448 | 449 | JSONObject jsonMain = json.optJSONObject (WeatherData.JSON_MAIN); 450 | this.main = jsonMain != null ? new Main (jsonMain) : null; 451 | 452 | JSONObject jsonWind = json.optJSONObject (WeatherData.JSON_WIND); 453 | this.wind = jsonWind != null ? new Wind (jsonWind) : null; 454 | 455 | if (json.has (WeatherData.JSON_CLOUDS)) { 456 | JSONArray coudsArray = json.optJSONArray (WeatherData.JSON_CLOUDS); 457 | if (coudsArray != null) 458 | this.clouds = new Clouds (coudsArray); 459 | else { 460 | JSONObject cloudsObj = json.optJSONObject (WeatherData.JSON_CLOUDS); 461 | if (cloudsObj != null) 462 | this.clouds = new Clouds (cloudsObj); 463 | else 464 | this.clouds = null; 465 | } 466 | } else 467 | this.clouds = null; 468 | 469 | JSONObject jsonRain = json.optJSONObject (WeatherData.JSON_RAIN); 470 | this.rain = jsonRain != null ? new Precipitation (jsonRain) : null; 471 | 472 | JSONObject jsonSnow = json.optJSONObject (WeatherData.JSON_SNOW); 473 | this.snow = jsonSnow != null ? new Precipitation (jsonSnow) : null; 474 | 475 | if (json.has (WeatherData.JSON_WEATHER)) { 476 | JSONArray jsonConditions = json.optJSONArray (WeatherData.JSON_WEATHER); 477 | if (jsonConditions != null) { 478 | this.weatherConditions = new ArrayList (jsonConditions.length ()); 479 | if (jsonConditions != null) { 480 | for (int i = 0; i < jsonConditions.length (); i++) { 481 | JSONObject jsonCondition = jsonConditions.optJSONObject (i); 482 | if (jsonCondition != null) 483 | this.weatherConditions.add ( 484 | new WeatherCondition (jsonCondition)); 485 | } 486 | } 487 | } else { 488 | this.weatherConditions = Collections.emptyList (); 489 | } 490 | } else { 491 | this.weatherConditions = Collections.emptyList (); 492 | } 493 | } 494 | 495 | public boolean hasMain () { 496 | return this.main != null; 497 | } 498 | public Main getMain () { 499 | return this.main; 500 | } 501 | 502 | public boolean hasWind () { 503 | return this.wind != null; 504 | } 505 | public Wind getWind () { 506 | return this.wind; 507 | } 508 | 509 | public boolean hasClouds () { 510 | return this.clouds != null; 511 | } 512 | public Clouds getClouds () { 513 | return this.clouds; 514 | } 515 | 516 | public boolean hasRain () { 517 | return this.rain != null; 518 | } 519 | public Precipitation getRainObj () { 520 | return this.rain; 521 | } 522 | 523 | public boolean hasSnow () { 524 | return this.snow != null; 525 | } 526 | public Precipitation getSnowObj () { 527 | return this.snow; 528 | } 529 | 530 | public boolean hasWeatherConditions () { 531 | return this.weatherConditions != null && !this.weatherConditions.isEmpty (); 532 | } 533 | public List getWeatherConditions () { 534 | return this.weatherConditions; 535 | } 536 | 537 | /* */ 538 | 539 | public float getTemp () { 540 | if (hasMain () && this.main.hasTemp ()) 541 | return this.main.getTemp (); 542 | return Float.NaN; 543 | } 544 | 545 | public float getHumidity () { 546 | if (hasMain () && this.main.hasHumidity ()) 547 | return this.main.getHumidity (); 548 | return Float.NaN; 549 | } 550 | 551 | public float getPressure () { 552 | if (hasMain () && this.main.hasPressure ()) 553 | return this.main.getPressure (); 554 | return Float.NaN; 555 | } 556 | 557 | public float getWindSpeed () { 558 | if (hasWind () && this.wind.hasSpeed ()) 559 | return this.wind.getSpeed (); 560 | return Float.NaN; 561 | } 562 | 563 | public float getWindGust () { 564 | if (hasWind () && this.wind.hasGust ()) 565 | return this.wind.getGust (); 566 | return Float.NaN; 567 | } 568 | 569 | public int getWindDeg () { 570 | if (hasWind () && this.wind.hasDeg ()) 571 | return this.wind.getDeg (); 572 | return Integer.MIN_VALUE; 573 | } 574 | 575 | public int getRain () { 576 | if (!hasRain ()) 577 | return Integer.MIN_VALUE; 578 | int measure = this.rain.getMeasure (1); 579 | if (measure != Integer.MIN_VALUE) 580 | return measure; 581 | return this.rain.getToday (); 582 | } 583 | 584 | public int getSnow () { 585 | if (!hasSnow ()) 586 | return Integer.MIN_VALUE; 587 | int measure = this.snow.getMeasure (1); 588 | if (measure != Integer.MIN_VALUE) 589 | return measure; 590 | return this.snow.getToday (); 591 | } 592 | 593 | public int getPrecipitation () { 594 | int precipitation = Integer.MIN_VALUE; 595 | if (hasRain ()) 596 | precipitation = getRain (); 597 | if (hasSnow ()) 598 | precipitation = precipitation != Integer.MIN_VALUE ? precipitation + getSnow () : getSnow (); 599 | return precipitation; 600 | } 601 | } -------------------------------------------------------------------------------- /resources/code_formatters/eclipse.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | --------------------------------------------------------------------------------