Commit c3104765 authored by Deepak's avatar Deepak

Added nearest postcode fetcher

parent 5883f913
package com.postcode.io.initializers;
import org.json.JSONObject;
import com.mashape.unirest.http.Unirest;
public class NearestPostcode {
private static final String LOOKUP_URL = "http://api.postcodes.io/postcodes/";
private static String postcode;
private static int limit;
private static int radius;
public NearestPostcode(String postcode) {
NearestPostcode.postcode = postcode;
}
/**
* Limits number of postcodes matches to return. Defaults to 10. Needs to be less than 100.
*
* @param limit
* @return
*/
public NearestPostcode limit(int limit) {
NearestPostcode.limit = limit;
return this;
}
/**
* Limits number of postcodes matches to return. Defaults to 100m. Needs to be less than 2,000m.
*
* @param radius
* @return
*/
public NearestPostcode radius(int radius) {
NearestPostcode.radius = radius;
return this;
}
/**
* Get JSON for the given {@link #postcode} / {@link #postcodes}
*
* @return
* @throws Exception
*/
public JSONObject asJson() throws Exception {
return Unirest.get(LOOKUP_URL.concat(postcode).concat("/nearest")).queryString("limit", limit != 0 ? limit : 10)
.queryString("radius", radius != 0 ? radius : 100).asJson().getBody().getObject();
}
}
......@@ -95,4 +95,8 @@ public class PostcodeLookup {
return Postcode.validatePostcode(postcode);
}
public static NearestPostcode nearestPostcode(String postcode) {
return new NearestPostcode(postcode);
}
}
......@@ -109,4 +109,14 @@ public class PostcodeLookupTest {
assertFalse(PostcodeLookup.validate("ST4"));
}
@Test
public void testNearestPostcode() throws Exception {
assertTrue(PostcodeLookup.nearestPostcode("ST4 2EU").asJson().get("status").equals(200));
assertEquals(7, PostcodeLookup.nearestPostcode("ST4 2EU").asJson().getJSONArray("result").length());
assertTrue(PostcodeLookup.nearestPostcode("ST4").asJson().get("status").equals(404));
assertEquals(5, PostcodeLookup.nearestPostcode("ST42EU").limit(5).asJson().getJSONArray("result").length());
assertEquals(7, PostcodeLookup.nearestPostcode("ST42EU").limit(20).radius(100).asJson().getJSONArray("result")
.length());
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment