JUnit test TestGoogleGeocoding



package test.nl.kameroom.location;

import java.io.InputStream;
import java.io.StringReader;
import java.net.URI;
import java.net.URL;
import java.sql.SQLException;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.xml.sax.InputSource;


public class TestGoogleGeocoding {
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		
	}

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testGeocoding() throws Exception {			
		    
		URI uri = new URI(
			    "http", 
			    "maps.googleapis.com",
			    "/maps/api/geocode/xml",
			    "address=,+NL&sensor=false", 
			    null);
		URL url = uri.toURL();
		InputStream is = url.openStream();
		String xml = IOUtils.toString(is, "utf-8"); //encoding is important
      
		XPathFactory xpathFactory = XPathFactory.newInstance();
		XPath xpath = xpathFactory.newXPath();
		System.out.println(xml);
		String lng = xpath.evaluate("//GeocodeResponse/result/geometry/location/lng[1]", new InputSource(new StringReader(xml)));
		String lat = xpath.evaluate("//GeocodeResponse/result/geometry/location/lat[1]", new InputSource(new StringReader(xml)));
		System.out.println("lng=" + lng);
		System.out.println("lat=" + lat);
		is.close(); 
	}
	
}


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s