Example usage for twitter4j Status getUser

List of usage examples for twitter4j Status getUser

Introduction

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

Prototype

User getUser();

Source Link

Document

Return the user associated with the status.
This can be null if the instance is from User.getStatus().

Usage

From source file:com.appspot.bitlyminous.handler.twitter.SearchHandler.java

License:Apache License

@Override
public StatusUpdate execute(Status tweet) {
    GoogleSearchQueryFactory factory = GoogleSearchQueryFactory
            .newInstance(ApplicationConstants.GOOGLE_API_KEY);
    WebSearchQuery query = factory.newWebSearchQuery();
    query.setReferrer(ApplicationConstants.GOOGLE_API_REFERER);
    PagedList<WebResult> response = query.withQuery(getMentionText(tweet)).list();
    if (response.isEmpty()) {
        return null;
    } else {// www . java 2  s  . c  o  m
        StatusUpdate update = new StatusUpdate(
                "@" + tweet.getUser().getScreenName() + " " + buildStatus(response.get(0)));
        update.setInReplyToStatusId(tweet.getId());
        return update;
    }
}

From source file:com.appspot.bitlyminous.handler.twitter.SendRelatedUrlsHandler.java

License:Apache License

@Override
public StatusUpdate execute(Status tweet) {
    try {//w ww.j  a v a 2s  . co  m
        DeliciousGateway deliciousGateway = getDeliciousGateway(context.getVersion());
        DiggGateway diggGateway = getDiggGateway();
        List<Url> urls = context.getUrls();
        for (Url entity : urls) {
            WebSearchQuery googleQuery = getGoogleWebSearchQuery();
            googleQuery.withRelatedSite(entity.getUrl());
            List<Url> relatedUrls = new ArrayList<Url>();
            List<String> tags = entity.getTags();
            if (!tags.isEmpty()) {
                for (String tag : tags) {
                    try {
                        relatedUrls.addAll(deliciousGateway.getPopularUrls(tag));
                        relatedUrls.addAll(convertToUrls(diggGateway.getPopularStories(tag, 5)));
                    } catch (Exception e) {
                        logger.log(Level.WARNING, "Error while getting related urls.", e);
                    }
                }
                relatedUrls.addAll(convertToUrls(googleQuery.withQuery(createQuery(tags)).list()));
                relatedUrls = getBestMatches(entity, relatedUrls, 2);
            }

            if (!relatedUrls.isEmpty()) {
                StatusUpdate reply = new StatusUpdate(
                        "@" + tweet.getUser().getScreenName() + " " + buildStatus(relatedUrls));
                reply.setInReplyToStatusId(tweet.getId());
                return reply;
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error while sending related urls.", e);
    }

    return null;
}

From source file:com.appspot.bitlyminous.handler.twitter.SubscribeHandler.java

License:Apache License

@Override
public StatusUpdate execute(Status tweet) {
    try {/*w  w  w  .  ja v a 2 s  .co m*/
        User user = context.getUser();
        if (user == null) {
            user = getUserByScreenName(tweet.getUser().getScreenName());
            context.setUser(user);
        }
        if (user != null) {
            if (user.getTags() == null) {
                user.setTags(new Tags());
            }

            List<Tag> tags = user.getTags().getTag();
            String[] mentionTags = getMentionText(tweet).split("\\s+");
            for (String tag : mentionTags) {
                if (!isExisting(tags, tag)) {
                    Tag obj = new Tag();
                    obj.setTag(tag);
                    obj.setCount(5L);
                    tags.add(obj);
                }
            }
            user.setTags(user.getTags());
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error while subscribing tags.", e);
    }
    return null;
}

From source file:com.appspot.bitlyminous.handler.twitter.TweetForMeHandler.java

License:Apache License

@Override
public StatusUpdate execute(Status tweet) {
    try {//from w  w w  .  j av a  2s .  co  m
        User user = context.getUser();
        if (user == null) {
            user = getUserByScreenName(tweet.getUser().getScreenName());
            context.setUser(user);
        }
        if (user == null || user.getTwitterToken() == null || user.getTwitterSecret() == null) {
            StatusUpdate reply = new StatusUpdate(
                    ApplicationResources.getLocalizedString("com.appspot.bitlyminous.message.notAuthenticated",
                            new String[] { "@" + tweet.getUser().getScreenName(), "Twitter",
                                    shortenUrl(ApplicationConstants.TWITTER_CALLBACK_URL) }));
            reply.setInReplyToStatusId(tweet.getId());
            return reply;
        } else {
            Twitter twitter = getTwitterClient(user.getTwitterToken().getValue(),
                    user.getTwitterSecret().getValue());
            String status = buildStatus(user.getUrls(), user.getTags());
            if (status != null) {
                StatusUpdate reply = new StatusUpdate(status);
                reply.setInReplyToStatusId(tweet.getId());
                twitter.updateStatus(reply);
            }
            return null;
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error while tweeting on behalf of user.", e);
    }
    return null;
}

From source file:com.appspot.bitlyminous.service.impl.TwitterServiceImpl.java

License:Apache License

public void handleFriendsTimeline() {
    try {/*from   ww  w . j a va2s  . c  o  m*/
        Version version = getCurrentVersion();
        Twitter twitter = getTwitterClient();
        List<Status> homeTimeline = twitter.getFriendsTimeline(new Paging(version.getLastHomeTweetId()));
        long lastTweetId = 0L;
        for (Status status : homeTimeline) {
            if (status.getId() > lastTweetId) {
                lastTweetId = status.getId();
            }
            if (!ApplicationConstants.TWITTER_SCREEN_NAME.equalsIgnoreCase(status.getUser().getScreenName())) {
                TwitterContext context = new TwitterContext();
                context.setVersion(version);
                for (TwitterHandler command : getTimelineHandlers(context)) {
                    StatusUpdate reply = command.execute(status);
                    if (reply != null) {
                        twitter.updateStatus(reply);
                    }
                }
                saveUser(context.getUser());
            }
        }
        if (lastTweetId > version.getLastHomeTweetId()) {
            version.setLastHomeTweetId(lastTweetId);
            saveVersion(version);
        }
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:com.aremaitch.codestock2010.repository.TweetObj.java

License:Apache License

public static TweetObj createInstance(Status status) {
    TweetObj to = new TweetObj();
    to.setId(status.getId());/*from   w  w  w  .j av a 2s .c o  m*/
    to.setText(status.getText());
    to.setToUserId(status.getInReplyToUserId());
    to.setToUser(status.getInReplyToScreenName());
    if (status.getUser() != null) {
        to.setFromUser(status.getUser().getScreenName());
        to.setFromUserId(status.getUser().getId());
        to.setIsoLanguageCode(status.getUser().getLang());
        to.setProfileImageUrl(status.getUser().getProfileBackgroundImageUrl());
    }
    to.setSource(status.getSource());
    to.setCreatedAt(status.getCreatedAt());
    if (status.getGeoLocation() != null) {
        to.setLatitude(status.getGeoLocation().getLatitude());
        to.setLongitude(status.getGeoLocation().getLongitude());
    }
    return to;

}

From source file:com.arihant15.ActionServlet.java

@RequestMapping("/getTimeline.arihant15")
public void doTimeline(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {/*from  w  w w.  j a  va 2  s  .  com*/
        Twitter twitter = (Twitter) req.getSession().getAttribute("t");
        List<Status> statuses = twitter.getHomeTimeline();
        for (Status status : statuses) {
            (res.getWriter()).println(status.getUser().getScreenName() + ":" + status.getText() + "\n");
        }
    } catch (Exception e) {
        (res.getWriter()).println(e);
    }
}

From source file:com.babatunde.twittergoogle.Utility.java

public void postToGoogle(PlusDomains s, String id, String hashtag) {
    try {/*from  ww w.jav a2  s. c o  m*/
        final PlusDomains serve = s;
        final String circleID = id;
        listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                String msg = status.getUser().getName() + " - " + "@" + status.getUser().getScreenName() + " - "
                        + status.getText();
                System.out.println(msg);
                //Create a list of ACL entries
                if (serve != null && (!circleID.isEmpty() || (circleID != null))) {
                    PlusDomainsAclentryResource resource = new PlusDomainsAclentryResource();
                    resource.setType("domain").setType("circle").setId(circleID);

                    //Get Emails of people in the circle.
                    List<PlusDomainsAclentryResource> aclEntries = new ArrayList<PlusDomainsAclentryResource>();
                    aclEntries.add(resource);

                    Acl acl = new Acl();

                    acl.setItems(aclEntries);
                    acl.setDomainRestricted(true); // Required, this does the domain restriction

                    // Create a new activity object
                    Activity activity = new Activity()
                            .setObject(new Activity.PlusDomainsObject().setOriginalContent(msg)).setAccess(acl);
                    try {
                        // Execute the API request, which calls `activities.insert` for the logged in user
                        activity = serve.activities().insert("me", activity).execute();
                    } catch (IOException ex) {
                        Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }

            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
                System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
            }

            @Override
            public void onScrubGeo(long userId, long upToStatusId) {
                System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
            }

            @Override
            public void onStallWarning(StallWarning warning) {
                System.out.println("Got stall warning:" + warning);
            }

            @Override
            public void onException(Exception ex) {
                ex.printStackTrace();
            }

        };
    } catch (Exception e) {
    }

    TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();

    twitterStream.addListener(listener);
    String str[] = { hashtag };
    twitterStream.shutdown();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
    }
    twitterStream.filter(new FilterQuery().track(str));

}

From source file:com.cafeform.iumfs.twitterfs.files.AbstractTimelineFile.java

License:Apache License

/**
 * Convert Status to formated text./*from   ww w. j  a v a 2 s.  com*/
 *
 * @param status Status
 * @return formatted text
 */
public static String statusToFormattedString(Status status) {
    // Add user name time..
    StringBuilder sb = new StringBuilder();
    Date createdDate = status.getCreatedAt();
    SimpleDateFormat simpleFormat = new SimpleDateFormat("MM/dd HH:mm:ss");

    sb.append(simpleFormat.format(createdDate));
    sb.append(" ");
    sb.append(status.getUser().getScreenName());
    sb.append("[");
    sb.append(status.getUser().getName());
    sb.append("] \n");
    sb.append(status.getText());
    sb.append("\n\n");
    return sb.toString();
}

From source file:com.chimpler.example.TwitterStatusProducer.java

License:Apache License

public synchronized void startSample(String username, String password) {
    if (twitterStream != null) {
        return;//w w w.j  a v  a  2s .  c  o  m
    }
    TwitterStreamFactory factory = new TwitterStreamFactory(
            new ConfigurationBuilder().setUser(username).setPassword(password).build());
    twitterStream = factory.getInstance();
    twitterStream.addListener(new StatusAdapter() {
        public void onStatus(Status status) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", "OK");
            map.put("createdAt", status.getCreatedAt().toString());
            map.put("username", status.getUser().getName());
            map.put("profileImageUrl", status.getUser().getMiniProfileImageURL());
            map.put("text", status.getText());
            cometTwitterService.publishMessage(map, Long.toString(status.getId()));
        }

        @Override
        public void onException(Exception ex) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", "ERR");
            map.put("text", ex.getMessage());
            cometTwitterService.publishMessage(map, "-1");
            stopSample();
        }
    });
    logger.log(Level.INFO, "Starting listening to twitter sample");
    twitterStream.sample();
}