Example usage for twitter4j JSONObject JSONObject

List of usage examples for twitter4j JSONObject JSONObject

Introduction

In this page you can find the example usage for twitter4j JSONObject JSONObject.

Prototype

public JSONObject(String json) throws JSONException 

Source Link

Document

Creates a new JSONObject with name/value mappings from the JSON string.

Usage

From source file:com.tweettrends.pravar.FilterStreamExample.java

License:Apache License

public static void run(String consumerKey, String consumerSecret, String token, String secret,
        SimpleQueueService simpleQueueService) throws InterruptedException {
    BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
    StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint();
    // add some track terms
    endpoint.trackTerms(Lists.newArrayList("modi", "India", "Trump", "New York", "English", "London",
            "Tuesday Motivation", "Celtics", "GA06"));
    endpoint.languages(Lists.newArrayList("en"));

    Authentication auth = new OAuth1(consumerKey, consumerSecret, token, secret);
    // Authentication auth = new BasicAuth(username, password);

    // Create a new BasicClient. By default gzip is enabled.
    Client client = new ClientBuilder().hosts(Constants.STREAM_HOST).endpoint(endpoint).authentication(auth)
            .processor(new StringDelimitedProcessor(queue)).build();

    // Establish a connection
    client.connect();//www .j  a  v a  2s . co m

    while (true) {
        // Do whatever needs to be done with messages
        for (int msgRead = 0; msgRead < 1000; msgRead++) {
            String msg = queue.take();

            try {
                JSONObject tweet = new JSONObject(msg);
                if (tweet.has("coordinates")) {
                    String geoInfo = tweet.get("coordinates").toString();
                    if (!geoInfo.equals("null")) {
                        simpleQueueService.sendMessage(msg);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //client.stop();

    }
}

From source file:com.waves_rsp.ikb4stream.scoring.twitter.TwitterScoreProcessor.java

License:Open Source License

/**
 * Process score of an event from {@link com.waves_rsp.ikb4stream.datasource.twitter.TwitterProducerConnector TwitterProducerConnector}
 *
 * @param event an event without score//from w  ww  . j a  v a 2s.  c  om
 * @return Event with a score after OpenNLP processing
 * @throws NullPointerException     if event is null
 * @throws IllegalArgumentException if event is invalid
 * @see TwitterScoreProcessor#openNLP
 * @see TwitterScoreProcessor#COEFF_HASHTAG
 */
@Override
public Event processScore(Event event) {
    Objects.requireNonNull(event);
    long start = System.currentTimeMillis();
    String tweet;
    byte score = 0;
    try {
        JSONObject jsonTweet = new JSONObject(event.getDescription());
        tweet = getParseDescription(jsonTweet);
        List<String> tweetMap = openNLP.applyNLPlemma(tweet);
        score = scoreWords(score, tweetMap);
        //Score x COEFF_VERIFY_ACCOUNT if the twitter is certified
        if (isCertified(jsonTweet)) {
            score *= COEFF_VERIFY_ACCOUNT;
        }
    } catch (JSONException e) {
        LOGGER.error("Wrong JsonObject from Twitter Connector\n" + e.getMessage());
        throw new IllegalArgumentException("Wrong description of event");
    }
    long time = System.currentTimeMillis() - start;
    METRICS_LOGGER.log("time_scoring_" + event.getSource(), time);
    return new Event(event.getLocation(), event.getStart(), event.getEnd(), tweet, verifyMaxScore(score),
            event.getSource());
}

From source file:edu.smc.mediacommons.modules.WeatherModule.java

License:Open Source License

public WeatherModule(String search) {
    InputStream is = null;// w  w w . ja  va2s. c o  m
    JSONObject result = null;

    String baseUrl = "http://query.yahooapis.com/v1/public/yql?q=";
    String query = "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\""
            + search + "\")";

    try {
        String fullUrlStr = baseUrl + URLEncoder.encode(query, "UTF-8") + "&format=json";
        URL fullUrl = new URL(fullUrlStr);
        is = fullUrl.openStream();

        JSONTokener tok = new JSONTokener(is);
        result = new JSONObject(tok);
    } catch (JSONException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    response = result;
}

From source file:edu.smc.mediacommons.panels.WeatherPanel.java

License:Open Source License

public WeatherPanel() {
    setLayout(null);/*from  ww w.  jav  a 2s  . c om*/

    add(Utils.createLabel("Enter a ZIP Code or City, then Search", 35, 20, 300, 20, Resources.VERDANA_12_BOLD));

    final JTextField searchBox = Utils.createTextField(35, 40, 200, 20);
    add(searchBox);

    add(Utils.createLabel("Region", 30, 80, 200, 20, Resources.VERDANA_12_BOLD));
    add(Utils.createLabel("Country", 30, 105, 200, 20, Resources.VERDANA_12_BOLD));
    add(Utils.createLabel("City", 30, 130, 200, 20, Resources.VERDANA_12_BOLD));
    add(Utils.createLabel("Sunset", 30, 155, 200, 20, Resources.VERDANA_12_BOLD));
    add(Utils.createLabel("Sunrise", 30, 180, 200, 20, Resources.VERDANA_12_BOLD));
    add(Utils.createLabel("Forecast", 30, 205, 200, 20, Resources.VERDANA_12_BOLD));
    add(Utils.createLabel("High", 30, 230, 200, 20, Resources.VERDANA_12_BOLD));
    add(Utils.createLabel("Low", 30, 255, 200, 20, Resources.VERDANA_12_BOLD));

    final JTextField regionBox = Utils.createTextField(100, 80, 100, 20);
    add(regionBox);

    final JTextField countryBox = Utils.createTextField(100, 105, 100, 20);
    add(countryBox);

    final JTextField cityBox = Utils.createTextField(100, 130, 100, 20);
    add(cityBox);

    final JTextField sunsetBox = Utils.createTextField(100, 155, 100, 20);
    add(sunsetBox);

    final JTextField sunriseBox = Utils.createTextField(100, 180, 100, 20);
    add(sunriseBox);

    final JTextField forecastBox = Utils.createTextField(100, 205, 100, 20);
    add(forecastBox);

    final JTextField highBox = Utils.createTextField(100, 230, 100, 20);
    add(highBox);

    final JTextField lowBox = Utils.createTextField(100, 255, 100, 20);
    add(lowBox);

    cartoonRepresentation = new ImagePanel(Resources.IMAGE_SUN, 100, 100);
    cartoonRepresentation.setBounds(250, 70, 200, 200);
    add(cartoonRepresentation);

    JButton searchButton = new JButton("Search");
    searchButton.setBounds(235, 40, 150, 20);
    add(searchButton);

    searchButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (searchBox.getText().isEmpty()) {
                JOptionPane.showMessageDialog(getParent(), "Warning! Your input was blank.");
            } else {
                new Thread() {
                    @Override
                    public void run() {
                        JSONObject result = new WeatherModule(searchBox.getText()).getResponse();

                        try {
                            JSONObject query = new JSONObject(result.getString("query"));
                            JSONObject results = new JSONObject(query.getString("results"));
                            JSONObject channel = new JSONObject(results.getString("channel"));
                            JSONObject location = new JSONObject(channel.getString("location"));
                            JSONObject astronomy = new JSONObject(channel.getString("astronomy"));
                            JSONObject item = new JSONObject(channel.getString("item"));
                            JSONArray array = new JSONArray(item.getString("forecast"));
                            JSONObject forecast = array.getJSONObject(0);

                            regionBox.setText(location.getString("region"));
                            countryBox.setText(location.getString("country"));
                            cityBox.setText(location.getString("city"));
                            sunsetBox.setText(astronomy.getString("sunset"));
                            sunriseBox.setText(astronomy.getString("sunrise"));
                            forecastBox.setText(forecast.getString("text"));
                            highBox.setText(forecast.getString("high"));
                            lowBox.setText(forecast.getString("low"));

                            String partial = forecast.getString("text");

                            if (partial.contains("Cloud")) {
                                cartoonRepresentation.setScaled(Resources.IMAGE_CLOUDY);
                            } else if (partial.contains("Rain")) {
                                cartoonRepresentation.setScaled(Resources.IMAGE_RAINY);
                            }

                            cartoonRepresentation.repaint();
                        } catch (JSONException ex) {
                            ex.printStackTrace();
                        }
                    }
                }.start();
            }
        }
    });
}

From source file:EjemploObservador.BuscadorDeTweets.java

License:Apache License

@Override
public void run() {
    IniciaVariablesDeConeccion();//w w  w .j  av a 2  s .  c  o m
    client.connect();
    while (true) {
        try {
            /// Toma el JSON devuelto por el API de tweeter 
            /// Y extrae los datos en el TweetText

            String msg = queue.take();
            JSONObject Tweet = new JSONObject(msg);
            String Text = Tweet.getString("text");
            String User = Tweet.getJSONObject("user").getString("name");
            String location = Tweet.getJSONObject("user").getString("location");
            String TweetText = ">>>>>>>> " + location + "\n" + User + ": " + Text + "\n";

            /// Envia el TweetText al la Lista
            ListaDeTweets.agregaTweet(TweetText);

        } catch (InterruptedException ex) {
            Logger.getLogger(BuscadorDeTweets.class.getName()).log(Level.SEVERE, null, ex);

        } catch (JSONException ex) {
            Logger.getLogger(BuscadorDeTweets.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

From source file:net.lacolaco.smileessence.util.TwitterMock.java

License:Open Source License

public String getAccessToken() throws IOException, JSONException {
    return new JSONObject(getJson("tokens.json")).getString("token");
}

From source file:net.lacolaco.smileessence.util.TwitterMock.java

License:Open Source License

public String getAccessTokenSecret() throws IOException, JSONException {
    return new JSONObject(getJson("tokens.json")).getString("token_secret");
}

From source file:org.csi.yucca.storage.datamanagementapi.model.metadata.ckan.MetadataCkanFactory.java

private static JSONObject loadMessages(Locale currentLocale, String element) {
    InputStream is = null;/* w  w w .j  a  va2 s. c o  m*/
    JSONObject json = null;
    try {
        String tagsDomainsURL = Config.getInstance().getApiAdminServiceUrl();
        is = new URL(tagsDomainsURL + "/misc/stream" + element + "/").openStream();

        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = null;
        jsonText = readAll(rd);
        json = new JSONObject(jsonText);

        is.close();
    } catch (JSONException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return json;
}

From source file:tweetcrawling.TweetCrawler.java

private String getUserGender(String user) {
    String gender = "unknown";
    String apiUrl = "http://api.namsor.com/onomastics/api/json/gendre/";
    String namesPath = "";

    if (user.contains(" ")) {
        String[] firstTwoParts = user.split(" ");

        if (firstTwoParts.length == 1) {
            String name = firstTwoParts[0].replaceAll("[^A-Za-z0-9]", "");

            if (!name.isEmpty()) {
                namesPath = name + "/" + name;
            }//from   w  w w  . j a v  a 2 s. c  o m
        } else {
            String name1 = firstTwoParts[0].replaceAll("[^A-Za-z0-9]", "");
            String name2 = firstTwoParts[1].replaceAll("[^A-Za-z0-9]", "");

            if (name1 != null && name2 != null && !name1.isEmpty() && !name2.isEmpty()) {
                namesPath = name1 + "/" + name2;
            } else if (name1 != null && !name1.isEmpty() && (name2 == null || name2.isEmpty())) {
                namesPath = name1 + "/" + name1;
            } else if ((name1 == null || name1.isEmpty()) && !name2.isEmpty() && name2 != null) {
                namesPath = name2 + "/" + name2;
            }
        }
    } else {
        String name = user.replaceAll("[^A-Za-z0-9]", "");
        namesPath = name + "/" + name;
    }

    namesPath = namesPath.trim();

    if (!namesPath.isEmpty() && namesPath != "/") {
        try {
            String data = getData(apiUrl + namesPath);
            JSONObject obj = new JSONObject(data);
            gender = obj.getString("gender");
        } catch (Exception e) {
            return "unknown";
        }
    }

    return gender;
}

From source file:twitterapp.TweetsProcessing.java

public static void createSeparateEntities() throws JSONException {

    String[] collectionsTweets = { "myTweetCol", "myTweetCol2", "myTweetCol3", "myTweetCol4" };
    String[] colEntities = { "separateEntities", "separateEntities2", "separateEntities3",
            "separateEntities4" };
    for (int col = 0; col < collectionsTweets.length; col++) {
        MongoClient mongo = new MongoClient("localhost", 27017);
        MongoDatabase database = mongo.getDatabase("myTweetdb");
        MongoCollection<Document> collection = database.getCollection(collectionsTweets[col]);
        Iterator<Document> kati = collection.find().iterator();

        while (kati.hasNext()) {

            Document doc = kati.next();

            String user, url, hashtag, mentioned, id, timestamp;
            user = url = hashtag = mentioned = id = timestamp = "";

            JSONObject a = new JSONObject(doc);
            String temp = a.getString("user");
            String tokens[] = temp.split(",");
            for (int j = 0; j < tokens.length; j++) {
                if (tokens[j].contains("screen_name")) {

                    temp = tokens[j].replace("\"screen_name\":", "");
                    user = temp.replace("\"", "");

                }/* w w w . j  a  v  a  2s  .com*/

            }
            timestamp = String.valueOf(a.getLong("timestamp_ms"));
            JSONObject b = a.getJSONObject("entities");
            tokens = b.toString().split(",");
            for (int j = 0; j < tokens.length; j++) {
                if (tokens[j].contains("text")) {
                    String temp2 = tokens[j].replace("\"", "");
                    temp2 = temp2.replace(":", "");
                    temp2 = temp2.replace("}", "");
                    temp2 = temp2.replace("]", "");
                    temp2 = temp2.replace("text", "");
                    hashtag = hashtag.concat(temp2 + " ").trim();

                }
                if (tokens[j].contains("expanded_url")) {
                    String temp2 = tokens[j].replace("\":\"", "");
                    temp2 = temp2.replace("\"", "");
                    temp2 = temp2.replace("expanded_url", "");
                    url = url.concat(temp2 + " ");
                }
                if (tokens[j].contains("screen_name")) {
                    String temp2 = tokens[j].replace(":", "");
                    temp2 = temp2.replace("\"", "");
                    temp2 = temp2.replace("screen_name", "");
                    mentioned = mentioned.concat(temp2 + " ");
                }

            }

            if (a.toString().contains("retweeted_status")) {
                b = (JSONObject) a.getJSONObject("retweeted_status");
                id = b.getString("id_str");

            }

            Document object = new Document("user", user).append("timestamp", timestamp).append("hashtag",
                    hashtag);
            Document object1 = new Document("user", user).append("timestamp", timestamp).append("url", url);
            Document object2 = new Document("user", user).append("timestamp", timestamp)
                    .append("mentioned_users", mentioned);
            Document object3 = new Document("user", user).append("timestamp", timestamp)
                    .append("retweeted_tweet", id);

            MongoCollection<Document> collection2 = database.getCollection(colEntities[col]);

            collection2.insertOne(object);
            collection2.insertOne(object1);
            collection2.insertOne(object2);
            collection2.insertOne(object3);

        }
    }

}