List of usage examples for twitter4j Status getId
long getId();
From source file:org.opennms.netmgt.notifd.MicroblogNotificationStrategy.java
License:Open Source License
/** {@inheritDoc} */ @Override/* w w w .j a v a2 s . co m*/ public int send(List<Argument> arguments) { Twitter svc = buildUblogService(arguments); String messageBody = buildMessageBody(arguments); Status response; final String baseURL = svc.getConfiguration().getClientURL(); LOG.debug("Dispatching microblog notification at base URL '{}' with message '{}'", baseURL, messageBody); try { response = svc.updateStatus(messageBody); } catch (TwitterException e) { LOG.error("Microblog notification failed at service URL '{}'", baseURL, e); return 1; } LOG.info("Microblog notification succeeded: update posted with ID {}", response.getId()); return 0; }
From source file:org.opennms.netmgt.notifd.MicroblogReplyNotificationStrategy.java
License:Open Source License
/** {@inheritDoc} */ @Override//from w w w .jav a 2 s . c o m public int send(final List<Argument> arguments) { final Twitter svc = buildUblogService(arguments); String destUser = findDestName(arguments); Status response; if (destUser == null || "".equals(destUser)) { LOG.error( "Cannot send a microblog reply notice to a user with no microblog username set. Either set a microblog username for this OpenNMS user or use the MicroblogUpdateNotificationStrategy instead."); return 1; } // In case the user tried to be helpful, avoid a double @@ if (destUser.startsWith("@")) destUser = destUser.substring(1); final String fullMessage = String.format("@%s %s", destUser, buildMessageBody(arguments)); LOG.debug("Dispatching microblog reply notification at base URL '{}' with message '{}'", svc.getConfiguration().getClientURL(), fullMessage); try { response = svc.updateStatus(fullMessage); } catch (final TwitterException e) { LOG.error("Microblog notification failed at service URL '{}'", svc.getConfiguration().getClientURL(), e); return 1; } LOG.info("Microblog reply notification succeeded: reply update posted with ID {}", response.getId()); return 0; }
From source file:org.opensocial.TwitterProxy.java
License:Apache License
/** * Called on HTTP GET/* w w w . jav a 2s . c om*/ * Returns last 20 tweets from the user using "screen_name". * If screenName is null or an empty string, we return the last 20 tweets from the public * timeline * @param screenName * @return JSON Response a ActivityStream Activity collection for the set tweets */ @GET @Produces(MediaType.APPLICATION_JSON) public Object getTweets(@QueryParam("screen_name") String screenName) { JSONArray resultArray = new JSONArray(); ResponseList<Status> list = null; try { if (screenName == null || screenName.equals("")) { list = twitter.getHomeTimeline(); } else { list = twitter.getUserTimeline(screenName); } System.out.println("Rate limit: " + list.getRateLimitStatus().getRemainingHits()); Iterator<Status> iter = list.iterator(); while (iter.hasNext()) { Status status = iter.next(); ActivityBuilder activityBuilder = Activity.makeActivity().id(Long.toString(status.getId())) .verb(Verb.POST).published(new DateTime(status.getCreatedAt().getTime())) .source(ASObject.makeObject(ASObject.SOURCE).displayName(status.getSource())) .author(PersonObject.makePerson(status.getUser().getScreenName()) .id(Long.toString(status.getUser().getId())) .image(MediaLink .makeMediaLink(status.getUser().getProfileImageURL().toExternalForm())) .get()); boolean eeAdded = false; eeAdded = EmbeddedExperiences.addHashtagEE(uriInfo, status, activityBuilder); if (!eeAdded) { eeAdded = EmbeddedExperiences.addUrlMatchedEE(uriInfo, status, activityBuilder); } if (!eeAdded) { eeAdded = EmbeddedExperiences.addUrlStyleEE(status, activityBuilder); } activityBuilder.content(status.getText()); Activity activity = activityBuilder.get(); StringWriter swriter = new StringWriter(); activity.writeTo(swriter); JSONObject jobj = new JSONObject(swriter.toString()); resultArray.put(jobj); } return resultArray; } catch (Exception e) { e.printStackTrace(); return Response.serverError().entity(e).build(); } }
From source file:org.rhq.enterprise.server.plugins.alertMicroblog.MicroblogSender.java
License:Open Source License
@Override public SenderResult send(Alert alert) { SenderResult result;//from w w w .j a v a2s. com String consumerKey = preferences.getSimpleValue("consumerKey", CONS_KEY); String consumerSecret = preferences.getSimpleValue("consumerSecret", CONS_SECRET); String accessTokenFilePath = preferences.getSimpleValue("accessTokenFilePath", "/path/to/token.ser"); try { TwitterFactory tFactory = new TwitterFactory(); AccessToken accessToken = restoreAccessToken(accessTokenFilePath); log.debug("loading accessToken from " + accessTokenFilePath); log.debug("token: [" + accessToken.getToken() + "]"); log.debug("tokenSecret: [" + accessToken.getTokenSecret() + "]"); Twitter twitter = tFactory.getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); twitter.setOAuthAccessToken(accessToken); AlertManagerLocal alertManager = LookupUtil.getAlertManager(); StringBuilder b = new StringBuilder("Alert "); b.append(alert.getId()).append(":'"); // Alert id b.append(alert.getAlertDefinition().getResource().getName()); b.append("' ("); b.append(alert.getAlertDefinition().getResource().getId()); b.append("): "); b.append(alertManager.prettyPrintAlertConditions(alert, true)); b.append("-by " + this.alertParameters.getSimpleValue("twittedBy", "@RHQ")); // TODO not for production :-) // TODO use some alert url shortening service String msg = b.toString(); if (msg.length() > 140) msg = msg.substring(0, 140); Status status = twitter.updateStatus(msg); result = SenderResult.getSimpleSuccess("Send notification - msg-id: " + status.getId()); } catch (TwitterException e) { log.warn("Notification via Microblog failed!", e); result = SenderResult.getSimpleFailure("Sending failed :" + e.getMessage()); } catch (IOException e) { log.error("Notification via Microblog failed!", e); result = SenderResult.getSimpleFailure("Sending failed :" + e.getMessage()); } return result; }
From source file:org.selman.tweetamo.PersistentStore.java
License:Apache License
public void add(Status status) throws Exception { try {//from ww w . ja v a 2 s. co m Map<String, AttributeValue> item = newItem(status); PutItemRequest putItemRequest = new PutItemRequest(TABLE_NAME, item); dynamoDB.putItem(putItemRequest); LOG.info("Stored status in Dynamo: " + status.getId()); } catch (Exception e) { handleException(e); } }
From source file:org.selman.tweetamo.PersistentStore.java
License:Apache License
private static Map<String, AttributeValue> newItem(Status status) { Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); item.put(COL_ID, new AttributeValue().withN(Long.toString(status.getId()))); item.put(COL_CREATEDAT, new AttributeValue().withN(Long.toString(status.getCreatedAt().getTime()))); if (status.getGeoLocation() != null) { item.put(COL_LAT, new AttributeValue().withN(Double.toString(status.getGeoLocation().getLatitude()))); item.put(COL_LONG, new AttributeValue().withN(Double.toString(status.getGeoLocation().getLongitude()))); }/* w w w. j ava 2 s. c o m*/ item.put(COL_SCREENNAME, new AttributeValue().withS(status.getUser().getScreenName())); item.put(COL_TEXT, new AttributeValue().withS(status.getText())); return item; }
From source file:org.smarttechie.servlet.SimpleStream.java
public void getStream(TwitterStream twitterStream, String[] parametros, final Session session)//,PrintStream out) { listener = new StatusListener() { @Override//from www. ja va2 s . c o m public void onException(Exception arg0) { // TODO Auto-generated method stub } @Override public void onDeletionNotice(StatusDeletionNotice arg0) { // TODO Auto-generated method stub } @Override public void onScrubGeo(long arg0, long arg1) { // TODO Auto-generated method stub } @Override public void onStatus(Status status) { Twitter twitter = new TwitterFactory().getInstance(); User user = status.getUser(); // gets Username String username = status.getUser().getScreenName(); System.out.println(""); String profileLocation = user.getLocation(); System.out.println(profileLocation); long tweetId = status.getId(); System.out.println(tweetId); String content = status.getText(); System.out.println(content + "\n"); JSONObject obj = new JSONObject(); obj.put("User", status.getUser().getScreenName()); obj.put("ProfileLocation", user.getLocation().replaceAll("'", "''")); obj.put("Id", status.getId()); obj.put("UserId", status.getUser().getId()); //obj.put("User", status.getUser()); obj.put("Message", status.getText().replaceAll("'", "''")); obj.put("CreatedAt", status.getCreatedAt().toString()); obj.put("CurrentUserRetweetId", status.getCurrentUserRetweetId()); //Get user retweeteed String otheruser; try { if (status.getCurrentUserRetweetId() != -1) { User user2 = twitter.showUser(status.getCurrentUserRetweetId()); otheruser = user2.getScreenName(); System.out.println("Other user: " + otheruser); } } catch (Exception ex) { System.out.println("ERROR: " + ex.getMessage().toString()); } obj.put("IsRetweet", status.isRetweet()); obj.put("IsRetweeted", status.isRetweeted()); obj.put("IsFavorited", status.isFavorited()); obj.put("InReplyToUserId", status.getInReplyToUserId()); //In reply to obj.put("InReplyToScreenName", status.getInReplyToScreenName()); obj.put("RetweetCount", status.getRetweetCount()); if (status.getGeoLocation() != null) { obj.put("GeoLocationLatitude", status.getGeoLocation().getLatitude()); obj.put("GeoLocationLongitude", status.getGeoLocation().getLongitude()); } JSONArray listHashtags = new JSONArray(); String hashtags = ""; for (HashtagEntity entity : status.getHashtagEntities()) { listHashtags.add(entity.getText()); hashtags += entity.getText() + ","; } if (!hashtags.isEmpty()) obj.put("HashtagEntities", hashtags.substring(0, hashtags.length() - 1)); if (status.getPlace() != null) { obj.put("PlaceCountry", status.getPlace().getCountry()); obj.put("PlaceFullName", status.getPlace().getFullName()); } obj.put("Source", status.getSource()); obj.put("IsPossiblySensitive", status.isPossiblySensitive()); obj.put("IsTruncated", status.isTruncated()); if (status.getScopes() != null) { JSONArray listScopes = new JSONArray(); String scopes = ""; for (String scope : status.getScopes().getPlaceIds()) { listScopes.add(scope); scopes += scope + ","; } if (!scopes.isEmpty()) obj.put("Scopes", scopes.substring(0, scopes.length() - 1)); } obj.put("QuotedStatusId", status.getQuotedStatusId()); JSONArray list = new JSONArray(); String contributors = ""; for (long id : status.getContributors()) { list.add(id); contributors += id + ","; } if (!contributors.isEmpty()) obj.put("Contributors", contributors.substring(0, contributors.length() - 1)); System.out.println("" + obj.toJSONString()); insertNodeNeo4j(obj); //out.println(obj.toJSONString()); String statement = "INSERT INTO TweetsClassification JSON '" + obj.toJSONString() + "';"; executeQuery(session, statement); } @Override public void onTrackLimitationNotice(int arg0) { // TODO Auto-generated method stub } @Override public void onStallWarning(StallWarning sw) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }; FilterQuery fq = new FilterQuery(); fq.track(parametros); twitterStream.addListener(listener); twitterStream.filter(fq); }
From source file:org.sociotech.communitymashup.source.twitter.TwitterSourceService.java
License:Open Source License
/** * Creates a content for the given tweet, adds it to the data set and sets * the author./*from w w w. j a va 2s .co m*/ * * @param author * Person corresponding to the twitter user which authored the * tweet * @param tweet * The tweet * @return The Content created from the tweet, null in error case. */ private Content createContentFromTweet(Person author, Status tweet) { if (tweet == null) { return null; } String tweetText = tweet.getText(); if (tweetText == null || tweetText.isEmpty()) { return null; } String ident = tweet.getId() + ""; if (this.getContentWithSourceIdent(ident) != null) { // status already created return null; } Content tweetContent = factory.createContent(); tweetContent.setStringValue(tweetText); tweetContent.setName(createTitleFromTwitterText(tweetText)); tweetContent = (Content) this.add(tweetContent, ident); if (tweetContent == null) { return null; } tweetContent.metaTag(TwitterTags.TWITTER); tweetContent.setCreated(tweet.getCreatedAt()); if (author != null) { tweetContent.setAuthor(author); } // and tag the status HashtagEntity[] hashtags = tweet.getHashtagEntities(); tagIOwithHashtags(tweetContent, hashtags); UserMentionEntity[] mentionedUsers = tweet.getUserMentionEntities(); if (mentionedUsers != null && mentionedUsers.length > 0 && source.isPropertyTrue(TwitterProperties.ADD_MENTIONED_PEOPLE_PROPERTY)) { for (int i = 0; i < mentionedUsers.length; i++) { Person mentionedPerson = getPersonForTwitterUserId(mentionedUsers[i].getId()); if (mentionedPerson == null) { continue; } tweetContent.addContributor(mentionedPerson); } } URLEntity[] urlEntities = tweet.getURLEntities(); if (urlEntities != null && urlEntities.length > 0 && source.isPropertyTrue(TwitterProperties.ADD_URL_ENTITIES_PROPERTY)) { for (int i = 0; i < urlEntities.length; i++) { String url = urlEntities[i].getURL(); if (url != null) { // attach url as website tweetContent.addWebSite(url); } } } // no more available // String language = tweet.getIsoLanguageCode(); // if(language != null && !language.isEmpty()) // { // // set in content // tweetContent.setLocale(language); // // set as meta tag // tweetContent.metaTag(language); // } // TODO check media entities // MediaEntity[] mediaEntities = twitterStatus.getMediaEntities(); // add location GeoLocation tweetLocation = tweet.getGeoLocation(); Place place = tweet.getPlace(); if (tweetLocation != null || place != null) { Location location = factory.createLocation(); if (place != null) { location.setStreet(place.getStreetAddress()); location.setCountry(place.getCountry()); location.setStringValue(place.getFullName()); } if (tweetLocation != null) { location.setLatitude(tweetLocation.getLatitude() + ""); location.setLongitude(tweetLocation.getLongitude() + ""); } location = (Location) this.add(location, "tloc_" + tweet.getId()); if (location != null) { location.metaTag(TwitterTags.TWITTER); tweetContent.extend(location); if (place != null) { location.metaTag(place.getCountryCode()); location.metaTag(place.getPlaceType()); } } } return tweetContent; }
From source file:org.springframework.integration.twitter.AbstractInboundTwitterStatusEndpointSupport.java
License:Apache License
@Override protected void markLastStatusId(Status statusId) { this.markerId = statusId.getId(); }
From source file:org.talend.spark.utils.twitter.TwitterUtil.java
License:Open Source License
public static Object parse(TwitterParameter parameter, Status status) { if (parameter == TwitterParameter.USERNAME) { return status.getUser().getName(); } else if (parameter == TwitterParameter.TEXT) { return status.getText(); } else if (parameter == TwitterParameter.SOURCE) { return status.getSource(); } else if (parameter == TwitterParameter.ACCESSLEVEL) { return status.getAccessLevel(); } else if (parameter == TwitterParameter.DATE) { return status.getCreatedAt(); } else if (parameter == TwitterParameter.ID) { return status.getId(); } else if (parameter == TwitterParameter.GEOLOCATION_LATITUDE) { return status.getGeoLocation().getLatitude(); } else if (parameter == TwitterParameter.GEOLOCATION_LONGITUDE) { return status.getGeoLocation().getLongitude(); } else if (parameter == TwitterParameter.HASHTAG) { String hashTags = ""; HashtagEntity[] hashTagArray = status.getHashtagEntities(); for (int i = 0; i < hashTagArray.length; i++) { if (hashTags.equals("")) { hashTags = hashTagArray[i].getText(); } else { hashTags = hashTags + "," + hashTagArray[i].getText(); }/*from w ww . j a v a2 s. c o m*/ } return hashTags; } return null; }