Example usage for twitter4j Query Query

List of usage examples for twitter4j Query Query

Introduction

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

Prototype

public Query(String query) 

Source Link

Usage

From source file:uk.ac.essex.wonderland.modules.twitter.client.TwitterPanel.java

License:Open Source License

private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed

    if (DEBUG) {/*from  w  ww  .ja  v  a2 s .  com*/
        String queryString = queryField.getText().trim();
        if (queryString.isEmpty()) {
            return;
        }
        Query query = new Query(queryString);
        query.setLang("en");

        Twitter twitter = new TwitterFactory().getInstance();
        try {
            QueryResult result = twitter.search(query);
            String warning = result.getWarning();
            if (warning != null) {
                System.err.println(warning);
            }
            @SuppressWarnings("unchecked")
            List<Tweet> tweets = result.getTweets();
            for (Tweet tweet : tweets) {
                addTweet(tweet);
            }
        } catch (TwitterException ex) {
            Logger.getLogger(TwitterPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        String query = queryField.getText().trim();
        if (!query.isEmpty()) {
            cell.performQuery(query);
        }
    }

}

From source file:uk.ac.essex.wonderland.modules.twitter.server.TwitterCellMO.java

License:Open Source License

private void runQuery(String queryString) {
    //If this is a new query string, invalidate the old results
    if (queryResult != null) {
        if (!queryString.equalsIgnoreCase(queryResult.getQuery())) {
            queryResult = null;/*www  .  j a  va  2  s  . com*/
        }
    }
    Twitter twitter = new TwitterFactory().getInstance();
    TwitterManager tm = AppContext.getManager(TwitterManager.class);
    //Call the method on the service
    //Callbacks to this object via twitterQueryResult()
    Query query = new Query(queryString);
    tm.runQuery(twitter, query, this);
}

From source file:uk.ac.susx.tag.method51.twitter.params.QueryParams.java

License:Apache License

public Query buildQuery() throws SQLException {
    List<String> keywords = getKeywords();

    if (keywords.size() == 0 && getLocation().size() == 0) {
        throw new RuntimeException("No keywords or locations provided");
    }/*w  w w  .  j  a  v a 2 s  . com*/

    final String q;

    if (keywords.size() > 1) {
        q = "\"" + StringUtils.join(keywords, "\" OR \"") + "\"";
    } else {
        q = keywords.get(0);
    }

    //LOG.info("Searching keywords: {}", q);
    //LOG.info("Query length: {}", q.length());

    Query query = new Query(q);
    query.setCount(100);
    query.setResultType(Query.RECENT);

    if (getAcceptedLanguages().size() > 0) {
        query.setLang(StringUtils.join(getAcceptedLanguages(), ","));
    }

    if (getUntilId() != null) {
        query.setMaxId(getUntilId());
    }

    if (getSinceId() != null) {
        query.setSinceId(getSinceId());

    } else if (getSinceMaxId()) {
        try (Connection con = dbParams.get().buildConnection()) {
            long maxId = Util.getMaxID(con, getMysqlTweetOutputTable());
            query.setSinceId(maxId);
            LOG.info("Determined {} as max id, searching since that.", maxId);
        }
    }

    if (getSinceId() == null && getSinceDate() != null) {
        long approxSinceId = Util.getMinSnowflakeId(getSinceDate());
        query.setSinceId(approxSinceId);
        LOG.info("Determined min Snowflake ID {}", approxSinceId);
    }

    if (getUntilId() == null && getUntilDate() != null) {
        long approxUntilId = Util.getMaxSnowflakeId(getUntilDate());
        query.setMaxId(approxUntilId);
        LOG.info("Determined max Snowflake ID {}", approxUntilId);
    }

    if (getLocation().size() == 1) {
        try {
            String[] geo = getLocation().get(0).split("\\|");

            query.setGeoCode(new GeoLocation(Double.parseDouble(geo[0]), Double.parseDouble(geo[1])),
                    Double.parseDouble(geo[2]), Query.KILOMETERS);

        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("invalid location param " + getLocation().get(0), e);
        }
    }

    return query;
}

From source file:uniandes.cupi2.tweetSpy.mundo.TweeSpy.java

License:Academic Free License

/**
 * Retorna la lista de Usuarios que se encuantran en cierto indice.
 * @param indice//from  w  w  w  .  j ava 2s . c  o m
 * @return
 */
public ListaDoblementeEncadenada<Usuario> darUsuariosEnIndice(String indice) {

    ListaDoblementeEncadenada<Usuario> listaIndice = new ListaDoblementeEncadenada<Usuario>();
    try {

        //Para buscaar por indices

        Query query = new Query(indice);
        QueryResult result;

        result = user.search(query);

        List<Status> tweets = result.getTweets();
        for (int i = 0; i < tweets.size(); i++) {
            Status tweet = (Status) tweets.get(i);
            String nombre = tweet.getUser().getName();
            Usuario nuevoAmigo = new Usuario(nombre, "", "");
            listaIndice.agregarFinal(nuevoAmigo);
        }

        // contenedor?

    } catch (Exception e) {
    }
    return listaIndice;
}

From source file:uniandes.edu.twitterreader.TwitterApp.java

/**
 * Reads all twetts accoding to TWITTER_QUERIES with JSON format and inserts
 * in MongoDB collection//from   www.  ja va2 s. c o m
 *
 * @param writesFile writes an additional file in TWEETS_PATH if true
 */
public void readColombiaTopics(boolean writesFile) {

    PrintWriter writer = null;

    try {
        if (writesFile) {
            writer = new PrintWriter(TWEETS_PATH, "UTF-8");
        }

        for (String queryString : TWITTER_QUERIES) {
            Query query = new Query(queryString);
            query.setSince(QUERY_SINCE_DATE);
            query.setUntil(QUERY_LAST_DATE);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    String jsonTweet = TwitterObjectFactory.getRawJSON(tweet);
                    if (writesFile && writer != null) {
                        writer.println(jsonTweet);
                    }
                    mongoCollection.insertOne(Document.parse(jsonTweet));
                }
            } while ((query = result.nextQuery()) != null);
        }

    } catch (FileNotFoundException | UnsupportedEncodingException | TwitterException ex) {
        Logger.getLogger(TwitterApp.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (writesFile && writer != null) {
            writer.close();
        }
    }

}

