View Javadoc
1   /*
2    * Copyright (c) Patrick Magauran 2018.
3    *   Licensed under the AGPLv3. All conditions of said license apply.
4    *       This file is part of ABOS.
5    *
6    *       ABOS is free software: you can redistribute it and/or modify
7    *       it under the terms of the GNU Affero General Public License as published by
8    *       the Free Software Foundation, either version 3 of the License, or
9    *       (at your option) any later version.
10   *
11   *       ABOS is distributed in the hope that it will be useful,
12   *       but WITHOUT ANY WARRANTY; without even the implied warranty of
13   *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   *       GNU Affero General Public License for more details.
15   *
16   *       You should have received a copy of the GNU Affero General Public License
17   *       along with ABOS.  If not, see <http://www.gnu.org/licenses/>.
18   */
19  
20  package Utilities;/*
21   * Copyright (c) Patrick Magauran 2018.
22   *   Licensed under the AGPLv3. All conditions of said license apply.
23   *       This file is part of ABOS.
24   *
25   *       ABOS is free software: you can redistribute it and/or modify
26   *       it under the terms of the GNU Affero General Public License as published by
27   *       the Free Software Foundation, either version 3 of the License, or
28   *       (at your option) any later version.
29   *
30   *       ABOS is distributed in the hope that it will be useful,
31   *       but WITHOUT ANY WARRANTY; without even the implied warranty of
32   *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33   *       GNU Affero General Public License for more details.
34   *
35   *       You should have received a copy of the GNU Affero General Public License
36   *       along with ABOS.  If not, see <http://www.gnu.org/licenses/>.
37   */
38  
39  import Exceptions.addressException;
40  import org.w3c.dom.Document;
41  import org.w3c.dom.Element;
42  import org.w3c.dom.Node;
43  import org.w3c.dom.NodeList;
44  import org.xml.sax.InputSource;
45  import org.xml.sax.SAXException;
46  
47  import javax.xml.parsers.DocumentBuilder;
48  import javax.xml.parsers.DocumentBuilderFactory;
49  import javax.xml.parsers.ParserConfigurationException;
50  import java.io.BufferedReader;
51  import java.io.IOException;
52  import java.io.InputStreamReader;
53  import java.io.StringReader;
54  import java.net.HttpURLConnection;
55  import java.net.URL;
56  import java.util.Objects;
57  
58  /**
59   * Created by patrick on 7/26/16.
60   */
61  public class Geolocation {
62  
63      /**
64       * Takes a zipcode and returns the city and state of the customer.
65       *
66       * @param zipCode The Zipcode of the customer
67       * @return The City and state of the customer
68       * @throws IOException If it fails to retrieve the city and state
69       */
70      public static String getCityState(String zipCode) throws IOException {
71          //String AddressF = Address.replace(" ","+");
72          //The URL for the MapquestAPI
73  
74          String url = String.format("https://api.opencagedata.com/geocode/v1/xml?key=4745cb28cf7744d7b43f1dd482b83d5d&countrycode=us&min_confidence=6&no_annotations=1&q=%s", zipCode);
75  
76          //Defines connection
77          URL obj = new URL(url);
78          HttpURLConnection con = (HttpURLConnection) obj.openConnection();
79          con.setRequestMethod("GET");
80          //add request header
81          con.setRequestProperty("User-Agent", "Mozilla/5.0");
82          String city = "";
83          String State = "";
84          Integer prevConfidence = 0;
85          //Creates Response buffer for Web response
86          try (BufferedReader in = new BufferedReader(
87                  new InputStreamReader(con.getInputStream()))) {
88              String inputLine;
89              StringBuilder response = new StringBuilder();
90  
91              //Fill String buffer with response
92              while ((inputLine = in.readLine()) != null) {
93                  //inputLine = StringEscapeUtils.escapeHtml4(inputLine);
94                  //inputLine = StringEscapeUtils.escapeXml11(inputLine);
95                  response.append(inputLine);
96              }
97  
98  
99              //Parses XML response and fills City and State Variables
100             try {
101                 InputSource is = new InputSource(new StringReader(response.toString()));
102 
103                 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
104                 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
105                 Document doc = dBuilder.parse(is);
106 
107                 doc.getDocumentElement().normalize();
108 
109                 //System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
110 
111                 NodeList nList = doc.getElementsByTagName("result");
112 
113 
114                 for (int temp = 0; temp < nList.getLength(); temp++) {
115 
116                     Node nNode = nList.item(temp);
117 
118 
119                     if ((int) nNode.getNodeType() == (int) Node.ELEMENT_NODE) {
120 
121                         Element eElement = (Element) nNode;
122                         if (Objects.equals(eElement.getElementsByTagName("_type").item(0).getTextContent(), "city") && Integer.valueOf(eElement.getElementsByTagName("confidence").item(0).getTextContent()) > prevConfidence) {
123 
124                             city = eElement.getElementsByTagName("city").item(0).getTextContent();
125                             State = eElement.getElementsByTagName("state").item(0).getTextContent();
126                         }
127 
128                         //final Object[] columnNames = {"Product Name", "Size", "Price/Item", "Quantity", "Total Cost"};
129 
130 
131                     }
132                 }
133             } catch (Exception e) {
134                 LogToFile.log(e, Severity.WARNING, "Error parsing geolocation server response. Please Check the address and try again");
135             }
136         }
137         //Formats City and state into one string to return
138         String fullName = city + '&';
139         fullName += State;
140         //print result
141         //	return parseCoords(response.toString());
142         return fullName;
143     }
144 
145     public static Coords GetCoords(String Address) throws IOException {
146         String AddressF = Address.replace(" ", "%20");
147         String url = String.format("https://api.opencagedata.com/geocode/v1/xml?key=4745cb28cf7744d7b43f1dd482b83d5d&countrycode=us&min_confidence=6&no_annotations=1&q=%s", AddressF);
148         Integer prevConfidence = 0;
149 
150         URL obj = new URL(url);
151         HttpURLConnection con = (HttpURLConnection) obj.openConnection();
152 
153         // optional default is GET
154         con.setRequestMethod("GET");
155 
156         //add request header
157         String USER_AGENT = "Mozilla/5.0";
158         con.setRequestProperty("User-Agent", USER_AGENT);
159 
160         //int responseCode = con.getResponseCode();
161         //System.out.println("\nSending 'GET' request to URL : " + url);
162         //System.out.println("Response Code : " + responseCode);
163 
164         try (BufferedReader in = new BufferedReader(
165                 new InputStreamReader(con.getInputStream()))) {
166             String inputLine;
167             StringBuilder response = new StringBuilder();
168 
169             while ((inputLine = in.readLine()) != null) {
170                 response.append(inputLine);
171             }
172 
173 
174             //print result
175             Coords coords = new Coords();
176             try {
177                 InputSource is = new InputSource(new StringReader(response.toString()));
178 
179                 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
180                 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
181                 Document doc = dBuilder.parse(is);
182 
183                 //optional, but recommended
184                 //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
185                 doc.getDocumentElement().normalize();
186 
187                 //System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
188 
189                 NodeList nList = doc.getElementsByTagName("result");
190 
191                 if (nList.getLength() < 1) { throw new addressException();}
192 
193 
194                 for (int temp = 0; temp < nList.getLength(); temp++) {
195 
196                     Node nNode = nList.item(temp);
197 
198 
199                     if ((int) nNode.getNodeType() == (int) Node.ELEMENT_NODE) {
200 
201                         Element eElement = (Element) nNode;
202                         if (Objects.equals(eElement.getElementsByTagName("_type").item(0).getTextContent(), "building") && Integer.valueOf(eElement.getElementsByTagName("confidence").item(0).getTextContent()) > prevConfidence) {
203                             Element geometry = (Element) eElement.getElementsByTagName("geometry").item(0);
204 
205 
206                             coords.setLat(Double.valueOf(geometry.getElementsByTagName("lat").item(0).getTextContent()));
207                             coords.setLon(Double.valueOf(geometry.getElementsByTagName("lng").item(0).getTextContent()));
208                         }
209 
210                         //final Object[] columnNames = {"Product Name", "Size", "Price/Item", "Quantity", "Total Cost"};
211 
212 
213                     }
214                 }
215             } catch (IOException | ParserConfigurationException | SAXException e) {
216                 LogToFile.log(e, Severity.WARNING, "Error parsing geolocation server response. Please try again or contact support.");
217             }
218             if (coords.getLat() <= -190 && coords.getLon() <= -190) {
219                 throw new addressException();
220 
221             } else {
222 
223 
224                 return coords;
225             }
226         } catch (Exception e) {
227             throw new addressException();
228         }
229     }
230 
231     private static Object[][] parseCoords(String xml) throws addressException {
232         Object[][] coords = new Object[1][2];
233         try {
234             InputSource is = new InputSource(new StringReader(xml));
235 
236             DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
237             DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
238             Document doc = dBuilder.parse(is);
239 
240             //optional, but recommended
241             //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
242             doc.getDocumentElement().normalize();
243 
244             //System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
245 
246             NodeList nList = doc.getElementsByTagName("place");
247 
248             if (nList.getLength() < 1) { throw new addressException();}
249             for (int temp = 0; temp < nList.getLength(); temp++) {
250 
251                 Node nNode = nList.item(temp);
252 
253 
254                 if ((int) nNode.getNodeType() == (int) Node.ELEMENT_NODE) {
255 
256 
257                     coords[0][0] = ((Element) nNode).getAttributeNode("lat").getValue();
258                     coords[0][1] = ((Element) nNode).getAttributeNode("lon").getValue();
259 
260 
261                     //final Object[] columnNames = {"Product Name", "Size", "Price/Item", "Quantity", "Total Cost"};
262 
263 
264                 }
265             }
266         } catch (IOException | ParserConfigurationException | SAXException e) {
267             LogToFile.log(e, Severity.WARNING, "Error parsing geolocation server response. Please try again or contact support.");
268         }
269         return coords;
270     }
271 
272 
273 }