Getting User Tweets into Processing successfully - Twitter4j - twitter

Managed to finally get my own tweets into Processing, using the following code and the twitter4j library. I've now been trying to adapt the code to pull in the tweets of a specific user, without any luck, regardless of the many people online who have posted 'working code'. Could someone steer me right and show me what exactly needs to be altered? Thanks!
import twitter4j.util.*;
import twitter4j.*;
import twitter4j.management.*;
import twitter4j.api.*;
import twitter4j.conf.*;
import twitter4j.json.*;
import twitter4j.auth.*;
import java.util.*;
List<Status>statuses = null;
TwitterFactory twitterFactory;
Twitter twitter;
void setup() {
size(100, 100);
background(0);
connectTwitter();
getTimeline();
}
void draw() {
background(0);
}
// Initial connection
void connectTwitter() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("XXXX");
cb.setOAuthConsumerSecret("XXXX");
cb.setOAuthAccessToken("XXXX");
cb.setOAuthAccessTokenSecret("XXXX");
twitterFactory = new TwitterFactory(cb.build());
twitter = twitterFactory.getInstance();
println("connected");
}
// Get your tweets
void getTimeline() {
try {
statuses = twitter.getUserTimeline();
}
catch(TwitterException e) {
println("Get timeline: " + e + " Status code: " + e.getStatusCode());
}
for (Status status:statuses) {
println(status.getUser().getName() + ": " + status.getText());
}
}
EDIT - Amended code to get User Tweets. Produces no errors or results...
void getUserTimeLine(long stephenfry) {
try {
ResponseList<Status> statuses = twitter.getUserTimeline(stephenfry);
}
catch(TwitterException e) {
println("Get timeline: " + e + " Status code: " + e.getStatusCode());
}
for (Status status : statuses) {
System.out.println(status.getText());
}
}

You just need to add following to your code to retrieve any users timeline-
void getUserTimeLine(long userID/*You can also use screenName*/) {
ResponseList<Status> statuses = twitter.getUserTimeline(userID/*You can also use screenName*/);
for (Status status : statuses) {
System.out.println(status.getText());
}
}

Related

GPS.ane for my app and i keep getting an error Line 55, Column 50 1120: Access of undefined property onClickStop

