1 31 package org.blojsom.plugin.weather; 32 33 import org.apache.commons.logging.Log; 34 import org.apache.commons.logging.LogFactory; 35 import org.blojsom.plugin.weather.beans.WeatherInformation; 36 import org.blojsom.util.BlojsomConstants; 37 import org.w3c.dom.Document ; 38 import org.xml.sax.InputSource ; 39 import org.xml.sax.SAXException ; 40 41 import javax.xml.parsers.DocumentBuilder ; 42 import javax.xml.parsers.DocumentBuilderFactory ; 43 import javax.xml.parsers.ParserConfigurationException ; 44 import java.io.*; 45 import java.net.HttpURLConnection ; 46 import java.net.URL ; 47 import java.net.URLConnection ; 48 import java.util.zip.GZIPInputStream ; 49 50 58 public class WeatherFetcher { 59 60 private Log _logger = LogFactory.getLog(WeatherFetcher.class); 61 62 private DocumentBuilder _documentBuilder; 63 64 67 public WeatherFetcher() { 68 DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 69 documentBuilderFactory.setValidating(false); 70 documentBuilderFactory.setIgnoringElementContentWhitespace(true); 71 documentBuilderFactory.setIgnoringComments(true); 72 documentBuilderFactory.setCoalescing(true); 73 documentBuilderFactory.setNamespaceAware(false); 74 75 try { 76 _documentBuilder = documentBuilderFactory.newDocumentBuilder(); 77 } catch (ParserConfigurationException e) { 78 if (_logger.isErrorEnabled()) { 79 _logger.error(e); 80 } 81 } 82 } 83 84 92 public WeatherInformation retrieveForecast(WeatherInformation provider) throws IllegalArgumentException , IOException { 93 URL forecastUrl = new URL (provider.getProviderUrl()); 94 URLConnection connection = forecastUrl.openConnection(); 95 96 if (!(connection instanceof HttpURLConnection )) { 97 throw new IllegalArgumentException (forecastUrl.toExternalForm() + " is not a valid HTTP Url"); 98 } 99 100 HttpURLConnection httpConnection = (HttpURLConnection ) connection; 101 httpConnection.setRequestProperty("Accept-Encoding", WeatherConstants.GZIP); 102 httpConnection.setRequestProperty("User-Agent", WeatherConstants.BLOJSOM_WEATHER_USER_AGENT); 103 104 httpConnection.connect(); 105 InputStream is = connection.getInputStream(); 106 BufferedInputStream bis; 107 108 if (WeatherConstants.GZIP.equalsIgnoreCase(httpConnection.getContentEncoding())) { 109 bis = new BufferedInputStream(new GZIPInputStream (is)); 110 } else { 111 bis = new BufferedInputStream(is); 112 } 113 114 StringBuffer buffer = new StringBuffer (); 115 BufferedReader br = new BufferedReader(new InputStreamReader(bis)); 116 117 String input; 118 while ((input = br.readLine()) != null) { 119 buffer.append(input).append(BlojsomConstants.LINE_SEPARATOR); 120 } 121 122 try { 123 Document document = _documentBuilder.parse(new InputSource (new StringReader(buffer.toString()))); 124 provider.parseDocument(document); 125 } catch (SAXException e) { 126 if (_logger.isErrorEnabled()) { 127 _logger.error(e); 128 } 129 } 130 131 bis.close(); 132 133 return provider; 134 } 135 } 136 | Popular Tags |