In this blog post I am going to explain about consuming the Global
Weather web service available at webservicex.net.
Global Weather:
Global Weather web service has two service operations
- GetCitiesByCountry
- GetWether
Initially I am going to populate a drop down list with some country
names. Based on a country you select, drop down will trigger an AJAX call which
in turn calls a service operation GetCitiesByCountry. This service operation
would return cities of the country you have selected in a XML format. You can
parse this XML and load another drop down with the city names. Then you can
select a city name in the city drop down list and it will call the GetWeather
service operation. This service operation would also returns an XML and I am
going to parse this using JAXB.
The WSDL location is.
Using the wsimport parse the WSDL and generate the web
service client Java files. (
See the blog post). Copy these files to
net.webservicex package. See the diagram for more information.
index.jsp
This page will display country names and the drop down is linked with the AJAX call.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function getCities() {
var selectOb = document.getElementById("country");
var country = selectOb.options[selectOb.selectedIndex].value;
if (country == "-1") {
alert("Invalid selection");
return false;
}
var xmlHttp;
xmlHttp = new XMLHttpRequest();
var url = "GetCities.jsp";
url += "?country=" + country;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
document.getElementById("cities").innerHTML = xmlHttp.responseText
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function getTemp(x) {
var selectOb = document.getElementById("country");
var country = selectOb.options[selectOb.selectedIndex].value;
if (country == "-1" || x == "select") {
alert("Invalid selection");
return false;
}
var xmlHttp;
xmlHttp = new XMLHttpRequest();
var url = "GetWeather.jsp";
url += "?country=" + country + "&city=" + x;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
document.getElementById("weather").innerHTML = xmlHttp.responseText
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
</script>
</head>
<body>
Country
<select onchange="getCities()" id="country">
<option value="-1">--select--</option>
<option value="India">India</option>
<option value="Ukraine">Ukraine</option>
<option value="US">US</option>
<option value="Nepal">Nepal</option>
<option value="Germany">Germany</option>
<option value="Japan">Japan</option>
</select>
<br>
<br>
<div id="cities">
Cities <select onChange="getTemp(this)"
id="city">
<option value="-1">--select--</option>
</select>
</div>
<div id="weather"></div>
</body>
</html>
GetCities.jsp
The AJAX call on a country drop down linked with GetCities.jsp.
This GetCities.jsp in turn call GetCitiesByCountry service operation via GlobalWeatherDelegate.java
<%@page import="org.sri.bd.GlobalWeatherDelegate"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
import="java.util.*" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String cities = "Cities <select name='cityselect' onChange=getTemp(this.value);> <option value='-1'>Select</option>";
GlobalWeatherDelegate globalWeatherbd = new GlobalWeatherDelegate();
ArrayList<String> cityList = (ArrayList<String>) globalWeatherbd
.getCities(request.getParameter("country"));
Iterator<String> cityIerator = cityList.iterator();
while (cityIerator.hasNext()) {
String city = cityIerator.next();
cities += "<option value=" + city + ">" + city + "</option>";
}
cities += "</select>";
System.out.println(cities);
out.println(cities);
%>
</body>
</html>
GetWeather.jsp
Once you select a city on the city drop down it will trigger
an AJAX call through GetWeather.jsp. GetWeather.jsp will call the GlobalWeatherDelegate.java
to get a weather information of a city
<%@page
import="org.sri.bd.GlobalWeatherDelegate,org.sri.bd.CurrentWeather"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
GlobalWeatherDelegate globalWeatherbd = new GlobalWeatherDelegate();
CurrentWeather currentWeather = globalWeatherbd.getWeather(
request.getParameter("city"), request.getParameter("country"));
if (currentWeather != null) {
String responseXml = "<table border=\"0\" cellspacing=\"10\" cellpadding=\"10\"> <th> "
+ request.getParameter("city")
+ "</th> <tr> <td> Location </td> <td> "
+ currentWeather.getLocation()
+ "</td> </tr>"
+ "<tr> <td> Time </td> <td> "
+ currentWeather.getTime()
+ "</td> </tr>"
+ "<tr> <td> wind </td> <td> "
+ currentWeather.getWind()
+ "</td> </tr>"
+ "<tr> <td> Visibility </td> <td> "
+ currentWeather.getVisibility()
+ "</td> </tr>"
+ "<tr> <td> Temperature </td> <td> "
+ currentWeather.getTemperature()
+ "</td> </tr>"
+ "<tr> <td> Pressure </td> <td> "
+ currentWeather.getPressure()
+ "</td> </tr>"
+ "<tr> <td> Dewpoint </td> <td> "
+ currentWeather.getDewPoint()
+ "</td> </tr>"
+ "<tr> <td> Humidity </td> <td> "
+ currentWeather.getRelativeHumidity()
+ "</td> </tr>"
+ "</table>";
out.print(responseXml);
} else {
out.print("<h3> No Data Found Try another City </h3>");
}
%>
<table border="1" cellspacing="10" cellpadding="10">
</table>
</body>
</html>
CurrentWeather.java
package org.sri.bd;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="CurrentWeather")
public class CurrentWeather {
private String location;
private String time;
private String wind;
private String visibility;
private String temperature;
private String dewPoint;
private String relativeHumidity;
private String pressure;
private String status;
@XmlElement(name="Location")
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
@XmlElement(name="Time")
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
@XmlElement(name="Wind")
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
@XmlElement(name="Visibility")
public String getVisibility() {
return visibility;
}
public void setVisibility(String visibility) {
this.visibility = visibility;
}
@XmlElement(name="Temperature")
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
@XmlElement(name="DewPoint")
public String getDewPoint() {
return dewPoint;
}
public void setDewPoint(String dewPoint) {
this.dewPoint = dewPoint;
}
@XmlElement(name="RelativeHumidity")
public String getRelativeHumidity() {
return relativeHumidity;
}
public void setRelativeHumidity(String relativeHumidity) {
this.relativeHumidity = relativeHumidity;
}
@XmlElement(name="Pressure")
public String getPressure() {
return pressure;
}
public void setPressure(String pressure) {
this.pressure = pressure;
}
@XmlElement(name="Status")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return "CurrentWeather [location=" + location + ", time=" + time
+ ", wind=" + wind + ", visibility=" + visibility
+ ", temperature=" + temperature + ", dewPoint=" + dewPoint
+ ", relativeHumidity=" + relativeHumidity + ", pressure="
+ pressure + ", status=" + status + "]";
}
}
GlobalWeatherDelegate.java
This Java class is responsible for calling the web service and fetching the details from it. This will parse the XML returned from the web service using the JAXB and give it back to the JSP.
package org.sri.bd;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import net.webservicex.GlobalWeather;
import n et.webservicex.GlobalWeatherSoap;
public class GlobalWeatherDelegate {
GlobalWeather weather = new GlobalWeather();
GlobalWeatherSoap soap = weather.getGlobalWeatherSoap();
public List<String> getCities(String countryName) {
ArrayList<String> cityList = new ArrayList<String>();
GlobalWeather weather = new GlobalWeather();
GlobalWeatherSoap soap = weather.getGlobalWeatherSoap();
String cities = soap.getCitiesByCountry(countryName);
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory
.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(cities));
Document doc = documentBuilder.parse(is);
NodeList nodes = doc.getElementsByTagName("Table");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList subnode = element.getElementsByTagName("City");
Element subelement = (Element) subnode.item(0);
cityList.add(subelement.getTextContent());
System.out.println(subelement.getTextContent());
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return cityList;
}
public CurrentWeather getWeather(String city, String country) {
try {
GlobalWeather weather = new GlobalWeather();
GlobalWeatherSoap soapWeather = weather.getGlobalWeatherSoap();
String response = soapWeather.getWeather(city, country);
if (response.equalsIgnoreCase("Data Not Found"))
return null;
else {
JAXBContext jAXBContext = JAXBContext
.newInstance(CurrentWeather.class);
Unmarshaller unmarshaller = jAXBContext.createUnmarshaller();
CurrentWeather currentWeather = (CurrentWeather) unmarshaller
.unmarshal(new StringReader(response));
return currentWeather;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}