I was wondering if I could get some feedback on the library I created to persist data online.
JitterPushDemo.java
public class JitterPushDemo {
public static void main(String[] args) {
Jitter jitter = new Jitter("scores");
// create hash map to map scores to players
HashMap<String, String> map = new HashMap<String, String>();
map.put("Bob", "300");
map.put("Sam", "500");
// push data online to jitter object
jitter.pushData(map);
}
}
JitterPullDemo.java
public class JitterPullDemo {
public static void main(String[] args) {
Jitter jitter = new Jitter("scores");
// now pulling data from online and iterating
for (Map.Entry<String, String> item: jitter.pullData().entrySet()) {
System.out.println("Player: " + item.getKey());
System.out.println("Scores: " + item.getValue());
}
}
}
Source Code
package org.main;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
public class Jitter {
URL location;
String thing;
public Jitter(String thing) {
this.thing = thing;
}
private void setLocation(String place) {
try
{
location = new URL(place);
location.openConnection();
}
catch (Exception e)
{
}
}
public String readData() {
InputStream dataStream = null;
InputStreamReader read = null;
String result = ""; int value;
try
{
dataStream = location.openStream();
read = new InputStreamReader(dataStream);
while ((value = read.read()) != -1)
result += String.valueOf((char) value);
}
catch (Exception e)
{
}
return result;
}
public void pushData(HashMap<String, String> map) {
String url = "https://dweet.io/dweet/for/" + thing + "?";
for (Map.Entry<String, String> item : map.entrySet()) {
String k = URLEncoder.encode(item.getKey());
String v = URLEncoder.encode(item.getValue());
String sub = k + '=' + v + "&"; url += sub;
}
try
{
setLocation(url);
}
catch (Exception e)
{
}
readData();
}
public void pushData(String key, String value) {
String url = "https://dweet.io/dweet/for/" + thing + "?";
setLocation(url + key + "=" + value); readData();
}
public String pullData(String key) {
setLocation("https://dweet.io/get/latest/dweet/for/" + thing);
JSONArray main = new JSONObject(readData()).getJSONArray("with");
JSONObject data = ((JSONObject) main.get(0)).getJSONObject("content");
return data.optString(key);
}
public HashMap<String, String> pullData() {
setLocation("https://dweet.io/get/latest/dweet/for/" + thing);
JSONArray main = new JSONObject(readData()).getJSONArray("with");
JSONObject data = ((JSONObject) main.get(0)).getJSONObject("content");
HashMap<String, String> map = new HashMap<String, String>();
for (String key : data.keySet()) {
map.put(key, data.optString(key));
}
return map;
}
}