From source file:uta.ak.CollectTweets.java

public void collectTweetsByFileList(String sinceDate, String untilDate, String tag) {
    try {//from  www . j a  v  a  2s  . c  om
        // The factory instance is re-useable and thread safe.
        System.out.println("Start to collect tweets from :");
        Set<String> mediaList = new HashSet<String>();
        Resource res = new ClassPathResource("new-social-meida-list.txt");
        //                File stopwords=res.getFile();
        //      File stopwords=new File("/Users/zhangcong/dev/corpus/StopWordTable2.txt");
        InputStreamReader isr = new InputStreamReader(res.getInputStream());
        //            File medias=new File(path);
        //            BufferedReader mdsreader = new BufferedReader(new FileReader(medias));
        BufferedReader mdsreader = new BufferedReader(isr);
        String tempString = mdsreader.readLine();
        while ((tempString = mdsreader.readLine()) != null) {
            System.out.println(tempString.toLowerCase());
            mediaList.add(tempString.toLowerCase());
        }

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("LuhVZOucqdHX6x0lcVgJO6QK3")
                .setOAuthConsumerSecret("6S7zbGLvHMXDMgRXq7jRIA6QmMpdI8i5IJNpnjlB55vpHpFMpj")
                .setOAuthAccessToken("861637891-kLunD37VRY8ipAK3TVOA0YKOKxeidliTqMtNb7wf")
                .setOAuthAccessTokenSecret("vcKDxs6qHnEE8fhIJr5ktDcTbPGql5o3cNtZuztZwPYl4");
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        /*
        Connection con = null; //MYSQL
        Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL
        con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/USTTMP", "root", "root.123"); //MYSQL
        System.out.println("connection yes");
                
        String insertSQL="INSERT INTO c_rawtext(mme_lastupdate, mme_updater, title, text, tag, text_createdate) "
                        + "VALUES (NOW(), \"AK\", ?, ?, ?, ?)";
        PreparedStatement insertPS = con.prepareStatement(insertSQL);
        */

        //?usttmp??
        String restUrl = "http://192.168.0.103:8991/usttmp_textreceiver/rest/addText";

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (String mediastr : mediaList) {
            Query query = new Query("from:" + mediastr);
            query.setSince(sinceDate);
            query.setUntil(untilDate);
            query.setCount(100);
            query.setLang("en");

            QueryResult result = twitter.search(query);
            for (Status status : result.getTweets()) {
                System.out.println("@" + status.getUser().getScreenName() + " | "
                        + status.getCreatedAt().toString() + ":" + status.getText());
                System.out.println("Inserting the record into the table...");

                String formattedDate = format1.format(status.getCreatedAt());
                /*
                insertPS.setString (1, status.getUser().getScreenName());
                insertPS.setString (2, status.getText());
                insertPS.setString (3, tag);
                insertPS.setString (4, formattedDate);
                insertPS.addBatch();*/

                //                    if(null!=status.getText()){
                //                        break;
                //                    }

                String interfaceMsg = "<message> " + "    <title> "
                        + ((null != status.getUser().getScreenName()) ? status.getUser().getScreenName()
                                : "NO TITLE")
                        + "    </title> " + "    <text> " + StringEscapeUtils.escapeXml10(status.getText())
                        + "    </text> " + "    <textCreatetime> " + formattedDate + "    </textCreatetime> "
                        + "    <tag> " + tag + "    </tag> " + "</message>";

                //                    String restUrl="http://127.0.0.1:8991/usttmp_textreceiver/rest/addText";

                RestTemplate restTemplate = new RestTemplate();

                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.TEXT_XML);
                headers.setAccept(Arrays.asList(MediaType.TEXT_XML));
                //            headers.setContentLength();
                HttpEntity<String> entity = new HttpEntity<String>(interfaceMsg, headers);

                ResponseEntity<String> resresult = restTemplate.exchange(restUrl, HttpMethod.POST, entity,
                        String.class);

                System.out.println(resresult.getBody());
                if (resresult.getBody().contains("<result>failed</result>")) {
                    throw new RuntimeException("response message error");
                }

            }
        }

        //            System.out.println("Start to insert records...");
        //            insertPS.clearParameters();
        //            int[] results = insertPS.executeBatch();

    } catch (Exception te) {
        te.printStackTrace();
        System.out.println("Failed: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:uta.ak.CollectTweets.java

public void collectTweetsByKeyWords(String keyWords, String sinceDate, String untilDate, String tag) {
    try {//from  w w w.  j  a  va 2s.c o m

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("LuhVZOucqdHX6x0lcVgJO6QK3")
                .setOAuthConsumerSecret("6S7zbGLvHMXDMgRXq7jRIA6QmMpdI8i5IJNpnjlB55vpHpFMpj")
                .setOAuthAccessToken("861637891-kLunD37VRY8ipAK3TVOA0YKOKxeidliTqMtNb7wf")
                .setOAuthAccessTokenSecret("vcKDxs6qHnEE8fhIJr5ktDcTbPGql5o3cNtZuztZwPYl4");
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        Connection con = null; //MYSQL
        Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL
        con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/USTTMP", "root", "root.123"); //MYSQL
        System.out.println("connection yes");

        String insertSQL = "INSERT INTO c_rawtext(mme_lastupdate, mme_updater, title, text, tag, text_createdate) VALUES (NOW(), \"AK\", ?, ?, ?, ?)";
        PreparedStatement insertPS = con.prepareStatement(insertSQL);

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");

        Query query = new Query(keyWords);
        query.setSince(sinceDate);
        query.setUntil(untilDate);
        query.setCount(100);
        query.setLang("en");

        QueryResult result = twitter.search(query);
        for (Status status : result.getTweets()) {
            //                    System.out.println("@" + status.getUser().getScreenName() +
            //                                       " | " + status.getCreatedAt().toString() +
            //                                       ":" + status.getText());
            //                    System.out.println("Inserting the record into the table...");

            String formattedDate = format1.format(status.getCreatedAt());

            insertPS.setString(1, status.getUser().getScreenName());
            insertPS.setString(2, status.getText());
            insertPS.setString(3, tag);
            insertPS.setString(4, formattedDate);
            insertPS.addBatch();
        }

        System.out.println("Start to insert records...");
        insertPS.clearParameters();
        int[] results = insertPS.executeBatch();

    } catch (Exception te) {
        te.printStackTrace();
        System.out.println("Failed: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:wap.twitter.model.TwitterUtility.java

public List<Tweet> getTweets(String news) {
    TwitterFactory tf = config();/*from w  w  w .ja  va  2s. com*/
    Twitter twitter = tf.getInstance();
    try {
        List<Tweet> tws = new ArrayList<Tweet>();
        int i = 0;
        Query query = new Query("#" + news);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                Tweet tw = new Tweet();
                if (i == 8) {
                    break;
                } else {
                    tw.setTitle(news);
                    tw.setUser(tweet.getUser().getScreenName());
                    tw.setUrl(tweet.getSource());
                    tw.setImage(tweet.getUser().getProfileImageURL());
                    tw.setBody(tweet.getText());
                    tw.setSource(tweet.getSource());
                    tw.setId(tweet.getId() + "");
                    i++;
                }
                System.out.println("******************* " + tweet.getGeoLocation());
                tws.add(tw);
            }
        } while ((query = result.nextQuery()) != null);
        return tws;
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    return null;
}

From source file:webServices.RestServiceImpl.java

@GET
@Path("/findTwittsRest")
@Produces({ MediaType.TEXT_PLAIN })//from www .  j  a v  a2 s .co  m
public String twitterSearchRest(@QueryParam("keys") String searchKeys, @QueryParam("sinceId") long sinceId,
        @QueryParam("maxId") long maxId, @QueryParam("update") boolean update,
        @QueryParam("location") String location) {

    final Vector<String> results = new Vector<String>();
    String output = "";
    long higherStatusId = Long.MIN_VALUE;
    long lowerStatusId = Long.MAX_VALUE;

    Query searchQuery = new Query(searchKeys);
    searchQuery.setCount(50);
    searchQuery.setResultType(Query.ResultType.recent);

    if (sinceId != 0) {
        if (update) {
            searchQuery.setSinceId(sinceId);
        }
        higherStatusId = sinceId;
    }
    if (maxId != 0) {
        if (!update) {
            searchQuery.setMaxId(maxId);
        }
        lowerStatusId = maxId;
    }
    if (location != null) {
        double lat = Double.parseDouble(location.substring(0, location.indexOf(",")));
        double lon = Double.parseDouble(location.substring(location.indexOf(",") + 1, location.length()));

        searchQuery.setGeoCode(new GeoLocation(lat, lon), 10, Query.KILOMETERS);
    }

    try {
        QueryResult qResult = twitter.search(searchQuery);

        for (Status status : qResult.getTweets()) {
            //System.out.println(Long.toString(status.getId())+"  ***  "+Long.toString(status.getUser().getId())+"  ***  "+status.isRetweet()+"  ***  "+status.isRetweeted());

            higherStatusId = Math.max(status.getId(), higherStatusId);
            lowerStatusId = Math.min(status.getId(), lowerStatusId);

            if (!status.isRetweet()) {
                if (status.getGeoLocation() != null) {
                    System.out.println(Long.toString(status.getId()) + "@"
                            + Double.toString(status.getGeoLocation().getLatitude()) + ","
                            + Double.toString(status.getGeoLocation().getLongitude()));
                    results.add(Long.toString(status.getId()) + "@"
                            + Double.toString(status.getGeoLocation().getLatitude()) + ","
                            + Double.toString(status.getGeoLocation().getLongitude()));
                } else {
                    results.add(Long.toString(status.getId()) + "@null");
                }
            }
        }

    } catch (TwitterException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    TwitterResults resultsObj = new TwitterResults(results.toString(), higherStatusId, lowerStatusId);
    ObjectMapper mapper = new ObjectMapper();
    try {
        output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultsObj);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return output;
}

From source file:wedt.project.MainWindow.java

private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
    statusLabel.setText("Trwa wyszukiwanie...");
    lockUI();/*from   www  .  j  ava2s  .c  om*/
    SwingWorker<List<Status>, Void> worker = new SwingWorker<List<Status>, Void>() {

        @Override
        protected List<Status> doInBackground() throws Exception {
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true).setOAuthConsumerKey("PG0vtiQ73sbKKCfp9JfqyQ")
                    .setOAuthConsumerSecret("ITCkTQiqCh3aVZexXentwnwCJooVpUOcpkIENPKowI")
                    .setOAuthAccessToken("89783194-z0J1KLudg6MFMhhysKmL29zB5wBjxfxWUboAh6lAI")
                    .setOAuthAccessTokenSecret("ytOdt7t8P1OrmAI2ZCRoX30ZC3eLcDSgPY8gOa6FCwQ");
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter = tf.getInstance();

            try {
                Query query = new Query(searchField.getText());
                query.setCount(10);
                query.setLang("en");
                if (checkBoxLatest.isSelected() && checkBoxPopular.isSelected())
                    query.setResultType(Query.ResultType.mixed);
                else if (checkBoxLatest.isSelected())
                    query.setResultType(Query.ResultType.recent);
                else if (checkBoxPopular.isSelected())
                    query.setResultType(Query.ResultType.popular);

                QueryResult result = twitter.search(query);
                return result.getTweets();

            } catch (TwitterException e) {
                statusLabel.setText("Wyszukiwanie nie powiodlo sie");
                e.printStackTrace();
                //System.out.println("Failed to search tweets: " + te.getMessage());
                JOptionPane.showMessageDialog(null, e.getMessage(), "Blad pobierania wynikow wyszukiwania",
                        JOptionPane.INFORMATION_MESSAGE);
            }
            return null;
        }

        @Override
        protected void done() {
            try {
                List<Status> tweets = get();
                listModel = new DefaultListModel();
                tweetsList.setModel(listModel);
                tweets.stream().forEach((tweet) -> {
                    listModel.addElement(tweet.getText());
                });
                statusLabel.setText("Gotowe");
            } catch (Exception ex) {
                ex.printStackTrace();
                statusLabel.setText("Wyszukiwanie nie powiodlo sie");
            }
            unlockUI();
        }
    };
    worker.execute();
}