List of usage examples for twitter4j Query RECENT
ResultType RECENT
To view the source code for twitter4j Query RECENT.
Click Source Link
From source file:org.anc.lapps.datasource.twitter.TwitterDatasource.java
/** * Entry point for a Lappsgrid service.//w w w . jav a 2 s. com * <p> * Each service on the Lappsgrid will accept {@code org.lappsgrid.serialization.Data} object * and return a {@code Data} object with a {@code org.lappsgrid.serialization.lif.Container} * payload. * <p> * Errors and exceptions that occur during processing should be wrapped in a {@code Data} * object with the discriminator set to http://vocab.lappsgrid.org/ns/error * <p> * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/Data.html>org.lappsgrid.serialization.Data</a><br /> * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/lif/Container.html>org.lappsgrid.serialization.lif.Container</a><br /> * * @param input A JSON string representing a Data object * @return A JSON string containing a Data object with a Container payload. */ @Override public String execute(String input) { Data<String> data = Serializer.parse(input, Data.class); String discriminator = data.getDiscriminator(); // Return ERRORS back if (Discriminators.Uri.ERROR.equals(discriminator)) { return input; } // Generate an error if the used discriminator is wrong if (!Discriminators.Uri.GET.equals(discriminator)) { return generateError( "Invalid discriminator.\nExpected " + Discriminators.Uri.GET + "\nFound " + discriminator); } Configuration config = new ConfigurationBuilder().setApplicationOnlyAuthEnabled(true).setDebugEnabled(false) .build(); // Authentication using saved keys Twitter twitter = new TwitterFactory(config).getInstance(); String key = readProperty(KEY_PROPERTY); if (key == null) { return generateError("The Twitter Consumer Key property has not been set."); } String secret = readProperty(SECRET_PROPERTY); if (secret == null) { return generateError("The Twitter Consumer Secret property has not been set."); } twitter.setOAuthConsumer(key, secret); try { twitter.getOAuth2Token(); } catch (TwitterException te) { String errorData = generateError(te.getMessage()); logger.error(errorData); return errorData; } // Get query String from data payload Query query = new Query(data.getPayload()); // Set the type to Popular or Recent if specified // Results will be Mixed by default. if (data.getParameter("type") == "Popular") query.setResultType(Query.POPULAR); if (data.getParameter("type") == "Recent") query.setResultType(Query.RECENT); // Get lang string String langCode = (String) data.getParameter("lang"); // Verify the validity of the language code and add it to the query if it's valid if (validateLangCode(langCode)) query.setLang(langCode); // Get date strings String sinceString = (String) data.getParameter("since"); String untilString = (String) data.getParameter("until"); // Verify the format of the date strings and set the parameters to query if correctly given if (validateDateFormat(untilString)) query.setUntil(untilString); if (validateDateFormat(sinceString)) query.setSince(sinceString); // Get GeoLocation if (data.getParameter("address") != null) { String address = (String) data.getParameter("address"); double radius = (double) data.getParameter("radius"); if (radius <= 0) radius = 10; Query.Unit unit = Query.MILES; if (data.getParameter("unit") == "km") unit = Query.KILOMETERS; GeoLocation geoLocation; try { double[] coordinates = getGeocode(address); geoLocation = new GeoLocation(coordinates[0], coordinates[1]); } catch (Exception e) { String errorData = generateError(e.getMessage()); logger.error(errorData); return errorData; } query.geoCode(geoLocation, radius, String.valueOf(unit)); } // Get the number of tweets from count parameter, and set it to default = 15 if not specified int numberOfTweets; try { numberOfTweets = (int) data.getParameter("count"); } catch (NullPointerException e) { numberOfTweets = 15; } // Generate an ArrayList of the wanted number of tweets, and handle possible errors. // This is meant to avoid the 100 tweet limit set by twitter4j and extract as many tweets as needed ArrayList<Status> allTweets; Data tweetsData = getTweetsByCount(numberOfTweets, query, twitter); String tweetsDataDisc = tweetsData.getDiscriminator(); if (Discriminators.Uri.ERROR.equals(tweetsDataDisc)) return tweetsData.asPrettyJson(); else { allTweets = (ArrayList<Status>) tweetsData.getPayload(); } // Initialize StringBuilder to hold the final string StringBuilder builder = new StringBuilder(); // Append each Status (each tweet) to the initialized builder for (Status status : allTweets) { String single = status.getCreatedAt() + " : " + status.getUser().getScreenName() + " : " + status.getText() + "\n"; builder.append(single); } // Output results Container container = new Container(); container.setText(builder.toString()); Data<Container> output = new Data<>(Discriminators.Uri.LAPPS, container); return output.asPrettyJson(); }
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"); }//from www . ja v a2 s . co m 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; }