Я использую библиотеку с открытым исходным кодом для подключения к Dweet.io в своем приложении для Android, но у меня возникли некоторые проблемы с этим.В своей основной деятельности я пытаюсь настроить метод DweetIO.listen, который должен использовать внутри него DweetListener.Я получаю следующую ошибку: «DweetListener is Abstract, не может быть создан экземпляр». Я не уверен, где я ошибаюсь, поскольку все примеры указывают на то, как я это сделал.Вы можете найти оригинальную библиотеку на следующем Github: https://github.com/kbakhit/java-dweetio
Хотите знать, есть ли у кого-нибудь идеи заставить слушателя работать?Я приложил весь код ниже.
MainActivitiy.Java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
test();
}
public void test() {
try {
String thingName= "java-client-thing";
JsonObject json= new JsonObject();
json.addProperty("hello", "test!");
DweetIO.publish(thingName, json);
DweetIO.listen(thingName, new DweetListener(), null);
// Dweet dweet= DweetIO.getLatestDweet(thingName);
// Log.d("debug",dweet.getThingName()+ " said : "+ dweet.getContent().get("hello").getAsString() +" at "+ dweet.getCreationDate());
List<Dweet> dweets= DweetIO.getAllDweets(thingName);
for(Dweet d: dweets) {
Log.d("debug2",d.getThingName() + " said : " + d.getContent() + " at " + d.getCreationDate());
}
}
catch (ParseException e) {
}
catch (IOException e) {
}
}
}
DweetListener.java
public interface DweetListener
{
public void dweetReceived(Dweet dweet);
public void stopListening(String thingName);
public boolean isStillListeningTo(String thingName);
public void stoppedListening(String thingName);
public void connectionLost(String thingName, Exception e);
}
DweetIO.Java
public class DweetIO {
public static final float VERSION= 1.0f;
public static final String API_END_POINT= "dweet.io";
public static boolean USE_SSL= true;
private static final JsonParser jsonParser= new JsonParser();
public static void setSSLEnabled(boolean enable)
{
USE_SSL= enable;
}
public static boolean isSSLEnabled()
{
return USE_SSL;
}
public static boolean removeLock(String lock, String key) throws IOException
{
if(lock== null || key == null)
throw new NullPointerException();
lock= URLEncoder.encode(lock,"UTF-8");
key= URLEncoder.encode(key,"UTF-8");
URL url= new URL(getAPIEndPointURL()+"/remove/lock/"+lock+"?key="+key);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
JsonObject response= readResponse(connection.getInputStream());
connection.disconnect();
return response.has("this") && response.get("this").getAsString().equals("succeeded");
}
public static boolean unlock(String thingName, String key) throws IOException
{
if(key == null || thingName == null)
throw new NullPointerException();
thingName = URLEncoder.encode(thingName, "UTF-8");
key = URLEncoder.encode(key, "UTF-8");
URL url = new URL(getAPIEndPointURL() + "/unlock/" + thingName + "?key=" + key);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
JsonObject response = readResponse(connection.getInputStream());
connection.disconnect();
return response.has("this") && response.get("this").getAsString().equals("succeeded");
}
public static boolean createAlert(String thingName, String recipients, String condition, String key) throws IOException
{
if(thingName == null || recipients == null || condition == null)
throw new NullPointerException();
condition= condition.trim();
if(condition.length() > 2000)
{
throw new IOException("condition script is too large (above 2000 characters) ");
}
thingName = URLEncoder.encode(thingName, "UTF-8");
recipients= URLEncoder.encode(recipients, "UTF-8");
condition= URLEncoder.encode(condition, "UTF-8");
URL url= new URL(getAPIEndPointURL()+ "/alert/"+recipients+"/when/"+ thingName+"/"+condition+((key==null)?"":"?key="+URLEncoder.encode(key,"UTF-8")));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
JsonObject response= readResponse(connection.getInputStream());
connection.disconnect();
return (response.has("this") && response.get("this").getAsString().equals("succeeded"));
}
public static boolean removeAlert(String thingName, String key) throws IOException
{
if(key == null || thingName == null)
throw new NullPointerException();
thingName = URLEncoder.encode(thingName, "UTF-8");
key = URLEncoder.encode(key, "UTF-8");
URL url = new URL(getAPIEndPointURL() + "/remove/alert/for/" + thingName + "?key=" + key);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
JsonObject response = readResponse(connection.getInputStream());
connection.disconnect();
return response.has("this") && response.get("this").getAsString().equals("succeeded");
}
public static boolean lock(String thingName, String lock, String key) throws IOException
{
if(key == null || lock == null || thingName == null)
throw new NullPointerException();
thingName = URLEncoder.encode(thingName, "UTF-8");
lock= URLEncoder.encode(lock,"UTF-8");
key= URLEncoder.encode(key,"UTF-8");
URL url= new URL(getAPIEndPointURL()+"/lock/"+thingName+"?lock="+lock+"&key="+key);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
JsonObject response= readResponse(connection.getInputStream());
connection.disconnect();
return response.has("this") && response.get("this").getAsString().equals("succeeded");
}
public static boolean publish(String thingName, JsonElement content) throws IOException
{
return publish(thingName, content, null);
}
public static boolean publish(String thingName, JsonElement content, String key) throws IOException
{
if(thingName == null || content == null)
throw new NullPointerException();
thingName = URLEncoder.encode(thingName, "UTF-8");
URL url= new URL(getAPIEndPointURL()+ "/dweet/for/"+ thingName+((key==null)?"":"?key="+URLEncoder.encode(key,"UTF-8")));
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
PrintWriter out= new PrintWriter(connection.getOutputStream());
out.println(content.toString());
out.flush();
out.close();
JsonObject response= readResponse(connection.getInputStream());
connection.disconnect();
return (response.has("this") && response.get("this").getAsString().equals("succeeded"));
}
public static void listen(String thingName, DweetListener listener)
{
listen(thingName, listener, null);
}
public static void listen(String thingName, DweetListener listener, String key)
{
if(thingName == null || listener == null)
throw new NullPointerException();
try
{
thingName = URLEncoder.encode(thingName, "UTF-8");
URL url= new URL(getAPIEndPointURL()+ "/listen/for/dweets/from/"+ thingName+((key==null)?"":"?key="+URLEncoder.encode(key,"UTF-8")));
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
Scanner scan= new Scanner(connection.getInputStream());
String line;
while(scan.hasNextLine())
{
if(!listener.isStillListeningTo(thingName))
break;
line= scan.nextLine().trim();
if(line.indexOf('{') == -1 || line.lastIndexOf('}') == -1)
continue;
line= line.substring(line.indexOf('{'), line.lastIndexOf('}') + 1);
line= line.replace("\\\"", "\"").replace("\\\\", "\\");
listener.dweetReceived(new Dweet(jsonParser.parse(line)));
}
scan.close();
connection.disconnect();
listener.stoppedListening(thingName);
}
catch(Exception e)
{
listener.connectionLost(thingName, e);
}
}
public static List<Dweet> getAllDweets(String thingName) throws IOException, ParseException
{
return getAllDweets(thingName, null);
}
public static List<Dweet> getAllDweets(String thingName, String key) throws IOException, ParseException
{
if(thingName == null)
throw new NullPointerException();
thingName = URLEncoder.encode(thingName, "UTF-8");
URL url= new URL(getAPIEndPointURL()+"/get/dweets/for/"+thingName+((key==null)?"":"?key="+URLEncoder.encode(key,"UTF-8")));
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
JsonObject response= readResponse(connection.getInputStream());
connection.disconnect();
if(response.has("this") && response.get("this").getAsString().equals("succeeded"))
{
List<Dweet> dweets= new LinkedList<Dweet>();
JsonArray arr= response.getAsJsonArray("with");
Iterator<JsonElement> it= arr.iterator();
while(it.hasNext())
dweets.add(new Dweet(it.next()));
return dweets;
}
return null;
}
public static Dweet getLatestDweet(String thingName) throws IOException, ParseException
{
return getLatestDweet(thingName, null);
}
public static Dweet getLatestDweet(String thingName, String key) throws IOException, ParseException
{
if(thingName == null)
throw new NullPointerException();
thingName = URLEncoder.encode(thingName, "UTF-8");
URL url= new URL(getAPIEndPointURL()+"/get/latest/dweet/for/"+thingName+((key==null)?"":"?key="+URLEncoder.encode(key,"UTF-8")));
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
JsonObject response= readResponse(connection.getInputStream());
connection.disconnect();
if(response.has("this") && response.get("this").getAsString().equals("succeeded"))
{
JsonArray arr= response.getAsJsonArray("with");
if(arr.size() == 0)
return null;
return new Dweet(arr.remove(0));
}
return null;
}
public static String getAPIEndPointURL()
{
return "http"+((USE_SSL)?"s":"")+"://"+API_END_POINT;
}
private static JsonObject readResponse(InputStream in)
{
Scanner scan= new Scanner(in);
StringBuilder sn= new StringBuilder();
while(scan.hasNext())
sn.append(scan.nextLine()).append('\n');
scan.close();
return jsonParser.parse( sn.toString()).getAsJsonObject();
} }
Dweet.Java
public class Dweet {
private static final DateFormat date_format= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
private final JsonElement jsonDweet;
private final String thingName;
private final Date createdDate;
private final JsonObject content;
protected Dweet(JsonElement jsonDweet) throws ParseException
{
this.jsonDweet= jsonDweet;
JsonObject j= jsonDweet.getAsJsonObject();
thingName= j.get("thing").getAsString();
content= j.get("content").getAsJsonObject();
String date_string= j.get("created").getAsString();
createdDate= date_format.parse(date_string);
}
public String getThingName()
{
return thingName;
}
public Date getCreationDate()
{
return createdDate;
}
public JsonObject getContent()
{
return content;
}
@Override
public String toString()
{
return jsonDweet.toString();
}
}