Difference between revisions of "Twitter and Java"

From CompSciWiki
Jump to: navigation, search
(Step 2: Download jar Files)
 
(15 intermediate revisions by 2 users not shown)
Line 2: Line 2:
  
 
In this lab, we'll learn how to use a simple API wrapper for twitter to write Java programs to play with [http://www.twitter.com twitter].
 
In this lab, we'll learn how to use a simple API wrapper for twitter to write Java programs to play with [http://www.twitter.com twitter].
 +
  
 
==Step 0: Register for Twitter==
 
==Step 0: Register for Twitter==
Line 7: Line 8:
 
If you don't have a twitter account, you can sign up easily [https://twitter.com/signup here].  You can always delete this account later.  
 
If you don't have a twitter account, you can sign up easily [https://twitter.com/signup here].  You can always delete this account later.  
  
==Step 1: Download jTwitter==
+
==Step 1: Ensure you are running the latest version of JDK==
 +
 
 +
Before running your lab, make sure you are running JDK 1.6.0 or later. Some of the libraries we will need use things only available in 1.6.  Use the links on the main COMP 1010 website to get the latest JDK. If you are using a mac, then double check the version you are using. You will not be able to install JDK 1.6 on 32-bit macs(i.e., old intel macs).
 +
 
 +
==Step 2: Download jar Files==
 +
 
 +
For this code, we will need three jar files:
 +
