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: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();
            }//w w  w. j av a 2 s  .  co  m
        }
        return hashTags;
    }
    return null;
}

From source file:org.tomitribe.chatterbox.twitter.adapter.TwitterResourceAdapter.java

License:Apache License

@Override
public void onStatus(final Status status) {

    final String username = status.getUser().getScreenName();
    final Response response = RESPONSE_MAP.remove(username);

    if (response != null && response.getDialog() != null) {
        // pull the response object from the map

        final Object dialog = response.getDialog();

        try {// w w  w.  j  a  va2s  .c  om
            final List<Method> matchingMethods = findMatchingMethods(dialog.getClass(), status);

            if (dialog.getClass().isAnnotationPresent(InvokeAllMatches.class)) {
                for (final Method method : matchingMethods) {
                    LOGGER.log(Level.INFO,
                            "Invoking method " + method.toString() + " for " + getNormalizedText(status));
                    final Object[] values = getValues(method, status);
                    final Object result = method.invoke(dialog, values);
                    processResponse(status, result);
                }
            } else {
                final Method method = matchingMethods.get(0);
                LOGGER.log(Level.INFO,
                        "Invoking method " + method.toString() + " for " + getNormalizedText(status));
                final Object[] values = getValues(method, status);
                final Object result = method.invoke(dialog, values);
                processResponse(status, result);
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            LOGGER.severe("Unable to call response object:" + e.getMessage());
            RESPONSE_MAP.remove(status.getUser().getScreenName());
        }
    } else {
        for (final EndpointTarget endpointTarget : this.targets.values()) {
            endpointTarget.invoke(status);
        }
    }
}

From source file:org.tomitribe.chatterbox.twitter.adapter.TwitterResourceAdapter.java

License:Apache License

private void processResponse(final Status status, final Object result) {
    if (Response.class.isInstance(result)) {
        final Response response = Response.class.cast(result);
        RESPONSE_MAP.put(status.getUser().getScreenName(), response);
        try {/*w ww. ja  v a 2s .  co  m*/
            replyTo(status, response.getMessage());
        } catch (TwitterException e) {
            LOGGER.severe("Unable to send tweet" + e.getMessage());
        }
    } else {
        RESPONSE_MAP.remove(status.getUser().getScreenName());
    }

    if (String.class.isInstance(result)) {
        RESPONSE_MAP.remove(status.getUser().getScreenName());
        try {
            replyTo(status, String.class.cast(result));
        } catch (TwitterException e) {
            LOGGER.severe("Unable to send tweet" + e.getMessage());
        }
    }
}

From source file:org.tomitribe.chatterbox.twitter.adapter.TwitterResourceAdapter.java

License:Apache License

private void replyTo(final Status status, final String reply, final boolean prefix) throws TwitterException {
    final String message;

    if (prefix) {
        message = "@" + status.getUser().getScreenName() + " " + reply;
    } else {/*from   w  w w. j  a va  2  s  .  com*/
        message = reply;
    }

    final StatusUpdate statusUpdate = new StatusUpdate(message);
    statusUpdate.setInReplyToStatusId(status.getId());
    twitter.updateStatus(statusUpdate);
}

From source file:org.tomitribe.chatterbox.twitter.adapter.TwitterResourceAdapter.java

License:Apache License

private static boolean filterUser(final Status status, final Method m) {
    return !m.isAnnotationPresent(User.class) || "".equals(m.getAnnotation(User.class).value())
            || templateMatches(m.getAnnotation(User.class).value(), status.getUser().getScreenName());
}

From source file:org.tomitribe.chatterbox.twitter.adapter.TwitterResourceAdapter.java

License:Apache License

public static Object[] getValues(final Method method, final Status status) {

    if (method == null) {
        return null;
    }//from ww  w.  j ava  2 s .  c  o m

    final Parameter[] parameters = method.getParameters();
    if (parameters.length == 0) {
        return new Object[0];
    }

    final Template tweetTemplate = getTemplate(method.getAnnotation(Tweet.class));
    final Map<String, List<String>> tweetParamValues = new HashMap<>();
    if (tweetTemplate != null) {
        tweetTemplate.match(getNormalizedText(status), tweetParamValues);
    }

    final Template userTemplate = getTemplate(method.getAnnotation(User.class));
    final Map<String, List<String>> userParamValues = new HashMap<>();
    if (userTemplate != null) {
        userTemplate.match(status.getUser().getScreenName(), userParamValues);
    }

    final Object[] values = new Object[parameters.length];

    for (int i = 0; i < parameters.length; i++) {
        final Parameter parameter = parameters[i];

        values[i] = null;

        if (parameter.isAnnotationPresent(TweetParam.class)) {
            final TweetParam tweetParam = parameter.getAnnotation(TweetParam.class);
            if (tweetParam.value() == null || tweetParam.value().length() == 0) {
                values[i] = Converter.convert(getNormalizedText(status), parameter.getType(), null);
            } else {
                final List<String> paramValues = tweetParamValues.get(tweetParam.value());
                final String paramValue = paramValues == null || paramValues.size() == 0 ? null
                        : paramValues.get(0);
                values[i] = Converter.convert(paramValue, parameter.getType(), null);
            }
        }

        if (parameter.isAnnotationPresent(UserParam.class)) {
            final UserParam userParam = parameter.getAnnotation(UserParam.class);
            if (userParam.value() == null || userParam.value().length() == 0) {
                values[i] = Converter.convert(status.getUser().getScreenName(), parameter.getType(), null);
            } else {
                final List<String> paramValues = userParamValues.get(userParam.value());
                final String paramValue = paramValues == null || paramValues.size() == 0 ? null
                        : paramValues.get(0);
                values[i] = Converter.convert(paramValue, parameter.getType(), null);
            }
        }
    }

    return values;
}

From source file:org.tweetalib.android.model.TwitterStatus.java

License:Apache License

public TwitterStatus(Status status) {
    User statusUser = status.getUser();

    mCreatedAt = status.getCreatedAt();//from w w w.  jav a 2s  . co  m
    mId = status.getId();
    if (status.getInReplyToStatusId() != -1) {
        mInReplyToStatusId = status.getInReplyToStatusId();
    }
    if (status.getInReplyToUserId() != -1) {
        mInReplyToUserId = status.getInReplyToUserId();
    }
    mInReplyToUserScreenName = status.getInReplyToScreenName();
    mIsFavorited = status.isFavorited();
    mIsRetweet = status.isRetweet();
    mIsRetweetedByMe = status.isRetweetedByMe();

    mSource = TwitterUtil.stripMarkup(status.getSource());

    if (statusUser != null) {
        mUserId = statusUser.getId();
        mUserName = statusUser.getName();
        mUserScreenName = statusUser.getScreenName();
    }

    mMediaEntity = TwitterMediaEntity.createMediaEntity(status);

    boolean useDefaultAuthor = true;
    if (mIsRetweet) {
        if (status.getRetweetedStatus() != null && status.getRetweetedStatus().getUser() != null) {
            SetProfileImagesFromUser(new TwitterUser(status.getRetweetedStatus().getUser()));
        }
        mOriginalRetweetId = status.getRetweetedStatus().getId();

        // You'd think this check wasn't necessary, but apparently not...
        UserMentionEntity[] userMentions = status.getUserMentionEntities();
        if (userMentions != null && userMentions.length > 0) {
            useDefaultAuthor = false;
            UserMentionEntity authorMentionEntity = status.getUserMentionEntities()[0];
            mAuthorId = authorMentionEntity.getId();
            mAuthorName = authorMentionEntity.getName();
            mAuthorScreenName = authorMentionEntity.getScreenName();

            Status retweetedStatus = status.getRetweetedStatus();
            mStatus = retweetedStatus.getText();
            setStatusMarkup(retweetedStatus);
            mRetweetCount = retweetedStatus.getRetweetCount();
            mUserMentions = TwitterUtil.getUserMentions(retweetedStatus.getUserMentionEntities());
            mIsRetweetedByMe = retweetedStatus.isRetweetedByMe();
        }
    } else {
        if (statusUser != null) {
            SetProfileImagesFromUser(new TwitterUser(statusUser));
        }
    }

    if (useDefaultAuthor) {
        if (statusUser != null) {
            mAuthorId = statusUser.getId();
        }
        mStatus = status.getText();
        setStatusMarkup(status);
        mRetweetCount = status.getRetweetCount();
        mUserMentions = TwitterUtil.getUserMentions(status.getUserMentionEntities());
    }

    /*
     * if (status.getId() == 171546910249852928L) { mStatus =
     * "<a href=\"http://a.com\">@chrismlacy</a> You've been working on Tweet Lanes for ages. Is it done yet?"
     * ; mStatusMarkup =
     * "<a href=\"http://a.com\">@chrismlacy</a> You've been working on Tweet Lanes for ages. Is it done yet?"
     * ; mAuthorScreenName = "emmarclarke"; mStatusMarkup = mStatus; } else
     * if (status.getId() == 171444098698457089L) { mStatus =
     * "<a href=\"http://a.com\">@chrismlacy</a> How's that app of yours coming along?"
     * ; mStatusMarkup =
     * "<a href=\"http://a.com\">@chrismlacy</a> How's that app of yours coming along?"
     * ; mStatusMarkup = mStatus; }
     */
}

From source file:org.tweetalib.android.model.TwitterStatuses.java

License:Apache License

public void add(ResponseList<twitter4j.Status> statuses, AddUserCallback addUserCallback) {

    TwitterStatus firstItem = size() > 0 ? get(0) : null;
    int addCount = 0;

    boolean stillMore = true;
    TwitterStatus lastAddedStatus = null;

    mGetNewStatusesMaxId = null;// www. j av a 2  s . c  o  m

    for (Status status : statuses) {
        if (firstItem != null && status.getId() == firstItem.mId) {
            stillMore = false;
            break;
        }

        lastAddedStatus = new TwitterStatus(status);
        add(lastAddedStatus);

        if (addUserCallback != null) {
            addUserCallback.addUser(status.getUser());
            if (status.isRetweet()) {
                Status retweetedStatus = status.getRetweetedStatus();
                if (retweetedStatus != null) {
                    addUserCallback.addUser(retweetedStatus.getUser());
                }
            }
        }

        addCount += 1;
    }

    if (stillMore && lastAddedStatus != null) {
        mGetNewStatusesMaxId = lastAddedStatus.mId;
    }

    if (addCount > 0) {
        sort();
    }
}

From source file:org.unimonk.flume.source.twitter.TwitterSource.java

License:Apache License

@Override
public void start() {

    final ChannelProcessor channel = getChannelProcessor();

    StatusListener listener = new StatusListener() {
        @Override//from  w ww  .ja v  a 2 s .co m
        public void onStatus(Status status) {

            Tweet tweet = new Tweet();
            tweet.setId(status.getId());
            tweet.setUserId(status.getUser().getId());
            tweet.setLatitude(status.getGeoLocation().getLatitude());
            tweet.setLongitude(status.getGeoLocation().getLongitude());
            tweet.setText(status.getText());
            tweet.setCreatedAt(new Timestamp(status.getCreatedAt().getTime()));

            Event event = EventBuilder.withBody(tweet.toString(), Charsets.UTF_8);
            sourceCounter.incrementAppendReceivedCount();
            try {
                channel.processEvent(event);
                sourceCounter.incrementEventAcceptedCount();
            } catch (ChannelException ex) {
                logger.error("In Twitter source {} : Unable to process event due to exception {}.", getName(),
                        ex);

            }
        }

        // This listener will ignore everything except for new tweets
        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
        }

        @Override
        public void onException(Exception ex) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }
    };

    logger.debug("Setting up Twitter sample stream using consumer key {} and" + " access token {}",
            new String[] { consumerKey, accessToken });

    twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    if (keywords.length == 0) {
        logger.debug("Starting up Twitter sampling...");
        twitterStream.sample();
    } else {
        logger.debug("Starting up Twitter filtering...");
        FilterQuery query = new FilterQuery().track(keywords);
        twitterStream.filter(query);
    }
    this.sourceCounter.start();
    super.start();
}

