summaryrefslogtreecommitdiff
path: root/src/io/InputReader.java
blob: 985a59b11c28109c16f9aa8130ab5ac6874b6900 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package io;

import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import main.ResultListener;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Read from standard input and inserts these tweets into the database.
 *
 * @author Maurice Laveaux
 */
public class InputReader {

    /* The listener for standard input tweets. */
    private final ResultListener m_listener;

    /**
     * @param listener The given listener for the input.
     */
    public InputReader(final ResultListener listener) {
        m_listener = listener;
    }

    /* Create a reader for the standard input, read each line and tweetReceived
     * listener when a valid JSONObject is generated.
     */
    public void startLoop() {
        Scanner input = new Scanner(System.in);

        while (input.hasNext()) {
            try {
                String line = input.nextLine();
                if(line.equals("exit")) {
                    return;
                }
                
                JSONObject tweet = new JSONObject(line);
                
                if (!tweet.has("user")) {
                    throw new JSONException("not a valid tweet JSON object");
                }
                
                m_listener.tweetReceived(tweet);
            } catch (JSONException ex) {
                getLogger().log(Level.INFO, null, ex);
            }
        }
    }

    private Logger getLogger() {
        return Logger.getLogger(InputReader.class.getName());
    }
}