Since I've looked far and wide for a good example of this to no avail, I have created my own using the JSONArray
and JSONObject
classes. It took me a while to realize that the push
method for JSONObject
overwrites everything previously pushed.
public class PieChartData{
private static Logger logger = LoggerFactory.getLogger(PieChartData.class);
private static String envURL = System.getProperty("publicWebsite.env.url");
public PieChartData(){
}
public static JSONArray getJSON(String dataLocation)throws IOException, URISyntaxException, TransformerException, JSONException {
return getCSV(dataLocation);
}
public static JSONArray getCSV(String url) throws IOException, JSONException{
url = url.replace("ex.com", envURL + "ex.com");
String retVal = "";
HttpClient httpClient = new DefaultHttpClient();
JSONObject jObject = null;
JSONArray jArray = new JSONArray();
int count = 0;
try{
logger.info("\nSending 'GET' request to URL : " + url);
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
int responseCode = response.getStatusLine().getStatusCode();
logger.info("Response Code : " + responseCode);
if (responseCode != 404){
try(BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()))) {
if(reader != null){
//StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
String[] tab = aux.split(",");
if (count > 0){
jObject = new JSONObject();
jObject.put("name", tab[0]);
jObject.put("load", tab[1]);
jArray.put(jObject);
}
count++;
}
retVal = jArray.toString();
}
}
}
return jArray;
}finally{
httpClient.getConnectionManager().shutdown();
}
}
}