Created
November 7, 2011 19:32
-
-
Save federecio/1345899 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Module(name="googlemaps", schemaVersion="1.0") | |
| public class GoogleMapsModule | |
| { | |
| private static final String PROTOTYPE_URL = | |
| "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=%s&destinations=%s&units=%s&sensor=false"; | |
| private static final String DISTANCE_XPATH = "//DistanceMatrixResponse/row/element/distance/text/text()"; | |
| @Configurable | |
| private DistanceUnit distanceUnit; | |
| @Processor | |
| public String getDistance(String origin, String destination) throws Exception | |
| { | |
| String effectiveUrl = String.format(PROTOTYPE_URL, origin, destination, distanceUnit); | |
| InputStream responseStream = new URL(effectiveUrl).openConnection().getInputStream(); | |
| try | |
| { | |
| return getXPath(responseStream, DISTANCE_XPATH); | |
| } | |
| finally | |
| { | |
| IOUtils.closeQuietly(responseStream); | |
| } | |
| } | |
| public void setDistanceUnit(String distanceUnit) | |
| { | |
| this.distanceUnit = distanceUnit; | |
| } | |
| private String getXPath(InputStream inputStream, String xpath) throws Exception { | |
| DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); | |
| dbf.setNamespaceAware(true); | |
| Document doc = dbf.newDocumentBuilder().parse(inputStream); | |
| XPathFactory factory = XPathFactory.newInstance(); | |
| XPathExpression expr = factory.newXPath().compile(xpath); | |
| return (String) expr.evaluate(doc, XPathConstants.STRING); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment