communication.WeatherService.java Source code

Java tutorial

Introduction

Here is the source code for communication.WeatherService.java

Source

/**
 * The contents of this file are based of of the class "OwmClient" made by J. Miguel P. Tavares.
 * "OwmClient" has the following license:
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package communication;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import other.Weather;

/**
 * Contains methods for querying the current weather condition at a location (specified by longitude and latitude).
 * 
 * @author Brandon
 *
 */
public class WeatherService {

    static private final String APPID_HEADER = "x-api-key";

    static public enum HistoryType {
        UNKNOWN, TICK, HOUR, DAY
    }

    private String baseOwmUrl = "http://api.openweathermap.org/data/2.5/"; // Edited by Brandon (from 2.1 -> 2.5)
    private String owmAPPID = null;

    private HttpClient httpClient;

    public WeatherService(String api_key) {
        this.httpClient = new DefaultHttpClient();
        this.owmAPPID = api_key;
    }

    /** Find current weather at the given geographic point.
     * 
     * @param lat
     * @param lon
     * @return
     * @throws IOException
     * @throws JSONException
     */
    public Weather currentWeatherAtCoords(float lat, float lon) {
        try {
            String subUrl = String.format(Locale.ROOT, "weather?lat=%f&lon=%f", Float.valueOf(lat),
                    Float.valueOf(lon));
            JSONObject response = doQuery(subUrl);
            return new Weather(response);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private JSONObject doQuery(String subUrl) throws JSONException, IOException {
        String responseBody = null;
        HttpGet httpget = new HttpGet(this.baseOwmUrl + subUrl);
        if (this.owmAPPID != null) {
            httpget.addHeader(WeatherService.APPID_HEADER, this.owmAPPID);
        }
        System.out.println("getting...");
        HttpResponse response = this.httpClient.execute(httpget);
        System.out.println("...got");
        InputStream contentStream = null;
        try {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine == null) {
                throw new IOException(String.format("Unable to get a response from OWM server"));
            }
            int statusCode = statusLine.getStatusCode();
            if (statusCode < 200 && statusCode >= 300) {
                throw new IOException(
                        String.format("OWM server responded with status code %d: %s", statusCode, statusLine));
            }
            /* Read the response content */
            HttpEntity responseEntity = response.getEntity();
            contentStream = responseEntity.getContent();
            Reader isReader = new InputStreamReader(contentStream);
            int contentSize = (int) responseEntity.getContentLength();
            if (contentSize < 0)
                contentSize = 8 * 1024;
            StringWriter strWriter = new StringWriter(contentSize);
            char[] buffer = new char[8 * 1024];
            int n = 0;
            while ((n = isReader.read(buffer)) != -1) {
                strWriter.write(buffer, 0, n);
            }
            responseBody = strWriter.toString();
            contentStream.close();
        } catch (IOException e) {
            throw e;
        } catch (RuntimeException re) {
            httpget.abort();
            throw re;
        } finally {
            if (contentStream != null)
                contentStream.close();
        }
        System.out.println(responseBody); //Testing by Brandon
        return new JSONObject(responseBody);
    }

}