From source file:org.wandora.application.tools.extractors.twitter.AbstractTwitterExtractor.java

License:Open Source License

public Topic reifyTweet(Status t, TopicMap tm) {
    Topic tweetTopic = null;/*from   www. j a  va  2  s  .  c om*/
    try {
        long tId = t.getId();
        String msg = t.getText();
        User user = t.getUser();

        if (user == null) {
            tweetTopic = reifyTweet(tId, null, msg, tm);
        }

        else {
            String userScreenName = user.getScreenName();

            tweetTopic = reifyTweet(tId, userScreenName, msg, tm);

            Topic userTopic = reifyTwitterUser(user, tm);

            if (tweetTopic != null && userTopic != null) {
                Association a = tm.createAssociation(getTwitterFromUserType(tm));
                a.addPlayer(tweetTopic, getTweetType(tm));
                a.addPlayer(userTopic, getTwitterUserType(tm));
            }
        }

        /*
        String toUser = t.getToUser();
        if(toUser != null) {
        long toUid = t.getToUserId();       
        Topic toUserTopic = reifyTwitterUser(toUser, toUid, tm);
        if(tweetTopic != null && toUserTopic != null) {
            Association a = tm.createAssociation(getTwitterToUserType(tm));
            a.addPlayer(tweetTopic, getTweetType(tm));
            a.addPlayer(toUserTopic, getTwitterUserType(tm));
        }
        }
        */

        Date d = t.getCreatedAt();
        if (tweetTopic != null && d != null) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = df.format(d);
            tweetTopic.setData(getTweetDateType(tm), TMBox.getLangTopic(tweetTopic, DEFAULT_LANG), dateStr);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            dateStr = sdf.format(d);
            Topic dateTopic = ExtractHelper.getOrCreateTopic(DATE_SI_BODY + dateStr, dateStr,
                    getTweetDateType(tm), tm);
            if (dateTopic != null) {
                Association a = tm.createAssociation(getTweetDateType(tm));
                a.addPlayer(tweetTopic, getTweetType(tm));
                a.addPlayer(dateTopic, getTweetDateType(tm));
            }
        }

        /*
        String l = t.getIsoLanguageCode();
        if(l != null) {
        Topic tweetLangTopic = TMBox.getLangTopic(tweetTopic, l);
        if(tweetLangTopic != null) {
            Association a = tm.createAssociation(getTweetLangType(tm));
            a.addPlayer(tweetTopic, getTweetType(tm));
            a.addPlayer(tweetLangTopic, getTweetLangType(tm));
        }
        }
        */

        GeoLocation geo = t.getGeoLocation();
        if (geo != null) {
            double lat = geo.getLatitude();
            double lon = geo.getLongitude();
            String geoLocStr = lat + "," + lon;
            tweetTopic.setData(getTweetGeoLocationType(tm), TMBox.getLangTopic(tweetTopic, DEFAULT_LANG),
                    geoLocStr);
        }

        HashtagEntity[] entities = t.getHashtagEntities();
        if (entities != null && entities.length > 0) {
            for (int i = 0; i < entities.length; i++) {
                Topic entityTopic = reifyHashtagEntity(entities[i], tm);
                if (entityTopic != null) {
                    Association a = tm.createAssociation(getHashtagType(tm));
                    a.addPlayer(tweetTopic, getTweetType(tm));
                    a.addPlayer(entityTopic, getHashtagType(tm));
                }
            }
        }

        MediaEntity[] mediaEntities = t.getMediaEntities();
        if (mediaEntities != null && mediaEntities.length > 0) {
            for (int i = 0; i < mediaEntities.length; i++) {
                Topic entityTopic = reifyMediaEntity(mediaEntities[i], tm);
                if (entityTopic != null) {
                    Association a = tm.createAssociation(getMediaEntityType(tm));
                    a.addPlayer(tweetTopic, getTweetType(tm));
                    a.addPlayer(entityTopic, getMediaEntityType(tm));
                }
            }
        }

        URLEntity[] urlEntities = t.getURLEntities();
        if (urlEntities != null && urlEntities.length > 0) {
            for (int i = 0; i < urlEntities.length; i++) {
                Topic entityTopic = reifyUrlEntity(urlEntities[i], tm);
                if (entityTopic != null) {
                    Association a = tm.createAssociation(getURLEntityType(tm));
                    a.addPlayer(tweetTopic, getTweetType(tm));
                    a.addPlayer(entityTopic, getURLEntityType(tm));
                }
            }
        }
    } catch (Exception e) {
        log(e);
    }
    return tweetTopic;
}