summaryrefslogtreecommitdiff
path: root/src/Chapter4/util/TweetFileToGraph.java
blob: 6cf2e3a882392b65fa00587f58971c9fe8a445f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package Chapter4.util;

import java.io.File;

import GraphElements.RetweetEdge;
import GraphElements.UserNode;

import edu.uci.ics.jung.graph.DirectedGraph;
import edu.uci.ics.jung.graph.DirectedSparseGraph;
import edu.uci.ics.jung.graph.util.EdgeType;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *	Some basic functionality to convert files collected 
 *	in Chapter 2 to JUNG graphs.
 */
public class TweetFileToGraph {
	
	public static DirectedGraph<UserNode, RetweetEdge> getRetweetNetwork(File tweetFile){
		
		JSONObject tmp;
		
		TweetFileProcessor tfp = new TweetFileProcessor(tweetFile);
		DirectedSparseGraph<UserNode, RetweetEdge> dsg = new DirectedSparseGraph<UserNode, RetweetEdge>();
		
		while (tfp.hasNext()){
			tmp = tfp.next();
                        if(tmp==null)
                        {
                            continue;
                        }
			//get the author
			String user=null;
                        try {
                            user = tmp.getJSONObject("user").getString("screen_name");
                        } catch (JSONException ex) {
                            Logger.getLogger(TweetFileToGraph.class.getName()).log(Level.SEVERE, null, ex);
                        }
			if(user==null)
                        {
                            continue;
                        }
			//get the retweeted user
			try{
				JSONObject retweet = tmp.getJSONObject("retweeted_status");
				String retweeted_user = retweet.getJSONObject("user").getString("screen_name");
				
				//make an edge or increment the weight if it exists.
				UserNode toUser = new UserNode(retweeted_user);
				UserNode fromUser = new UserNode(user);
				
				dsg.addVertex(toUser);
				dsg.addVertex(fromUser);
			
				RetweetEdge edge = new RetweetEdge(toUser, fromUser); 
				
				if(dsg.containsEdge(edge)){
					dsg.findEdge(fromUser, toUser).incrementRTCount();
				}
				else{
					dsg.addEdge(edge, fromUser, toUser);
				}
				dsg.addEdge(edge, fromUser, toUser, EdgeType.DIRECTED);
			}
			catch(JSONException ex){
				//the tweet is not a retweet. this is not a problem.
			}
			
			
		}
		
		return dsg;
	}
}