package se252.jan15.calvinandhobbes.project0;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
* Echo web service exposed at "echo" path relative to base URI
*
* @author Yogesh Simmhan
* @version 1.0
* @see <a href="http://www.serc.iisc.ernet.in/~simmhan/SE252/">IISc SERC 'SE252:Intro to Cloud Computing' Course Webpage</a>
*
* (c) Yogesh Simmhan, 2015
* This work is licensed under a Attribution 4.0 International (CC BY 4.0).
* http://creativecommons.org/licenses/by/4.0/
*/
@Path("dataSDB")
public class IIScCampusMapSDB_GETService {
/**
* Method handling HTTP GET requests. The request expects a "msg" input parameter with value of type string.
* The returned object will be sent to the client as JSON media type.
*
* @return JSON form of EchoMessage will be returned as response.
*/
private static String placeLink = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
private static String apiGoogle = "AIzaSyCIthNbg4lwx-LWHxXMyw1wHBYssjmAuDA";
private static String pagetoken = "";
private static Calendar date = Calendar.getInstance();
private static LayerInfo[] cachedLayers = null;
private static LoadingCache<String, LayerInfo[]> categoryCache = null;
public static void cacheInit() {
categoryCache = CacheBuilder.newBuilder()
.maximumSize(7) // maximum 7 records can be cached
.expireAfterAccess(10, TimeUnit.MINUTES) // cache will expire after 10 minutes of access
.build(new CacheLoader<String, LayerInfo[]>(){ // build the cacheloader
@Override
public LayerInfo[] load(String category) throws Exception {
return getCategoryData(category);
}
});
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
private static JSONObject getJSON(String url) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.iisc.ernet.in", 3128));
InputStream is;
try {
is = new URL(url).openConnection(proxy).getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
is.close();
return json;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static LayerInfo[] diningOutside() {
ArrayList<LayerInfo> layers = new ArrayList<LayerInfo>();
if(date.get(Calendar.DATE) != Calendar.getInstance().get(Calendar.DATE))
date = Calendar.getInstance();
else if(cachedLayers != null)
return cachedLayers;
for(int i = 0; i < 3; i++) {
String url = placeLink + "location=13.020168,77.567319&radius=1500&types=restaurant&key=" + apiGoogle + "&pagetoken=" + pagetoken;
JSONObject jsonObj = getJSON(url);
if(jsonObj.has("next_page_token"))
pagetoken = jsonObj.getString("next_page_token");
JSONArray jsonPlaces = jsonObj.getJSONArray("results");
int len = jsonPlaces.length();
for(int j = 0; j < len; j++) {
JSONObject temp = jsonPlaces.getJSONObject(j);
LayerInfo layer = new LayerInfo(temp);
float lat = layer.getLatitude(), lon = layer.getLongitude();
float minLat = 13.011952F, minLon = 77.561869F, maxLat = 13.027422F, maxLon = 77.571224F;
if(!(minLat < lat && lat < maxLat && minLon < lon && lon < maxLon))
layers.add(layer);
}
try {
Thread.sleep(2000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
pagetoken = "";
cachedLayers = new LayerInfo[layers.size()];
layers.toArray(cachedLayers);
return cachedLayers;
}
public static LayerInfo[] getCategoryData(String category) {
System.out.println("called " + category);
LayerInfo[] layerArray = null;
if(category.equals("AllCategories"))
layerArray = SDBConn.getCategories();
else if(!category.equals("Dining Outside"))
layerArray = SDBConn.getCategoryInfo(category);
else
layerArray = diningOutside();
return layerArray;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public static Response IIScCampusMapGet(@DefaultValue("AllCategories") @QueryParam("category") String category) {
LayerInfo[] layers = null;
try {
layers = categoryCache.get(category);
} catch (ExecutionException e) {
e.printStackTrace();
}
return Response.ok(layers, MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin", "*").build();
}
}