Commit d960d385 authored by Dave McCormick's avatar Dave McCormick
Browse files

WIP commit including wiring up to twitter stream, removing old fizz buzz...

WIP commit including wiring up to twitter stream, removing old fizz buzz logic, and adding angular JS front end
parent bfd40f6f
package actors;
import twitter4j.*;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import twitter4j.Trend;
import twitter4j.conf.ConfigurationBuilder;
import java.util.HashMap;
import java.util.Map;
/*
Consumer Key (API Key) MkpBoVPy3REAIdsPNSZpC7u0I
Consumer Secret (API Secret) 3cNybn6qSJPpw2AnizXGitOclFV3ZolFXidWBWLpOnafRw7uL8
Access Token 315679785-SVT1kCKoow1eCTgTWLzPrh6BPaKA5OiPOfIlmAxt
Access Token Secret TYTg0PLDbU7isjXxm3uPIeu2xdYg3rXGaEGUdJuBkvCg2
*/
/**
* A rather trivial Actor that just plays FizzBuzz
*/
......@@ -21,53 +39,137 @@ public class FizzBuzzActor extends UntypedActor {
*/
public static Props props = Props.create(FizzBuzzActor.class);
Twitter twitter;
TwitterStream twitterStream;
StatusListener listener;
public FizzBuzzActor() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("MkpBoVPy3REAIdsPNSZpC7u0I")
.setOAuthConsumerSecret("3cNybn6qSJPpw2AnizXGitOclFV3ZolFXidWBWLpOnafRw7uL8")
.setOAuthAccessToken("315679785-SVT1kCKoow1eCTgTWLzPrh6BPaKA5OiPOfIlmAxt")
.setOAuthAccessTokenSecret("TYTg0PLDbU7isjXxm3uPIeu2xdYg3rXGaEGUdJuBkvCg2");
//TwitterFactory tf = new TwitterFactory(cb.build());
//twitter = tf.getInstance();
twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
listener = new StatusListener() {
@Override
public void onStatus(Status status) {
GeoLocation loc = status.getGeoLocation();
if (loc == null){
return;
}
reply("@" + status.getUser().getScreenName() + "said " + status.getText() + " - " + loc);
}
@Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
@Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
@Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
@Override
public void onStallWarning(StallWarning warning) {
System.out.println("Got stall warning:" + warning);
}
@Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};
}
@Override
public void onReceive(Object message) {
public void onReceive(Object message) throws TwitterException {
if (message.equals("Marshall")) {
/*
* We're given the marshall's ActorRef by a message saying "Marshall". The Marshall will appear
* to be the sender (even though it's actually been sent by Setup)
*/
marshallActor = getSender();
} else if (message instanceof ActorRef) {
// If we're sent an ActorRef, that's the marshall telling us who our opponent is and to get started
((ActorRef) message).tell(1, getSelf());
marshallActor.tell(1, getSelf());
} else if (message instanceof Integer) {
nextNum = (Integer) message + 1;
reply();
} else {
nextNum = nextNum + 2;
// Stop at 1000 so we don't blow the heap by writing forever into a StringBuilder
if (nextNum < 1000) {
reply();
} else if (message.equals("GetTrends")) {
//getTrendByLocation();
// Put this Actor to sleep for 250ms before it checks its next message
try {
Thread.sleep(300000);
} catch (InterruptedException ex) {
// do nothing
}
marshallActor.tell("ActorReadyAgain",getSelf());
} else if (message.equals("Heatmap")){
reply("Got initial message");
getStreamForHeatmap();
}
}
void reply() {
if (nextNum % 15 == 0) {
getSender().tell("fizzbuzz", getSelf());
marshallActor.tell("fizzbuzz", getSelf());
} else if (nextNum % 5 == 0) {
getSender().tell("buzz", getSelf());
marshallActor.tell("buzz", getSelf());
} else if (nextNum % 3 == 0) {
getSender().tell("fizz", getSelf());
marshallActor.tell("fizz", getSelf());
} else {
getSender().tell(nextNum, getSelf());
marshallActor.tell(nextNum, getSelf());
}
// int secondsUntilRequestAllowed(){
//
// try {
// RateLimitStatus status = twitter.getRateLimitStatus().get("/trends/place");
//
// return status.getSecondsUntilReset();
// } catch (TwitterException e) {
// e.printStackTrace();
// }
//
// // Twitter queries get reset after 15m, if we cant figure out how long left, default to that to be safe.
// return 900;
// }
//
// void getTrendByLocation(){
// Map<String, Boolean> seenLocations = new HashMap<>();
// ResponseList<Location> locations;
// try {
//
// Trends trends = twitter.getPlaceTrends(1);
// for (int i = 0; i < trends.getTrends().length; i++) {
// reply("Trend: " + trends.getTrends()[i].getName());
// }
//
// } catch (TwitterException e) {
// e.printStackTrace();
// }
//
// }
void reply(String trendName) {
marshallActor.tell(trendName, getSelf());
// Put this Actor to sleep for 250ms before it checks its next message
try {
Thread.sleep(250);
Thread.sleep(10);
} catch (InterruptedException ex) {
// do nothing
}
}
void getStreamForHeatmap(){
reply("Starting streaming...");
FilterQuery fq = new FilterQuery();
double[][] boundingBox= {{112.467,-55.050}, {168.000,-9.133}}; /// whole world;
FilterQuery filtro = new FilterQuery();
filtro.locations(boundingBox);
twitterStream.addListener(listener);
twitterStream.filter(filtro);
}
}
......@@ -24,9 +24,12 @@ public class MarshallActor extends UntypedActor {
public void onReceive(Object message) {
if (message.equals("Report!")) {
getSender().tell(messages.toString(), getSelf());
}
else if (message.equals("ActorReadyAgain"))
{
getSender().tell("Heatmap",getSelf());
} else {
messages.append(getSender().toString());
messages.append(" said ");
messages.append(message);
messages.append("\n");
}
......
......@@ -24,12 +24,10 @@ public class Setup {
public Setup(ActorSystem system) {
marshallActor = system.actorOf(MarshallActor.props);
ActorRef fb1 = system.actorOf(FizzBuzzActor.props, "Player1");
ActorRef fb2 = system.actorOf(FizzBuzzActor.props, "Player2");
fb1.tell("Marshall", marshallActor);
fb2.tell("Marshall", marshallActor);
//ActorRef fb1 = system.actorOf(FizzBuzzActor.props, "Player1");
//fb1.tell("Marshall", marshallActor);
fb1.tell(fb2, fb2);
//fb1.tell("Heatmap", marshallActor);
}
......
......@@ -36,8 +36,13 @@ public class Application extends Controller {
* But Future is a Scala class, so FutureConverters.toJava converts it into a CompletionStage, which is Java's equivalent.
* thenApply is a method on CompletionStage that means "when you get the result, do this with it, and return a new CompletionStage"
*/
return FutureConverters.toJava(ask(actorSetup.marshallActor, "Report!", 1000))
.thenApply(response -> ok(response.toString()));
.thenApply(response -> {
String responseString = response.toString();
return ok(views.html.application.index.render(responseString));
});
}
/**
......@@ -45,6 +50,6 @@ public class Application extends Controller {
* response
*/
public CompletionStage<Result> whatDidGitLabSay() {
return wsClient.url("http://www.une.edu.au/foo").get().thenApply(r -> ok(r.getStatusText()));
return wsClient.url("http://www.une.edu.au").get().thenApply(r -> ok(r.getStatusText()));
}
}
@(indexes:Array[Int])
@(string:String)
<!DOCTYPE html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=yes" />
<!--<script src="https://maps.google.com/maps/api/js?libraries=placeses,visualization,drawing,geometry,places"></script>-->
<!--<script src="https://code.angularjs.org/1.3.15/angular.js"></script>-->
<!--<script src="/assets/javascript/ng-map.js"></script>-->
<!--<script src="/assets/javascript/taxi-data.js"></script>-->
<script src="//maps.googleapis.com/maps/api/js?sensor=false&libraries=placeses,visualization,drawing,geometry,places"></script>
<html>
<head lang="en">
<meta name="referrer" content="no-referrer">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="//rawgit.com/angular-ui/angular-google-maps/2.1.5/dist/angular-google-maps.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js"></script>
<script>
angular.module("myApp", ['uiGmapgoogle-maps'])
.controller("Example", function($scope, $interval) {
function MockHeatLayer(heatLayer) {
// Adding 500 Data Points
var map, pointarray, heatmap;
var taxiData = [
new google.maps.LatLng(37.782551, -122.445368),
new google.maps.LatLng(37.782745, -122.444586),
new google.maps.LatLng(37.782842, -122.443688),
new google.maps.LatLng(37.782919, -122.442815),
new google.maps.LatLng(37.782992, -122.442112),
new google.maps.LatLng(37.783100, -122.441461),
new google.maps.LatLng(37.783206, -122.440829),
new google.maps.LatLng(37.783273, -122.440324),
new google.maps.LatLng(37.783316, -122.440023),
new google.maps.LatLng(37.783357, -122.439794),
new google.maps.LatLng(37.783371, -122.439687)
];
var pointArray = new google.maps.MVCArray(taxiData);
heatLayer.setData(pointArray);
};
$scope.map = {
center: {
latitude: 37.782551,
longitude: -122.445368
},
zoom: 12,
heatLayerCallback: function (layer) {
//set the heat layers backend data
var mockHeatLayer = new MockHeatLayer(layer);
},
showHeat: true
};
});
<h1>Tick all the beagles:</h1>
(function() {
'use strict';
var heatmapService = function() {
var dataPoints = [];
<form action="matches" method="POST">
@for(idx <- indexes) {
<div>
<input name="sent" value="@idx" type="hidden" />
<input name="beagle" value="@idx" type="checkbox" />
<img src="@model.Captcha.getPhoto(idx)" style="max-width: 400px; max-height: 200px;" />
</div>
}
this.addPoint = function(lat, lon, proximity) {
var weight = this.weight(proximity);
var newPoint = {
location: new google.maps.LatLng(lat, lon),
weight: weight
};
dataPoints.push(newPoint);
return newPoint;
};
<!--
TODO: For each index in the array, show a checkbox with the value of the index, and the relevant img
-->
<button type="submit">Submit</button>
</form>
this.getPoints = function() {
return dataPoints;
};
this.weight = function(proximity) {
// Weight is normalized by max distance
var maxDistance = 500; // meters
// Cap distance to maxDistance
if (distance > maxDistance) {
distance = maxDistaance;
}
var weight = (maxDistance - distance) / maxDistance;
return weight;
};
};
angular.module('myApp').service('heatmapService', [
heatmapService
]);
})();
</script>
</head>
<body>
<style>
.angular-google-map-container { height: 400px; }
</style>
<div ng-app="myApp" ng-controller="Example">
<ui-gmap-google-map center='map.center' zoom='map.zoom'>
<ui-gmap-layer namespace="visualization" type="HeatmapLayer" show="map.showHeat" onCreated="map.heatLayerCallback"></ui-gmap-layer>
</ui-gmap-google-map>
</div>
</body>
</html>
\ No newline at end of file
</html>
......@@ -10,6 +10,8 @@ routesGenerator := InjectedRoutesGenerator
libraryDependencies ++= Seq(
javaWs,
"org.mindrot" % "jbcrypt" % "0.3m"
"org.mindrot" % "jbcrypt" % "0.3m",
"org.twitter4j" % "twitter4j-core" % "4.0.4",
"org.twitter4j" % "twitter4j-stream" % "4.0.4"
)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment