com.happy_coding.viralo.twitter.SmartPoster.java Source code

Java tutorial

Introduction

Here is the source code for com.happy_coding.viralo.twitter.SmartPoster.java

Source

/**
 * Copyright (C) 2012 Happy Coding <contact@happy-coding.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.happy_coding.viralo.twitter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Trend;
import twitter4j.Trends;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Smart Poster.
 */
public class SmartPoster {

    /**
     * Location WOEID for trend retrieval. here US.
     */
    public static final int TREND_WOEID = 2450022;
    public static final int TWEETS_PER_PAGE = 30;
    public static final int MAX_TWEET_LENGTH = 140;

    /**
     * Logger.
     */
    private Logger logger;

    public SmartPoster() {
        logger = LoggerFactory.getLogger(getClass());
    }

    /**
     * Returns some kind of trends, which is worth writing about.
     *
     * @return
     */
    public String retrieveTrend() {

        Twitter twitter = new TwitterFactory().getInstance();

        try {
            Trends trends = twitter.getLocationTrends(TREND_WOEID);
            Trend[] trendsArr = trends.getTrends();
            logger.debug("size: " + trendsArr.length);

            int lengthCheck = 0;
            String matchedtrend = "";
            for (int i = 0; i < trendsArr.length; i++) {

                logger.debug("Trend: " + trendsArr[i].getName());

                if (trendsArr[i].getName().length() >= lengthCheck) {
                    matchedtrend = trendsArr[i].getName();
                    lengthCheck = trendsArr[i].getName().length();
                }
            }

            return matchedtrend;

        } catch (TwitterException e) {
            logger.error("can't retrieve trend", e);
            return null;
        }
    }

    /**
     * Returns tweet for keywords.
     *
     * @param keywords
     * @return
     */
    public ContactTweet getTweet(String keywords) {

        Query query = new Query(keywords);
        query.setPage(1);
        query.setRpp(TWEETS_PER_PAGE);

        Twitter twitter = new TwitterFactory().getInstance();

        QueryResult result = null;

        try {
            result = twitter.search(query);
        } catch (TwitterException e) {
            logger.error("can't load tweet", e);
            return null;
        }

        /*
        just get the first tweet.
         */
        Tweet firstTweet = result.getTweets().get(0);

        Contact contact = new Contact(firstTweet.getFromUserId());
        contact.setName(firstTweet.getFromUser());

        ContactTweet contactTweet = new ContactTweet(contact, firstTweet.getText());

        return contactTweet;
    }

    /**
     * Posts a tweet.
     *
     * @param tweet
     */
    public Boolean postTweet(String tweet) {

        Twitter twitter = new TwitterFactory().getInstance();
        try {
            if (tweet.length() > MAX_TWEET_LENGTH) {
                tweet = tweet.substring(0, MAX_TWEET_LENGTH);
            }

            twitter.updateStatus(tweet);
            return Boolean.TRUE;
        } catch (TwitterException e) {
            logger.error("can't post tweet", e);
            return Boolean.FALSE;
        }
    }

    /**
     * Returns mentions for user.
     *
     * @return
     */
    public List<ContactTweet> getMentions() {

        Twitter twitter = new TwitterFactory().getInstance();

        try {

            ResponseList<Status> mentions = twitter.getMentions();
            List<ContactTweet> contactTweets = new ArrayList<ContactTweet>();

            for (Status status : mentions) {

                Contact contact = new Contact();
                contact.setUid(status.getUser().getId());
                contact.setName(status.getUser().getScreenName());

                ContactTweet contactTweet = new ContactTweet(contact, status.getText());
                contactTweet.setTweetID(status.getId());
                contactTweets.add(contactTweet);
            }
            return contactTweets;

        } catch (TwitterException e) {
            logger.error("can't load mentions", e);
            return null;
        }
    }
}