Twitter4j error on processing - twitter

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);
}
}

Related

Refresh tweets frequently in my site homepage without reaching to the rate limit

I am working on the site which needs real time tweets to be displayed to users. I have used Tweet Sharp library to fetch tweets.
My site needs tweets to be refreshed frequently, but sometimes I get {"The remote server returned an error: (429) Too Many Requests."} error.
As my site needs real time information, I have to fetch tweets frequently. How can I achieve this? How to get newest tweets without hitting to the Rate Limits?
TwitterService service=new TwitterService(AppSetting.objTwitterClientInfo.ConsumerKey, AppSetting.objTwitterClientInfo.ConsumerSecret, AppSetting.objTwitterModerateInfo.ModerateAccessToken, AppSetting.objTwitterModerateInfo.ModerateAccessTokenSecret);
var options = new ListTweetsOnHomeTimelineOptions();
options.ExcludeReplies = false;
options.Count = intTotalRec;
var lstTwitterStatus = service.ListTweetsOnHomeTimeline(options);
You can use the streaming api like this:-
public void Can_stream_from_user_stream() {
const int maxStreamEvents = 5;
var block = new AutoResetEvent(false);
var count = 0;
service.StreamUser((streamEvent, response) =>
{
if (streamEvent is TwitterUserStreamEnd)
{
block.Set();
}
if (response.StatusCode == 0)
{
if (streamEvent is TwitterUserStreamFriends)
{
var friends = (TwitterUserStreamFriends)streamEvent;
Assert.IsNotNull(friends);
Assert.IsNotNull(friends.RawSource);
Assert.IsTrue(friends.Ids.Any());
}
if (streamEvent is TwitterUserStreamEvent)
{
var #event = (TwitterUserStreamEvent)streamEvent;
Assert.IsNotNull(#event);
Assert.IsNotNull(#event.TargetObject);
Assert.IsNotNull(#event.RawSource);
Console.Write(#event.Event + "\n" + #event.Source + "\n" + #event.Target);
}
if (streamEvent is TwitterUserStreamStatus)
{
var tweet = ((TwitterUserStreamStatus)streamEvent).Status;
Assert.IsNotNull(tweet);
Assert.IsNotNull(tweet.Id);
Assert.IsNotNull(tweet.User);
Assert.IsNotNull(tweet.RawSource);
Assert.IsNotNull(tweet.User.ScreenName);
Console.WriteLine(tweet.User.ScreenName + "\n" + tweet.Text);
}
if (streamEvent is TwitterUserStreamDirectMessage)
{
var dm = ((TwitterUserStreamDirectMessage)streamEvent).DirectMessage;
Assert.IsNotNull(dm);
Assert.IsNotNull(dm.Id);
Assert.IsNotNull(dm.Sender);
Assert.IsNotNull(dm.Recipient);
Assert.IsNotNull(dm.RawSource);
Console.WriteLine(dm.SenderScreenName + "\n" + dm.RecipientScreenName + "\n" + dm.Text);
}
if (streamEvent is TwitterUserStreamDeleteStatus)
{
var deleted = (TwitterUserStreamDeleteStatus)streamEvent;
Assert.IsNotNull(deleted);
Assert.IsTrue(deleted.StatusId > 0);
Assert.IsTrue(deleted.UserId > 0);
}
if (streamEvent is TwitterUserStreamDeleteDirectMessage)
{
var deleted = (TwitterUserStreamDeleteDirectMessage)streamEvent;
Assert.IsNotNull(deleted);
Assert.IsTrue(deleted.DirectMessageId > 0);
Assert.IsTrue(deleted.UserId > 0);
}
count++;
if (count == maxStreamEvents)
{
block.Set();
}
}
else
{
Assert.Ignore("Stream responsed with status code: {0}", response.StatusCode);
}
});
block.WaitOne();
service.CancelStreaming();
}

BlackBerry java.io.IOException: null

I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate

duplicate SSID in scanning wifi result

i'm trying to make an app that can create a list of available wifi access point. here's part of the code i used:
x = new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
if (results != null) {
for (int i=0; i<size; i++){
ScanResult scanresult = wifi.getScanResults().get(i);
String ssid = scanresult.SSID;
int rssi = scanresult.level;
String rssiString = String.valueOf(rssi);
textStatus.append(ssid + "," + rssiString);
textStatus.append("\n");
}
unregisterReceiver(x); //stops the continuous scan
textState.setText("Scanning complete!");
} else {
unregisterReceiver(x);
textState.setText("Nothing is found. Please make sure you are under any wifi coverage");
}
}
};
both textStatus and textState is a TextView.
i can get this to work but sometimes the result shows duplicate SSID but with different signal level, in a single scan. there might be 3-4 same SSIDs but with different signal level.
is it really different SSIDs and what differs them? can anyone explain?
Are you having several router modems for the same network? For example: A company has a big wireless network with multiple router modems installed in several places so every room has Wifi. If you do that scan you will get a lot of results with the same SSIDs but with different acces points, and thus different signal level.
EDIT:
According to Walt's comment you can also have multiple results despite having only one access point if your modem is dual-band.
use below code to to remove duplicate ssids with highest signal strength
public void onReceive(Context c, Intent intent) {
ArrayList<ScanResult> mItems = new ArrayList<>();
List<ScanResult> results = wifiManager.getScanResults();
wifiListAdapter = new WifiListAdapter(ConnectToInternetActivity.this, mItems);
lv.setAdapter(wifiListAdapter);
int size = results.size();
HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
try {
for (int i = 0; i < size; i++) {
ScanResult result = results.get(i);
if (!result.SSID.isEmpty()) {
String key = result.SSID + " "
+ result.capabilities;
if (!signalStrength.containsKey(key)) {
signalStrength.put(key, i);
mItems.add(result);
wifiListAdapter.notifyDataSetChanged();
} else {
int position = signalStrength.get(key);
ScanResult updateItem = mItems.get(position);
if (calculateSignalStength(wifiManager, updateItem.level) >
calculateSignalStength(wifiManager, result.level)) {
mItems.set(position, updateItem);
wifiListAdapter.notifyDataSetChanged();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is my simple Solution please and it is work for me
private void scanWifiListNew() {
wifiManager.startScan();
List<ScanResult> wifiList = wifiManager.getScanResults();
mWiFiList = new ArrayList<>();
for(ScanResult result: wifiList){
checkItemExists(mWiFiList, result);
}
setAdapter(mWiFiList);
}
private void printList(List<ScanResult> list){
for(ScanResult result: list){
int level = WifiManager.calculateSignalLevel(result.level, 100);
System.out.println(result.SSID + " Level is " + level + " out of 100");
}
}
private void checkItemExists(List<ScanResult> newWiFiList, ScanResult resultNew){
int indexToRemove = -1;
if(newWiFiList.size() > 0) {
for (int i = 0; i < newWiFiList.size(); i++) {
ScanResult resultCurrent = newWiFiList.get(i);
if (resultCurrent.SSID.equals(resultNew.SSID)) {
int levelCurrent = WifiManager.calculateSignalLevel(resultCurrent.level, 100);
int levelNew = WifiManager.calculateSignalLevel(resultNew.level, 100);
if (levelNew > levelCurrent) {
indexToRemove = i;
break;
}else indexToRemove = -2;
}
}
if(indexToRemove > -1){
newWiFiList.remove(indexToRemove);
newWiFiList.add(indexToRemove,resultNew);
}else if(indexToRemove == -1)newWiFiList.add(resultNew);
} else newWiFiList.add(resultNew);
}
private void setAdapter(List<ScanResult> list) {
listAdapter = new WifiListAdapter(getActivity().getApplicationContext(), list);
wifiListView.setAdapter(listAdapter);
}

Parse IMAP message and extract header information

I am trying to extract header and body information from email, the following code retrieves the header and body in their raw form. I have an email object that contains the fields from, subject, date, and body. I would like to extract these values from the email and assign them to the email object. How do I get around it? I have tried several ways like getting the header info and using a streamReader.ReadLine() to get a line but I got illegal path exceptions. I know I can use a library but I need to achieve it this way.
What I mean is this, IMAP command returns header information. And I want to extract subject value, date value, sender e-amil, etc. and assign them to my email objects corresponding values like
emailObject.subject = "subjectValue"
public class Imap
{
static void Main(string[] args)
{
try
{
path = Environment.CurrentDirectory + "\\emailresponse.txt";
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
sw = new System.IO.StreamWriter(System.IO.File.Create(path));
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
ssl = new System.Net.Security.SslStream(tcpc.GetStream());
ssl.AuthenticateAsClient("imap.gmail.com");
receiveResponse("");
Console.WriteLine("username : ");
username = Console.ReadLine();
Console.WriteLine("password : ");
password = Console.ReadLine();
receiveResponse("$ LOGIN " + username + " " + password + " \r\n");
Console.Clear();
receiveResponse("$ LIST " + "\"\"" + " \"*\"" + "\r\n");
receiveResponse("$ SELECT INBOX\r\n");
receiveResponse("$ STATUS INBOX (MESSAGES)\r\n");
Console.WriteLine("enter the email number to fetch :");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("*************Header************");
Console.WriteLine("");
// receiveResponse("$ FETCH " + number + " body[header]\r\n");
// BODY.PEEK[HEADER.FIELDS (SUBJECT)]
// StringBuilder sb = receiveResponse("$ FETCH " + number + " BODY.PEEK[HEADER.FIELDS (From Subject Date)]\r\n");
StringBuilder sb= receiveResponse("$ FETCH " + number + " body.peek[header]\r\n");
Console.WriteLine(sb);
Console.WriteLine("");
Console.WriteLine("Body");
sb = new StringBuilder();
sb=receiveResponse("$ FETCH " + number + " body[text]\r\n");
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] serverbuff = new Byte[1024];
int count = 0;
string retval = enc.GetString(serverbuff, 0, count);
Console.WriteLine(sb.ToString());
receiveResponse("$ LOGOUT\r\n");
}
catch (Exception ex)
{
Console.WriteLine("error: " + ex.Message);
}
finally
{
if (sw != null)
{
sw.Close();
sw.Dispose();
}
if (ssl != null)
{
ssl.Close();
ssl.Dispose();
}
if (tcpc != null)
{
tcpc.Close();
}
}
Console.ReadKey();
}
static StringBuilder receiveResponse(string command)
{
sb = new StringBuilder();
try
{
if (command != "")
{
if (tcpc.Connected)
{
dummy = Encoding.ASCII.GetBytes(command);
ssl.Write(dummy, 0, dummy.Length);
}
else
{
throw new ApplicationException("TCP CONNECTION DISCONNECTED");
}
}
ssl.Flush();
buffer = new byte[2048];
bytes = ssl.Read(buffer, 0, 2048);
sb.Append(Encoding.ASCII.GetString(buffer));
// Console.WriteLine(sb.ToString());
sw.WriteLine(sb.ToString());
// sb = new StringBuilder();
return sb;
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
You said you do not want to use an IMAP library. This means that you will have to implement your own. You should start by reading RFC 3501 because there is no chance you could get the protocol right without reading the docs carefuly. In particular, you're issuing a STATUS command on the currently selected mailbox, which is explicitly forbidden by the protocol specification. The rest of the code supports the assumption that you have not read the RFC yet.

Display HTTP Request Information - BlackBerry

How can I get the all HTTP request headers, method, the suffix of the connection, and all parameters that I added to the request?
Try something like this (I ran this code on a background thread, which I why I use UiApplication.invokeLater() to display results):
try {
ConnectionFactory factory = new ConnectionFactory(); // for OS 5.0+
factory.setPreferredTransportTypes(new int[] {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_TCP_CELLULAR
});
// For OS < 5.0
//HttpConnection conn = (HttpConnection) Connector.open("http://www.google.com;interface=wifi");
HttpConnection conn = (HttpConnection) factory.getConnection("http://www.google.com").getConnection();
conn.setRequestProperty("sessionId", "ABCDEF0123456789");
final StringBuffer results = new StringBuffer();
String key = "";
int index = 0;
// loop over all the header fields, and record their values
while (key != null) {
key = conn.getHeaderFieldKey(index);
if (key != null) {
String value = conn.getHeaderField(key);
results.append(key + " = " + value + "\n\n");
}
index++;
}
results.append("method = " + conn.getRequestMethod() + "\n\n");
// we (should) know which request properties we've set, so we ask
// for them by name here
String sessionId = conn.getRequestProperty("sessionId");
results.append("sessionId = " + sessionId + "\n\n");
String url = conn.getURL();
results.append("URL = " + url);
// show the result on screen (UI thread)
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
textField.setText(results.toString());
}
});
} catch (IOException e) {
e.printStackTrace();
}

Resources