*the jtwitter.jar file, [http://www.winterwell.com/software/jtwitter/jtwitter.jar available here].
 +
*the signpost.jar file, [http://code.google.com/p/oauth-signpost/downloads/detail?name=signpost-core-1.2.1.1.jar which is here].
 +
*the commons-codec-1.7.jar file, [http://apache.mirror.nexicom.net//commons/codec/binaries/commons-codec-1.7-bin.zip available as part of this package].
  
jTwitter is the jar file we will use to add twitter capability. You can download the file [http://www.cs.umanitoba.ca/~mdomarat/1010/jtwitter.jar here].  In this lab, we'll be using an old version of jTwitter to write our programs. A newer version of jTwitter is available on the [http://www.winterwell.com/software/jtwitter.php jtwitter homepage], but it requires more complex authorization than what we've got time for here. If you were building a serious application using jTwitter, you would want to use the most recent version.
+
Save all three of these files on your hard drive.
  
==Step 2: Make jTwitter accessible to your code==
+
==Step 3: Make jTwitter accessible to your code==
  
In eclipse, make the jar file accessible to your code:
+
In '''eclipse''', make the jar file accessible to your code:
 
# create a new Java project (File -> New -> Java Project).
 
# create a new Java project (File -> New -> Java Project).
 
# select the project, then click on Project-> Properties).
 
# select the project, then click on Project-> Properties).
Line 20: Line 30:
 
# select the jtwitter.jar file you downloaded.
 
# select the jtwitter.jar file you downloaded.
  
After this, the jtwitter.jar and all its contents should be accessible to your code.  
+
Repeat this process for all three jar files you downloaded. After this, the jtwitter.jar and all its contents should be accessible to your code.  
  
If you are not using eclipse, then you need to extract the jar file in the directory you want to work in. In Windows, do the following:
+
In '''netbeans''', use the following steps:
 +
# Make your project as usual (File > New Project >Java Application >Next> Fill in Program name >Finish)
 +
# Click File > Project Properties ("YourProgramName") If it doesn't say the right name, right-click on the coffee cup icon under the Projects from on the left-hand side and click "Set as Main Project"
 +
# Go to Libraries (on the left)
 +
# Click "Add JAR/Folder" and select the three .jar files (you can select them all at once) jtwitter.jar, signpost-core-1.2.1.1.jar commons-codec-1.3.jar
 +
# Click OK and you now have access to the API
 +
 
 +
In other IDEs, a similar technique to add JAR files should be available
 +
 
 +
If you are using textpad, then you need to extract the jar file in the directory you want to work in. In Windows, do the following:
  
 
# go to the directory you want to write you program in, and move the jTwitter.jar file to that directory.
 
# go to the directory you want to write you program in, and move the jTwitter.jar file to that directory.
Line 31: Line 50:
 
After this, the directory <tt>winterwell</tt> should have been created. In other operating systems (mac OS, linux), the same instructions work, and your OS should properly know where the <tt>jar</tt> command is.  
 
After this, the directory <tt>winterwell</tt> should have been created. In other operating systems (mac OS, linux), the same instructions work, and your OS should properly know where the <tt>jar</tt> command is.  
  
==Step 3: Start coding==
+
==Step 4: Start coding==
  
 
In order to access the jTwitter methods, add the following import line with the rest of your imports:
 
In order to access the jTwitter methods, add the following import line with the rest of your imports:
Line 39: Line 58:
 
</pre>
 
</pre>
  
We can now start by writing a simple program to use jTwitter:
+
The hardest part of using jTwitter is the OAuth Key/Secret that you need to provide the application for authorization.  We've registered a COMP 1010 app and have the key and secret. They will be provided for you at your lab (in a real application, you would register your own app
 
+
 
<pre>
 
<pre>
 
import winterwell.jtwitter.*;
 
import winterwell.jtwitter.*;
 +
import javax.swing.*;
  
 
public class tryjTwitter {
 
public class tryjTwitter {
 +
 
 
   public static void main (String[] args) {
 
   public static void main (String[] args) {
     Twitter myTwitter = new Twitter("yourUserName","yourPassword");
+
    final String oaKey = "will be given at lab";
    myTwitter.setStatus("hello twitter world.");
+
    final String oaSecret = "will be given at lab";
 +
    String pin;
 +
      
 +
    // all the authorization material.
 +
    OAuthSignpostClient client = new OAuthSignpostClient(oaKey,oaSecret,"oob");
 +
    Twitter tw = new Twitter("yourTwitterUserName",client);
 +
    client.authorizeDesktop();
 +
    pin = JOptionPane.showInputDialog("Please enter the pin here:");
 +
    client.setAuthorizationCode(pin);
 +
 
 +
    // the part that we actually care about:
 +
    tw.setStatus("hello twitter world.");
 
   }
 
   }
 
}
 
}
 
</pre>
 
</pre>
  
In this example, the string <tt>"yourUserName"</tt> is your actual user name that you use to log in to twitter, and <tt>"yourPassword"</tt> is your (plain-text!) password. So your code will actually contain your password! If you don't want your friend to see your password, don't let them see your code. They will abuse it if they find it. Trust me.  We will solve this problem in Step 6.
+
In this example, the string <tt>"yourTwitterUserName"</tt> is your actual user name that you use to log in to twitter (as a String, so put it in quotes). You don't have any place in the code to enter your password: this is all handled by twitter during the <tt>authorizeDesktop</tt> method call.
  
==Step 4: Don't wreck it for everyone==
+
This method is a little clunky, but it should work: the <tt>authorizeDesktop</tt> method should launch your browser, and then it will provide you with a pin number, which you paste in your JOptionPane input dialog box.
 +
After this program finishes, "hello twitter world." should be your status. 
 +
 
 +
==Step 5: Add user interaction==
 +
 
 +
To make your code more robust, you could ask the user to input (using JOptionPane, for instance):
 +
# their username (to replace the hardcoded <tt>"yourTwitterUserName"</tt>).
 +
# their tweet.
 +
 
 +
So for instance, instead of the line:
 +
<pre>
 +
    tw.setStatus("hello twitter world.");
 +
</pre>
 +
 
 +
You could write
 +
 
 +
<pre>
 +
String userTweet;
 +
userTweet = JOptionPane.showInputDialog("Enter your tweet");
 +
 
 +
// if the user hit cancel, then the userInput will be null.
 +
if (userTweet != null) {
 +
  tw.setStatus(userTweet);
 +
} else {
 +
  System.out.println("You hit cancel.");
 +
}
 +
</pre>
 +
 
 +
==Step 6: Don't wreck it for everyone==
  
 
The previous program (hopefully) works: it posts the string "hello twitter world" to your twitter account as a tweet.  So please, please, don't abuse this. Do not write code like  
 
The previous program (hopefully) works: it posts the string "hello twitter world" to your twitter account as a tweet.  So please, please, don't abuse this. Do not write code like  
Line 64: Line 123:
 
</pre>
 
</pre>
  
That might well get you 1000 tweets on your account.  But it might also get your account suspended and possibly wreck things for everyone. So please don't automate large volumes of tweets.
+
That might well get you 1000 tweets on your account.  But it might also get your account suspended. It might also get our application key (the long string provided to you) suspended, and wreck things for everyone. So please don't automate large volumes of tweets.
  
  
==Step 5: Other routines in jTwitter==
+
==Step 7: Other routines in jTwitter==
  
 
Setting your status is not the only thing you can accomplish with jTwitter. Other methods of the class <tt>Twitter</tt> that you may find useful are:
 
Setting your status is not the only thing you can accomplish with jTwitter. Other methods of the class <tt>Twitter</tt> that you may find useful are:
Line 86: Line 145:
 
}
 
}
 
</pre>
 
</pre>
 
+
Notice that this requires casting the result of the method call to an <tt>ArrayList</tt> if you want the result to be stored in a variable of that type.
==Step 6: Password safety in Java==
+
* Searching is similar. Use the method <tt>public java.util.List<Twitter.User> search (String searchTerm)</tt> which returns the latest tweets matching your search term. They are returned as a list. Example (uses Java 5 for loops):
 
+
Up to now, you've had to have your password displayed as plain text in your source code which means
+
# anyone looking at your source code can steal your password and
+
# no one else can use your code unless they hardcode in your password.
+
 
+
To solve this, we can use the <tt>JPasswordField</tt> class provided by Java to read in a password. You need to import <tt>javax.swing.JPasswordField</tt>. With it, you can write some dialog boxes using JOptionPane to read in usernames and passwords:
+
 
<pre>
 
<pre>
String userID = JOptionPane.showInputDialog(null,"Enter userid");
+
ArrayList<Twitter.Status> tweets = (ArrayList<Twitter.Status>) myT.search("what you want to search for");
JPasswordField pwd = new JPasswordField(10);
+
for (Twitter.Status x : tweets) {
JOptionPane.showConfirmDialog(null, pwd,"Enter Password for "+userID,JOptionPane.OK_OPTION);
+
  System.out.println(x.getUser() + " says " + x);
String userPassword = new String(pwd.getPassword());
+
}
Twitter myTwitter = new Twitter(userID,userPassword);
+
 
</pre>
 
</pre>
  
This is a small hack to quickly access the <tt>JPasswordField</tt> class. In a serious application, you would likely design a single window to read in both the username and password using <tt>JFrame</tt> as in the [[User:Mdomarat/Extralabs/GUI_Part_I|GUI lab]].
+
The '''full''' list of API calls is available [http://www.winterwell.com/software/jtwitter/javadoc/winterwell/jtwitter/Twitter.html here] on the jTwitter website.

Latest revision as of 11:59, 13 November 2012

Extra Lab: jTwitter

In this lab, we'll learn how to use a simple API wrapper for twitter to write Java programs to play with twitter.


Step 0: Register for Twitter

If you don't have a twitter account, you can sign up easily here. You can always delete this account later.

Step 1: Ensure you are running the latest version of JDK

Before running your lab, make sure you are running JDK 1.6.0 or later. Some of the libraries we will need use things only available in 1.6. Use the links on the main COMP 1010 website to get the latest JDK. If you are using a mac, then double check the version you are using. You will not be able to install JDK 1.6 on 32-bit macs(i.e., old intel macs).

Step 2: Download jar Files

For this code, we will need three jar files:

Save all three of these files on your hard drive.

Step 3: Make jTwitter accessible to your code

In eclipse, make the jar file accessible to your code:

  1. create a new Java project (File -> New -> Java Project).
  2. select the project, then click on Project-> Properties).
  3. click on "Java Build Path" in the left-hand pane, then click on the "Libraries" tab.
  4. click on "Add External JARs..." to add the jar file to the project.
  5. select the jtwitter.jar file you downloaded.

Repeat this process for all three jar files you downloaded. After this, the jtwitter.jar and all its contents should be accessible to your code.

In netbeans, use the following steps:

  1. Make your project as usual (File > New Project >Java Application >Next> Fill in Program name >Finish)
  2. Click File > Project Properties ("YourProgramName") If it doesn't say the right name, right-click on the coffee cup icon under the Projects from on the left-hand side and click "Set as Main Project"
  3. Go to Libraries (on the left)
  4. Click "Add JAR/Folder" and select the three .jar files (you can select them all at once) jtwitter.jar, signpost-core-1.2.1.1.jar commons-codec-1.3.jar
  5. Click OK and you now have access to the API

In other IDEs, a similar technique to add JAR files should be available

If you are using textpad, then you need to extract the jar file in the directory you want to work in. In Windows, do the following:

  1. go to the directory you want to write you program in, and move the jTwitter.jar file to that directory.
  2. open a command prompt and go to the same directory.
  3. at the command prompt extract the jar file with the command jar xf jtwitter.jar.
  4. if Windows complains about jar not being a recognized program, then you need to type the entire path of the jar command. Typically this is something like C:\Program Files\Java\jdk<some_number>\bin\jar.exe.

After this, the directory winterwell should have been created. In other operating systems (mac OS, linux), the same instructions work, and your OS should properly know where the jar command is.

Step 4: Start coding

In order to access the jTwitter methods, add the following import line with the rest of your imports:

import winterwell.jtwitter.*;

The hardest part of using jTwitter is the OAuth Key/Secret that you need to provide the application for authorization. We've registered a COMP 1010 app and have the key and secret. They will be provided for you at your lab (in a real application, you would register your own app

import winterwell.jtwitter.*;
import javax.swing.*;

public class tryjTwitter {
  
  public static void main (String[] args) {
     final String oaKey = "will be given at lab";
     final String oaSecret = "will be given at lab";
     String pin;
    
     // all the authorization material.
     OAuthSignpostClient client = new OAuthSignpostClient(oaKey,oaSecret,"oob");
     Twitter tw = new Twitter("yourTwitterUserName",client);
     client.authorizeDesktop();
     pin = JOptionPane.showInputDialog("Please enter the pin here:");
     client.setAuthorizationCode(pin);

     // the part that we actually care about:
     tw.setStatus("hello twitter world.");
  }
}

In this example, the string "yourTwitterUserName" is your actual user name that you use to log in to twitter (as a String, so put it in quotes). You don't have any place in the code to enter your password: this is all handled by twitter during the authorizeDesktop method call.

This method is a little clunky, but it should work: the authorizeDesktop method should launch your browser, and then it will provide you with a pin number, which you paste in your JOptionPane input dialog box. After this program finishes, "hello twitter world." should be your status.

Step 5: Add user interaction

To make your code more robust, you could ask the user to input (using JOptionPane, for instance):

  1. their username (to replace the hardcoded "yourTwitterUserName").
  2. their tweet.

So for instance, instead of the line:

     tw.setStatus("hello twitter world.");

You could write

String userTweet;
userTweet = JOptionPane.showInputDialog("Enter your tweet");

// if the user hit cancel, then the userInput will be null.
if (userTweet != null) {
  tw.setStatus(userTweet);
} else {
  System.out.println("You hit cancel.");
}

Step 6: Don't wreck it for everyone

The previous program (hopefully) works: it posts the string "hello twitter world" to your twitter account as a tweet. So please, please, don't abuse this. Do not write code like

for (int i = 0; i < 1000; i++) {
  myTwitter.setStatus("this is automated tweet number " + i);
}

That might well get you 1000 tweets on your account. But it might also get your account suspended. It might also get our application key (the long string provided to you) suspended, and wreck things for everyone. So please don't automate large volumes of tweets.


Step 7: Other routines in jTwitter

Setting your status is not the only thing you can accomplish with jTwitter. Other methods of the class Twitter that you may find useful are:

  • public Twitter.Status getStatus (String userName): Returns the current status of the twitter with user name userName. The method returns an object of type Twitter.Status, but this can be printed directly like it were a String:
 
System.out.println(myTwitter.getStatus("shitmydadsays"));

You don't need to be following the user to get the status. If no String parameter is passed, the status returned is your own.

  • public Twitter.User follow(String userName): follow the twitter account with user name userName. Returns an object of type Twitter.User which can be used to internally represent the user, but can also be

discarded.

  • public Twitter.User breakFriendship(String userName): stop following userName
  • public java.util.List<Twitter.User> getFriendsTimeline (): return the last 20 tweets from friends you follow. They are returned as a list. Example (uses Java 5 for loops):
ArrayList<Twitter.Status> tweets = (ArrayList<Twitter.Status>) myT.getFriendsTimeline();
for (Twitter.Status x : tweets) {
  System.out.println(x.getUser() + " says " + x);
}

Notice that this requires casting the result of the method call to an ArrayList if you want the result to be stored in a variable of that type.

  • Searching is similar. Use the method public java.util.List<Twitter.User> search (String searchTerm) which returns the latest tweets matching your search term. They are returned as a list. Example (uses Java 5 for loops):
ArrayList<Twitter.Status> tweets = (ArrayList<Twitter.Status>) myT.search("what you want to search for");
for (Twitter.Status x : tweets) {
  System.out.println(x.getUser() + " says " + x);
}

The full list of API calls is available here on the jTwitter website.