**trying to use the GPS.ane for my app and I keep getting an error
"Line 55, Column 50 1120: Access of undefined property onClickStop."
this is the line that is giving me the headache I think I am missing something small but i cant find it. The app is as you will think gives out the latitude and longitude of where you are at. thank you for you help **
**package {
import com.myflashlab.air.extensions.gps.Gps;
import com.myflashlab.air.extensions.gps.LocationAccuracy;
import com.myflashlab.air.extensions.gps.Location;
import com.myflashlab.air.extensions.gps.GpsEvent;
import com.myflashlab.air.extensions.nativePermissions.PermissionCheck;
import flash.utils.setTimeout;
import com.myflashlab.air.extensions.dependency.OverrideAir;
import flash.desktop.NativeApplication;
import flash.desktop.SystemIdleMode;
import flash.display.MovieClip;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.StatusEvent;
import flash.events.InvokeEvent;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.TouchEvent;
import flash.filesystem.File;
import flash.text.AntiAliasType;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import flash.ui.Keyboard;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class Main extends MovieClip{
private var _exPermissions:PermissionCheck = new PermissionCheck();
public function Main() {
// constructor code
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
NativeApplication.nativeApplication.addEventListener(Event.ACTIVATE, handleActivate);
NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, handleDeactivate);
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, handleKeys);
stage.scaleMode = StageScaleMode.EXACT_FIT;
stage.align = StageAlign.TOP_LEFT;
startBtn.addEventListener(TouchEvent.TOUCH_TAP, onClickStart);
stopBtn.addEventListener(TouchEvent.TOUCH_TAP, onClickStop);
checkPermissions();
}
private function onInvoke(e:InvokeEvent):void
{
NativeApplication.nativeApplication.removeEventListener(InvokeEvent.INVOKE, onInvoke);
}
private function handleActivate(e:Event):void
{
NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;
}
private function handleDeactivate(e:Event):void
{
NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.NORMAL;
}
private function handleKeys(e:KeyboardEvent):void
{
if(e.keyCode == Keyboard.BACK)
{
e.preventDefault();
NativeApplication.nativeApplication.exit();
}
}
private function checkPermissions():void
{
// first you need to make sure you have access to the Location API
var permissionState:int;
if(_exPermissions.os == PermissionCheck.ANDROID)
{
permissionState = _exPermissions.check(PermissionCheck.SOURCE_LOCATION);
}
else if(_exPermissions.os == PermissionCheck.IOS)
{
permissionState = _exPermissions.check(PermissionCheck.SOURCE_LOCATION_WHEN_IN_USE);
}
if (permissionState == PermissionCheck.PERMISSION_UNKNOWN || permissionState == PermissionCheck.PERMISSION_DENIED)
{
if(_exPermissions.os == PermissionCheck.ANDROID)
{
_exPermissions.request(PermissionCheck.SOURCE_LOCATION, onRequestResult);
}
else if(_exPermissions.os == PermissionCheck.IOS)
{
_exPermissions.request(PermissionCheck.SOURCE_LOCATION_WHEN_IN_USE, onRequestResult);
}
}
else
{
textDisplay.appendText("permissions are already ok, you can use gps features."+ "\n");
init();
}
function onRequestResult($state:int):void
{
if ($state != PermissionCheck.PERMISSION_GRANTED)
{
textDisplay.appendText("You did not allow the app the required permissions!"+ "\n");
}
else
{
textDisplay.appendText("necessary permissions are now granted."+ "\n");
init();
}
}
}
public function onClickStart (evt:TouchEvent):void{
textDisplay.appendText("Location Uptade Started.\n");
// use the start method to get gps information periodically (the gps icon will be shown at your device status bar)
Gps.location.addEventListener(GpsEvent.LOCATION_UPDATE, onLocationUpdate);
Gps.location.start(LocationAccuracy.HIGH, 0, 5000);
startBtn.alpha = 0.5;
stopBtn.alpha = 1;
}
public function onClickstop (evt:TouchEvent):void{
textDisplay.appendText("Location Uptade Stopped.\n");
// simply stop the gps service when you don't need to get location information periodically anymore.
Gps.location.removeEventListener(GpsEvent.LOCATION_UPDATE, onLocationUpdate);
Gps.location.stop();
startBtn.alpha = 1;
stopBtn.alpha = 0.5;
}
function onLocationUpdate(e:GpsEvent):void
{
textDisplay.appendText(" ------------------------------- onLocationUpdate"+ "\n");
var loc:Location = e.param;
textDisplay.appendText("accuracy = " + loc.accuracy+ "\n");
textDisplay.appendText("altitude = " + loc.altitude+ "\n");
textDisplay.appendText("bearing = " + loc.bearing+ "\n");
textDisplay.appendText("latitude = " + loc.latitude+ "\n");
textDisplay.appendText("longitude = " + loc.longitude+ "\n");
textDisplay.appendText("provider = " + loc.provider+ "\n");
textDisplay.appendText("speed = " + loc.speed+ "\n");
textDisplay.appendText("time = " + loc.time+ "\n");
textDisplay.appendText("---------------------------------"+ "\n");
}
private function myDebuggerDelegate($ane:String, $class:String, $msg:String):void
{
textDisplay.appendText($ane+"("+$class+") "+$msg+ "\n");
}
private function init():void
{
// remove this line in production build or pass null as the delegate
OverrideAir.enableDebugger(myDebuggerDelegate);
Gps.init(); // call init only once in your project
// will return null if no known last location has been found
Gps.location.getLastLocation(onLocationResult);
// may take a while depending on when gps info is found
Gps.location.getCurrentLocation(onLocationResult);
function onLocationResult($result:Location):void
{
if (!$result)
{
textDisplay.appendText("location is null"+ "\n");
return;
}
textDisplay.appendText("accuracy = " + $result.accuracy+ "\n");
textDisplay.appendText("altitude = " + $result.altitude+ "\n");
textDisplay.appendText("bearing = " + $result.bearing+ "\n");
textDisplay.appendText("latitude = " + $result.latitude+ "\n");
textDisplay.appendText("longitude = " + $result.longitude+ "\n");
textDisplay.appendText("provider = " + $result.provider+ "\n");
textDisplay.appendText("speed = " + $result.speed+ "\n");
textDisplay.appendText("time = " + $result.time+ "\n");
textDisplay.appendText("---------------------------------"+ "\n");
}
}
}
}
**
stopBtn.addEventListener(TouchEvent.TOUCH_TAP, onClickStop);
public function onClickstop (evt:TouchEvent):void{
Your function has a low case s in stop, but when you refer to it you use a capital S.
Think that's all that's wrong

Get view count using Google Youtube API

I want to get the view count of set of videos. Following is the relevant part of my code.
SearchResult singleVideo = iteratorSearchResults.next();
ResourceId rId = singleVideo.getId();
// Double checks the kind is video.
if (rId.getKind().equals("youtube#video")) {
Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().get("default");
System.out.println(" Video Id" + rId.getVideoId());
System.out.println(" Title: " + singleVideo.getSnippet().getTitle());
System.out.println(" Thumbnail: " + thumbnail.getUrl());
YouTube.Videos.List list = youtube.videos().list("statistics");
list.setId(rId.getVideoId());
list.setKey("youtube.apikey");
Video v = list.execute().getItems().get(0);
System.out.println("The view count is: "+v.getStatistics().getViewCount());
System.out.println("\n-------------------------------------------------------------\n");
}
This gives the following error in the line "YouTube.Videos.Lists list = youtube.videos().list("statistics");".
error: method list in class YouTube.Videos cannot be applied to given types;
If this is a compilation error then there might be some issue with the library version that you have included. I tried sample code from youtube API docs and it worked for me.
I have removed some extra code from the sample to show how view counts can be retrieved for a single video:
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Video;
import com.google.api.services.youtube.model.VideoListResponse;
import java.io.IOException;
import java.math.BigInteger;
public class GeolocationSearch {
public static void main(String[] args) {
try {
YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("APP_ID").build();
String apiKey = "API_KEY";
YouTube.Videos.List listVideosRequest = youtube.videos().list("statistics");
listVideosRequest.setId("lf_wVfwpfp8"); // add list of video IDs here
listVideosRequest.setKey(apiKey);
VideoListResponse listResponse = listVideosRequest.execute();
Video video = listResponse.getItems().get(0);
BigInteger viewCount = video.getStatistics().getViewCount();
System.out.println(" ViewCount: " + viewCount);
System.out.println("\n-------------------------------------------------------------\n");
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
}
}

Jira rest api, add attachment with transition

In jira rest api, we are working with transition api.
By posting on /rest/api/2/issue/{issueIdOrKey}/transitions url with transition id and comments and other fields, we are able to post comments and other fields with state transition.
{
"fields" : {"summary": "Test update 5"},
"transition": { "id": "4"},
"update": {
"comment": [
{
"add": {
"body": "It is time to finish this task"
}
}
]
}
}
Recently we came to know that jira has validation for attachments as well. Means I need to add attachment if I do transition. We are in search of how to add attachment during transition using rest api.
Any help would be really appreciated.
Thanks in advance.
Not sure if it would work during transitions, but here's how to add attachments.
https://docs.atlassian.com/jira/REST/latest/#d2e88
I had to make 2 calls -- first to create the issue and then another POST call to update it with the screenshot as there is no way to add attachments in the create call at all.
I am Not sure about adding attachements with transition(I had never done), but I think can be clubbed. Here is the code to just add an attachment to JIRA, You can use Transition API of JRJC and apply/add some logic in below code to get work done.
Follow link [Listing All JIRA Transitions via API
for updating status based on transition, Hope you may get something from here too.
public void addAttachment(IssueRestClient issueRestClient,
VersionOne versionOne, Issue issue, Epics epic) {
try {
URI attachmentsUri = new URI(
applicationProperties.get(Constants.JIRAURL)
+ "/rest/api/2/issue/" + issue.getKey()
+ "/attachments");
Iterable<Attachment> attachments = issue.getAttachments();
Set<String> existingAttachments = new TreeSet<String>();
String _jiraUser = applicationProperties.get(Constants.JIRAUSER);
String _jiraPwd = applicationProperties.get(Constants.JIRAPWD);
String auth = new String(Base64.encode(_jiraUser + ":" + _jiraPwd));
Set<String> files = new TreeSet<String>();
for (Attachment attachment : attachments) {
for (VAttachements vAttachement : epic
.getAttachement()) {
files.add(vAttachement.getFileName());
}
existingAttachments.add(attachment.getFilename());
}
for (VAttachements vAttachement : epic.getvAttachement()) {
if (!(existingAttachments.contains(vAttachement.getFileName()))) {
Promise<Void> attachmentResult = issueRestClient
.addAttachment(attachmentsUri,
vAttachement.getInputStream(),
vAttachement.getFileName());
attachmentResult.claim();
Constants.REPORT.info(attachmentResult.isDone());
}
}
for (Attachment attachment : attachments) {
for (String checkAttachment : existingAttachments) {
if (!files.contains(checkAttachment))
deleteJiraAttachment(attachment, auth, issue,
checkAttachment);
}
}
} catch (Exception e) {
Constants.ERROR.info(Level.INFO, e);
}
}
-Here Epics is a POJO class which contains attachments to be added in Jira, through getter/ setter method.
private void deleteJiraAttachment(Attachment attachment, String auth,
Issue issue, String jiraFilename) {
URI attachmentURL = attachment.getSelf();
int status;
try {
if (jiraFilename.equalsIgnoreCase(attachment.getFilename())) {
status = invokeDeleteMethod(auth, String.valueOf(attachmentURL));
if (status == 204) {
Constants.REPORT.info("Attachment deleted from Issue"
+ issue.getKey());
} else if (status == 403) {
System.out
.println("attachments for Issue\t "
+ issue.getKey()
+ " is disabled or you don't have permission to remove");
} else if (status == 404) {
Constants.REPORT.info("No attachment is not found for"
+ issue.getKey());
}
}
} catch (AuthenticationException | ClientHandlerException e) {
Constants.ERROR.info(Level.INFO, e);
}
}
private static int invokeDeleteMethod(String auth, String url)
throws AuthenticationException, ClientHandlerException {
Client client = Client.create();
WebResource webResource = client.resource(url);
ClientResponse response = webResource
.header("Authorization", "Basic " + auth)
.type("application/json").accept("application/json")
.delete(ClientResponse.class);
int statusCode = response.getStatus();
if (statusCode == 401) {
throw new AuthenticationException("Invalid Username or Password");
}
return statusCode;

Twitter4j error on processing

Im trying to follow this tutorial:
//Build an ArrayList to hold all of the words that we get from the
imported tweets
ArrayList<String> words = new ArrayList();
void setup() { //Set the size of the stage, and the background to black.
size(550,550);
background(0);
smooth();
//Credentials ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("lPFSpjBppo5u4KI5xEXaQ");
cb.setOAuthConsumerSecret("SYt3e4xxSHUL1gPfM9bxQIq6Jf34Hln9T1q9KGCPs");
cb.setOAuthAccessToken("17049577-Yyo3AEVsqZZopPTr055TFdySop228pKKAZGbJDtnV");
cb.setOAuthAccessTokenSecret("6ZjJBebElMBiOOeyVeh8GFLsROtXXtKktXALxAT0I");
//Make the twitter object and prepare the query
Twitter twitter = new
TwitterFactory(cb.build()).getInstance();
Query query = new Query("#OWS");
query.setRpp(100);
//Try making the query request. try {
QueryResult result = twitter.search(query);
ArrayList tweets = (ArrayList) result.getTweets();
for (int i = 0; i < tweets.size(); i++) {
Tweet t = (Tweet) tweets.get(i);
String user = t.getFromUser();
String msg = t.getText();
Date d = t.getCreatedAt();
println("Tweet by " + user + " at " + d + ": " + msg);
//Break the tweet into words
String[] input = msg.split(" ");
for (int j = 0; j < input.length; j++) {
//Put each word into the words ArrayList
words.add(input[j]);
}
}; } catch (TwitterException te) {
println("Couldn't connect: " + te); }; } void draw() { //Draw a faint black rectangle over what is currently on the stage so
it fades over time. fill(0,1); rect(0,0,width,height);
//Draw a word from the list of words that we've built int i = (frameCount % words.size()); String word = words.get(i);
//Put it somewhere random on the stage, with a random size and colour fill(255,random(50,150)); textSize(random(10,30));
text(word, random(width), random(height)); }
But i get the following error when i run the code in processing. cannot find class or type named tweet
Ive added the twitter4j libraries by dragging and dropping to the processing IDE.
Im using processing 2.1 and twitter4j3.05
Any suggestions?
This is a basic example using twitter4j 3.0.5.
import java.util.*;
List<Status>statuses = null;
TwitterFactory twitterFactory;
Twitter twitter;
void setup() {
size(100, 100);
background(0);
connectTwitter();
getTimeline();
getSearchTweets();
}
void draw() {
background(0);
}
// Initial connection
void connectTwitter() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("xxx");
cb.setOAuthConsumerSecret("xxx");
cb.setOAuthAccessToken("xxx");
cb.setOAuthAccessTokenSecret("xxx");
twitterFactory = new TwitterFactory(cb.build());
twitter = twitterFactory.getInstance();
println("connected");
}
// Get your tweets
void getTimeline() {
try {
statuses = twitter.getHomeTimeline();
}
catch(TwitterException e) {
println("Get timeline: " + e + " Status code: " + e.getStatusCode());
}
for (Status status:statuses) {
println(status.getUser().getName() + ": " + status.getText());
}
}
// Search for tweets
void getSearchTweets() {
try {
Query query = new Query("love");
QueryResult result = twitter.search(query);
for (Status status : result.getTweets()) {
println("#" + status.getUser().getScreenName() + ":" + status.getText());
}
}
catch (TwitterException e) {
println("Search tweets: " + e);
}
}

JS-Interop : Attempting to use salesforce proxy

I'm trying to use Salesforce's sforce library to place an Ajax call to salesforce. Here is the example javascript that is working:
function setupPage() {
var state = { //state that you need when the callback is called
output : document.getElementById("output"),
startTime : new Date().getTime()};
var callback = {
//call layoutResult if the request is successful
onSuccess: layoutResults,
//call queryFailed if the api request fails
onFailure: queryFailed,
source: state};
sforce.connection.query(
"Select Id, Name, Industry From Account order by Industry",
callback);
}
function queryFailed(error, source) {
// not shown function code
}
function layoutResults(queryResult, source) {
// not shown function code
}
Here's my dart implementation:
import 'dart:html';
import 'package:js/js.dart' as js;
import 'dart:json';
void main() {
js.scoped(() {
var sforce = js.context.sforce;
var callbackSuccess = new js.Callback.once(success);
var callbackFailed = new js.Callback.once(failure);
var sfdc = new js.Proxy(sforce.connection.query("Select Id, Name, Industry From Account order by Industry"),
js.map({"onSuccess" : callbackSuccess, "onFailure" : callbackFailed}));
});
}
void success(queryResult) {
print("queryResult is: " + queryResult);
}
void failure(error) {
print("error is: " + error);
}
The Ajax call is being placed, as I see the POST request being made and returning data. However, I always seem to get this error (and I've tried countless different combinations):
Uncaught TypeError: object is not a function (program):370
construct (program):370
ReceivePortSync.dispatchCall darttest:178
$$._JsSendPortSync.callSync$1 minidartjs:4929
$.Proxy_Proxy$withArgList minidartjs:8194
$.Proxy_Proxy minidartjs:8183
$$.main_anon.call$0 minidartjs:6057
$.scoped minidartjs:8136
$.main minidartjs:8066
$$._IsolateContext.eval$1 minidartjs:276
$.startRootIsolate minidartjs:6533
(anonymous function)
Any help would be greatly appreciated, as I'm not sure where to turn at this point.
You get this error because you try to create a js.Proxy (sfdc) with the result of sforce.connection.query(...) . When you use new js.Proxy(f), f must be a js.Proxy of a js function. Here you get an object and that's why you get the error.
Here's the code that should work.
import 'dart:html';
import 'package:js/js.dart' as js;
import 'dart:json';
void main() {
js.scoped(() {
var sforce = js.context.sforce;
var callbackSuccess = new js.Callback.once(success);
var callbackFailed = new js.Callback.once(failure);
sforce.connection.query("Select Id, Name, Industry From Account order by Industry",
js.map({"onSuccess" : callbackSuccess, "onFailure" : callbackFailed}));
});
}
void success(queryResult, source) {
print("queryResult is: " + queryResult);
}
void failure(error, source) {
print("error is: " + error);
}

Resources