package io; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import data.Tweet; import data.TwitterJsonDeserializer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * Reads tweets from an InputStream. * * @author Peter Wu */ public class TweetReader implements ITweetReader { private final InputStream is; private final BufferedReader reader; private final Gson gson; public TweetReader(InputStream is) { if (is == null) { throw new NullPointerException(); } this.is = is; reader = new BufferedReader(new InputStreamReader(is)); gson = TwitterJsonDeserializer.getGsonBuilder().create(); } @Override public Tweet getTweet() throws IOException { String line = reader.readLine(); Tweet tweet = null; if (line != null) { try { tweet = gson.fromJson(line, Tweet.class); } catch (JsonSyntaxException ex) { debugTweet(line, ex); throw ex; } } return tweet; } @Override public void close() { try { is.close(); } catch (IOException ex) { } } private void debugTweet(String line, JsonSyntaxException ex) { System.err.println("Faulty line: " + line); ex.printStackTrace(); } }