I'm getting a lot of java examples from twitter4j github and trying them on Processing to attempt to understand how things works. I succeeded in various, but this one is throwing a null pointer exception that i could not get, highlighting the ' } ' just before the last ' } ' in code . As it uses o lot of stuff i don't know like java.io, i'm stuck.
It should get an status (a tweet) and save it to a file in raw JSON. The example in java is
here and my code is like this
(i got my credentials at the right place, but deleted them here):
- import processing.opengl.*;
- import java.io.*;
- import java.util.List;
- import twitter4j.Status;
- import twitter4j.Twitter;
- import twitter4j.TwitterException;
- import twitter4j.TwitterFactory;
- import twitter4j.json.DataObjectFactory;
- Twitter twitter;
- void setup() {
- size(600, 400);
- //Credentials
- ConfigurationBuilder cb = new ConfigurationBuilder();
- cb.setOAuthConsumerKey("");
- cb.setOAuthConsumerSecret("");
- cb.setOAuthAccessToken("");
- cb.setOAuthAccessTokenSecret("");
- cb.setDebugEnabled(true);
- Twitter twitter = new TwitterFactory(cb.build()).getInstance();
- System.out.println("Saving public timeline.");
- try {
- new File("statuses").mkdir();
- List<Status> statuses = twitter.getHomeTimeline();
- for (Status status : statuses) {
- String rawJSON = DataObjectFactory.getRawJSON(status);
- String fileName = "statuses/" + status.getId() + ".json";
- storeJSON(rawJSON, fileName);
- System.out.println(fileName + " - " + status.getText());
- }
- System.out.print("\ndone.");
- System.exit(0);
- } catch (IOException ioe) {
- ioe.printStackTrace();
- System.out.println("Failed to store tweets: " + ioe.getMessage());
- } catch (TwitterException te) {
- te.printStackTrace();
- System.out.println("Failed to get timeline: " + te.getMessage());
- System.exit(-1);
- }
- }//eof setup
- private static void storeJSON(String rawJSON, String fileName) throws IOException {
- FileOutputStream fos = null;
- OutputStreamWriter osw = null;
- BufferedWriter bw = null;
- try {
- fos = new FileOutputStream(fileName);
- osw = new OutputStreamWriter(fos, "UTF-8");
- bw = new BufferedWriter(osw);
- bw.write(rawJSON);
- bw.flush();
- } finally {
- if (bw != null) {
- try {
- bw.close();
- } catch (IOException ignore) {
- }
- }
- if (osw != null) {
- try {
- osw.close();
- } catch (IOException ignore) {
- }
- }
- if (fos != null) {
- try {
- fos.close();
- } catch (IOException ignore) {
- }
- }
- }
- }
1