accounting-dashboard-harves.../src/main/java/org/gcube/dataharvest/harvester/SocialHarvester.java

93 lines
2.6 KiB
Java

package org.gcube.dataharvest.harvester;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.dataharvest.datamodel.Harvest;
import org.gcube.dataharvest.utils.Utils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SocialHarvester extends BasicHarvester {
private static Logger logger = LoggerFactory.getLogger(SocialHarvester.class);
private int likes, replies, posts;
private long from = 0, to = 0;
public SocialHarvester(Date start, Date end) throws ParseException {
super(start, end);
this.from = startDate.getTime();
this.to = endDate.getTime();
}
@Override
public List<Harvest> getData() throws Exception {
String context = Utils.getCurrentContext();
try {
ArrayList<Harvest> data = new ArrayList<Harvest>();
getJson();
Harvest likesH = new Harvest(Harvest.SOCIAL_LIKES, context, likes);
logger.debug("{}", likesH);
data.add(likesH);
Harvest postsH = new Harvest(Harvest.SOCIAL_POSTS, context, posts);
logger.debug("{}", postsH);
data.add(postsH);
Harvest socialReplies = new Harvest(Harvest.SOCIAL_REPLIES, context, replies);
logger.debug("{}", socialReplies);
data.add(socialReplies);
return data;
} catch(Exception e) {
logger.error("Error Harvesting Social Interactions for context {}", context, e);
throw e;
}
}
private void getJson() throws MalformedURLException, IOException {
likes = replies = posts = 0;
// la seguente stringa deve essere letta dinamicamente
String url = "https://socialnetworking1.d4science.org/social-networking-library-ws/rest/2/posts/get-posts-vre?gcube-token=";
String token = SecurityTokenProvider.instance.get();
JSONObject jsonObject = new JSONObject(Utils.getJson(url + token));
Boolean success = (Boolean) jsonObject.get("success");
if(success == false) {
String message = "getJson() on token: " + token + " success=false";
logger.error(message);
throw new IOException(message);
}
JSONArray res = jsonObject.getJSONArray("result");
int len = res.length();
for(int i = 0; i < len; i++) {
JSONObject item = res.getJSONObject(i);
long time = item.getLong("time");
//System.out.println(from + " - " + time + " - " + to );
if((from <= time) && (time <= to)) {
posts++;
replies += item.getInt("comments_no");
likes += item.getInt("likes_no");
}
}
}
}