I am trying to filter the latest tweets with the words sad, okay, joyful.
When a tweet which has either word inside it, I would like it to print that tweet. But I would also like there to be a delay in the tweets which are printed. So about a 10 second delay between each tweet. For example:
If a tweet comes through : #joker im so sad today
Then I want that to print to the screen, and to the following message
System.out.println("*************************a sad tweet");
Then if a tweet comes through after this: #programmer im joyful
Then 10 seconds after the last tweet I want that tweet to come through with the following message drawn to the screen.
System.out.println("*************************a joyful tweet");
And so on.
Below, I have made some code which allows you to filter the tweets, but im unsure of how to test and print a separate message for each tweet. I tried storing this in an Arraylist and retrieving each tweet with a message, but this doesn't work. Is there a way to do this?
Im using processing 2 and twitter4j 3
Any suggestions? Solutions
void GetTweetsByKeywords()
{
List<String>mood = new ArrayList <String>();
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("XXXX");
cb.setOAuthConsumerSecret("XXX");
cb.setOAuthAccessToken("XXXX");
cb.setOAuthAccessTokenSecret("XXXX");
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
StatusListener statusListener = new StatusListener()
{
private int count = 0;
private long originalTweetId = 0;
#Override
public void onStatus(Status status)
{
System.out.println(status.getUser().getName() + " : " + status.getText());
} //en of the onStatus()
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice)
{
// should really remove deleted tweets here ...
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses)
{
}
public void onScrubGeo(long userId, long upToStatusId) {
// should really remove deleted location information here ...
}
public void onStallWarning(StallWarning stallWarning) {
// should really do something about stalls here ...
}
#Override
public void onException(Exception ex)
{
ex.printStackTrace();
}
}; //end of the listener
String keywords[] = {"sad","okay","joyful"};
for(int i=0; i<keywords.length; i++)
{
FilterQuery fq = new FilterQuery();
fq.track(keywords);
twitterStream.addListener(statusListener);
twitterStream.filter(fq);
mood.add(//here i want to add the filtered tweets);
System.out.println("Heres a filter :" + mood.get(i));
if (mood.get(i).equals("sad"))
{
System.out.println("*********************************************a sad tweet");
}
else if (mood.get(i).equals("joyful"))
{
System.out.println("*********************************************a joyfull tweet");
}
else if(mood.get(i).equals("okay"))
{
System.out.println("*********************************************okay tweet");
}
}
}
The easiest is to use a separate thread and a queue. Do this:
final Queue<Status> queue = new LinkedBlockingQueue<Status>(10000);
new Thread(){
// In your status listener, post tweets to the queue
...
public void onStatus(Status status){
queue.offer(status);
}
...
// Create TwitterStream instance, add query
// and start listening
twitterStream.filter(fq);
}.start();
while(!Thread.currentThread().isInterrupted()){
Status nextTweet = queue.take();
System.out.println("Do stuff with tweet");
}
Related
i am at the moment developing a Softphone with javafx. and i kind of a have problem capturing incoming call to a textfield. an example of my code is here.
an incoming call is with Joptionpane successful bt i had like to have the value appear in call textfield just like telephone.
Thank you.
public void telephoneNumbs(String numbers) {
String replace = numbers.replace("sip:", "").trim().replace(".", ""); // Incoming Call Numbers from Sip UA
if (!replace.isEmpty()) {
List<TelephoneObj> telephons;
telTextField.setText(null); //init it with null
costumDao = new CostumersDao(); // costumers DB
telephons = costumDao.getOrCompareTelfone(numbers);
for (TelephoneObj tmp : telephons) {
System.out.println("Test: " + tmp.getTelephoneNums); // am getting exactle what i need here from my Database
//or
JOptionPane.showMessageDialog(null,"incoming:"+ tmp.getTelephoneNums); // it show it during incoming calls
//here is the problem. it wouldnt show the Value on the Textfield
telTextField.setText(tmp.getTelephoneNums); //try to push that Value(Telephone number) to show in JFXTextfield/it cold be any other Textfields
}
}
Sooo much happy today it went well with after 2days of thinking how to solve this miserable life of not taking time to think.
I finally got the answer by using Task to solve the problem.
Task<Void> task = new Task<Void>() {
{
updateMessage("");
}
#Override
public Void call() throws Exception {
while (true) {
updateMessage(callee);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
break;
}
}
return null;
}
};
//neuLabel.textProperty().bind(task.messageProperty());
kdAddrTel.textProperty().bind(task.messageProperty());
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
I'm trying to use an arraylist of Tweets that has been populated inside a callback but I can't figure out how to return the built list. Whenever I try to use the built list it's empty.
I got some code from this post
public ArrayList<Tweet> tweetList() {
final ArrayList<Tweet> tweets = new ArrayList<>();
final UserTimeline userTimeline = new UserTimeline.Builder()
.screenName("xxxxxxxx")
.build();
userTimeline.next(null, new Callback<TimelineResult<Tweet>>() {
#Override
public void success(Result<TimelineResult<Tweet>> result) {
for(Tweet tweet : result.data.items){
tweets.add(tweet);
}
Log.d("Finished Tweet List", String.valueOf(tweets));
// when this is printed I can see the ArrayList and all tweets are there
}
#Override
public void failure(TwitterException exception) {
exception.printStackTrace();
}
});
Log.d("Tweet list returned", String.valueOf(tweets));
// the value of tweets is empty here for some reason
return tweets;
}
Instead of returning the empty ArrayList of Tweets, you can modify your method so another ArrayList of Tweets is updated when the response from the Callback succeeds.
So I suggest modifying your method as follows:
private ArrayList<Tweet> tweetList = new ArrayList<>();
public void tweetList() {
final ArrayList<Tweet> tweets = new ArrayList<>();
final UserTimeline userTimeline = new UserTimeline.Builder()
.screenName("xxxxxxxx")
.build();
userTimeline.next(null, new Callback<TimelineResult<Tweet>>() {
#Override
public void success(Result<TimelineResult<Tweet>> result) {
for(Tweet tweet : result.data.items){
tweets.add(tweet);
}
this.tweetList = tweets;
// execute the next sequence of instructions in your program here
// and make use of tweetList instead of tweets
}
#Override
public void failure(TwitterException exception) {
exception.printStackTrace();
}
});
}
Of course, the value of tweets is empty here !
The function userTimeline.next(null, new Callback<TimelineResult<Tweet>>() is not executed on the main thread (It is an asynchronous task).
So the return tweets is called before your ArrayList<Tweets> tweets has been filled.
You can only do operations on your list in the
#Override
public void success(Result<TimelineResult<Tweet>> result) {
//do whatever with your list here !
}
Hope I'll have been clear !
Here is my code:
public String addxyz ()
{
String returnStatus = "";
DBConnection conn = new DBConnection();
returnStatus = conn.fun_GetData();
ArrayList<String> emailList = new ArrayList<String>();
emailList.add("xyz#gmail.com");
emailList.add("asd#hotmail.com");
for(String email : emailList)
{
SendEmail sendEmail = new SendEmail();
boolean statusEmail = sendEmail.SendingEmail(email);
}
return returnStatus;
}
I want to know what is the best way to send email to every email address after returning method status.
For example I have 100 email list so the above method is first sending 100 email then return status.
But i want to return something then send email so is that possible?
You have to send emails asynchronously then.
You can very well right a multi threaded program wherein you are sending emails in a different executor thread and main thread returns back with a status without getting blocked on sending the emails.
You can use Java Executors api for this one.
For multi threading you can do like this:
public String addxyz (String qweqw)
{
String returnStatus = "status";
ArrayList<String> emailList = new ArrayList<String>();
emailList.add("xyz#gmail.com");
emailList.add("asd#hotmail.com");
for(String email : emailList)
{
// create a thread
Thread th = new Thread(){
#Override
public void run(){
// Your SendMail logic
SendEmail sendEmail = new SendEmail();
boolean statusEmail = sendEmail.SendingEmail(email);
}
};
th.start(); // start the thread & continue to next email
}
return returnStatus;
}
From the snippet in your question, the status and parameter seem completely useless. So you could do:
// in main execution path
String returnStatus = "status";
new Thread( new Runnable() {
#Override public void run(){ addxyz("dummy"); }
} ).start();
But I really doubt that this will work out. I guess your example misses where and why status could be changed in the function. Then this solution is void!
UPDATE
From the point where your status won't change inside the function, you can wrap the rest in a Thread/Runnable and run it. For example:
....
returnStatus = conn.fun_GetData();
new Thread( new Runnable() { #Override public void run() {
ArrayList<String> emailList = new ArrayList<String>();
emailList.add("xyz#gmail.com");
emailList.add("asd#hotmail.com");
for(String email : emailList)
{
SendEmail sendEmail = new SendEmail();
boolean statusEmail = sendEmail.SendingEmail(email);
}
}}).start();
return returnStatus;
In Java 8 you can also use Lambda:
new Thread( () -> {
// your code here
} ).start();
So, I'm trying to write code for a search JTextField that retrieves results from the web (kinda like Google's fancy search tips). The only problem is... probably my lack of programming experience. More specifically, I have it set up to whenever a user hits a key, it sends out a request with the JTextField input through an HttpURLConnection and retrieves the results then updates. But whenever the HttpURLConnection is running, it freezes the program for a couple seconds while it does its thing, which mainly prohibits entering in more characters into the search field if I didn't mind anything else. I've considered using separate threads, but I'm not sure how I would properly interrupt a thread and have it start over using new data while having everything else wait on it but still accepting new data. I've considered using
thread.stop();
to help manage the issue, but from what I've read, that seems taboo (am I right?). Anyways, here's pretty much what I'm using:
public class SearchField extends JTextField implements KeyListener {
public SearchField() {
addkeyListener(this);
}
public void updateData(ArrayList<String results) {
/*Pass the data off the the GUI*/
{
#Override
public void keyTyped(KeyEvent e) {
SearchQuery query = new SearchQuery(this.getText());
updateData(query.getResults());
}
}
public class SearchQuery {
ArrayList<String> results = new ArrayList<String>();
public SearchQuery(String search) {
String search_path = "http://www.whatever.com/" + search;
URL url = new URL(search_path);
conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("User-Agent", "Mozilla/4.76");
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuffer buf = new StringBuffer();
int i;
while((i = in.read()) != -1) {
buf.append((char) i);
}
String data = buf.toString();
parse(data);
}
public void parse(String data) {
/*Parse a bunch of JSON, return the results in an array*/
results.add(data);
}
public ArrayList<String> getResults() {
return results;
}
}
I'm just at a loss for how to synchronise recieving continuous input while getting new results for each key stroke and dismissing unfinished connections and their respective data processing when it becomes invalid at the next key stroke.
You are doing the download in the same thread that responds to user events. You need to do the download in another thread, perhaps by making SearchQuery extend Thread and doing the query in the run method. When it comes time to update the text field, you can use SwingUtilities.invokeLater to update the text field. Here’s an example:
public class SearchQuery extends Thread {
private SearchField f;
public SearchQuery(JTextField f) {
this.f = f;
}
public void run() {
// do the query here
SwingUtilities.invokeLater(new Runnable() {
public void run() {
f.updateData(results);
}
});
}
}
Then change the line:
SearchQuery query = new SearchQuery(this.getText());
to this:
SearchQuery query = new SearchQuery(this);
My problem is annoying. My server side is generating 12 random numbers (double here).
My Client side received the correct data but nothing is displayed in my Chart. That worked fine with hardcoded data in the store but not with a REST call.
The transfer between my server and my client is that :
[{"key":"key0","value":0.47222548599297787},{"key":"key1","value":0.6009173797369691},{"key":"key2","value":0.13880104282435624},{"key":"key3","value":0.01804674319345545},{"key":"key4","value":0.5547733564202956},{"key":"key5","value":0.8229999661308851},{"key":"key6","value":0.8959346004391032},{"key":"key7","value":0.6848052288628435},{"key":"key8","value":0.10222856671111813},{"key":"key9","value":0.6931371931409103},{"key":"key10","value":0.2994297934549003},{"key":"key11","value":0.47566752196381334}]
Here my simple class used for my test. I am a newbie with GXT 3
public void onModuleLoad() {
final ListStore<JSOModel> store;
final ContentPanel panel = new FramedPanel();
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "/ws/DocumentService/v1/test");
builder.setHeader("Accept", "application/json");
HttpProxy proxy = new HttpProxy(builder);
final Loader<ListLoadConfig, ListLoadResult<JSOModel>> loader = new ListLoader<ListLoadConfig, ListLoadResult<JSOModel>>(proxy, new DataReader<ListLoadResult<JSOModel>, String>() {
#Override
public ListLoadResult<JSOModel> read(Object loadConfig, String data) {
List<JSOModel> jsoModels = new ArrayList<JSOModel>();
JsArray<JSOModel> jsoModelJsArray = JSOModel.arrayFromJson(data);
if(jsoModelJsArray != null) {
for(int i = 0; i < jsoModelJsArray.length(); i++) {
jsoModels.add(jsoModelJsArray.get(i));
}
}
return new ListLoadResultBean<JSOModel>(jsoModels);
}
});
store = new ListStore<JSOModel>(new ModelKeyProvider<JSOModel>() {
#Override
public String getKey(JSOModel item) {
return item.get("key");
}
});
loader.addLoadHandler(new LoadResultListStoreBinding<ListLoadConfig, JSOModel, ListLoadResult<JSOModel>>(store) {
#Override
public void onLoad(LoadEvent<ListLoadConfig, ListLoadResult<JSOModel>> event) {
ListLoadResult<JSOModel> loaded = event.getLoadResult();
if(loaded.getData() == null) {
store.replaceAll(new ArrayList<JSOModel>());
} else {
store.replaceAll(loaded.getData());
}
}
});
Chart<JSOModel> chart = new Chart<JSOModel>();
chart.setStore(store);
chart.setShadowChart(true);
NumericAxis<JSOModel> axis = new NumericAxis<JSOModel>();
axis.setPosition(Chart.Position.LEFT);
axis.addField(new ValueProvider<JSOModel, Number>() {
#Override
public Number getValue(JSOModel JSOModel) {
return JSOModel.getNumber("value");
}
#Override
public void setValue(JSOModel JSOModel, Number number) {
}
#Override
public String getPath() {
return "key";
}
});
axis.setTitleConfig(new TextSprite("Number of hits"));
axis.setWidth(50);
axis.setMinimum(0);
axis.setMaximum(100);
chart.addAxis(axis);
PathSprite odd = new PathSprite();
odd.setOpacity(1);
odd.setFill(new Color("#dff"));
odd.setStroke(new Color("#aaa"));
odd.setStrokeWidth(0.5);
axis.setGridOddConfig(odd);
CategoryAxis<JSOModel, String> horizontalAxis = new CategoryAxis<JSOModel, String>();
horizontalAxis.setPosition(Chart.Position.BOTTOM);
horizontalAxis.setField(new ValueProvider<JSOModel, String>() {
#Override
public String getValue(JSOModel JSOModel) {
return JSOModel.get("key");
}
#Override
public void setValue(JSOModel JSOModel, String s) {
}
#Override
public String getPath() {
return "key";
}
});
horizontalAxis.setTitleConfig(new TextSprite("month of year"));
chart.addAxis(horizontalAxis);
LineSeries<JSOModel> column = new LineSeries<JSOModel>();
column.setYAxisPosition(Chart.Position.LEFT);
column.setStroke(new RGB(148,174,10));
column.setHighlighting(true);
chart.addSeries(column);
axis.addField(column.getYField());
chart.addSeries(column);
chart.setHeight(100);
chart.setWidth(100);
Button b = new Button("ha");
b.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent clickEvent) {
loader.load();
}
});
RootPanel.get().add(b);
panel.setCollapsible(true);
panel.setHeadingText("Column Chart");
panel.setPixelSize(620, 500);
panel.setBodyBorder(true);
VerticalLayoutContainer layout = new VerticalLayoutContainer();
panel.add(layout);
chart.setLayoutData(new VerticalLayoutContainer.VerticalLayoutData(1,1));
layout.add(chart);
chart.setBackground(new Color("#dff"));
RootPanel.get().add(panel);
There are two ways to wire the chart into a store. One is to simply specify that the chart is using a store via setStore, as you have done:
chart.setStore(store);
When you do this, you must also inform the chart when it must redraw everything - you must call:
chart.redrawChart();
This call must be made shortly after the load is completed - consider doing it at the end of onLoad.
Why is this required? In some cases, developers want to make many changes to the store, one at a time, and if the chart automatically updated after each change, that would spawn many slow changes to the data model, and could end up looking strange. In a case like this, you would only call redrawChart() after all changes were complete.
There is another option however - instead of calling setStore, you can call bindStore, and ask the Chart to automatically update whenever any change occurs to the chart:
chart.bindStore(store);
In your case, this is likely the correct answer.