Example usage for twitter4j TwitterFactory TwitterFactory

List of usage examples for twitter4j TwitterFactory TwitterFactory

Introduction

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

Prototype

public TwitterFactory(String configTreePath) 

Source Link

Document

Creates a TwitterFactory with a specified config tree

Usage

From source file:com.oldterns.vilebot.handlers.user.UrlTweetAnnouncer.java

License:Open Source License

/**
 * Accesses the source of a HTML page and looks for a title element
 * /* w w w  . j av  a 2s .  c  o m*/
 * @param url http tweet String
 * @return String of text which represents the tweet.  Empty if error.
 */
private String scrapeURLHTMLTitle(String url) {
    String text = "";

    URL page;
    try {
        page = new URL(url);
    } catch (MalformedURLException x) {
        // System.err.format("scrapeURLHTMLTitle new URL error: %s%n", x);
        return text;
    }

    //split the url into pieces, change the request based on what we have
    String parts[] = url.split("/");
    int userPosition = 0;
    long tweetID = 0;
    for (int i = 0; i < parts.length; i++) {

        if (parts[i].toString().equals("twitter.com"))
            userPosition = i + 1;
        if (parts[i].toString().equals("status") || parts[i].toString().equals("statuses"))
            tweetID = Long.valueOf(parts[i + 1].toString()).longValue();
    }
    if (userPosition == 0)
        return text;
    else {
        try {
            String consumerKey = ""; //may be known as 'API key'
            String consumerSecret = ""; //may be known as 'API secret'
            String accessToken = ""; //may be known as 'Access token'
            String accessTokenSecret = ""; //may be known as 'Access token secret'
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
                    .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter = tf.getInstance();
            if (tweetID != 0) //tweet of the twitter.com/USERID/status/TWEETID variety
            {
                Status status = twitter.showStatus(tweetID);
                return (status.getUser().getName() + ": " + status.getText());
            } else //just the user is given, ie, twitter.com/USERID 
            {
                User user = twitter.showUser(parts[userPosition].toString());
                if (!user.getDescription().isEmpty()) //the user has a description
                    return ("Name: " + user.getName() + " | " + user.getDescription() + "\'\nLast Tweet: \'"
                            + user.getStatus().getText());
                else //the user doesn't have a description, don't print it
                    return ("Name: " + user.getName() + "\'\nLast Tweet: \'" + user.getStatus().getText());

            }
        } catch (TwitterException x) {
            return text;
        }
    }
}

From source file:com.ontotext.s4.TwitterVisualization.downloadTweets.SearchTweets.java

License:Open Source License

/**
 * Creates and configures Twitter client instance with provided credentials.
 * //from w  ww .  j ava  2  s . com
 * @return Twitter instance
 */
private Twitter ConfigurateTwitterAccount() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret)
            .setJSONStoreEnabled(true);
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    return twitter;
}

From source file:com.reyk.socialmedia.implementations.TwitterSB.java

@Override
public String connectToSocialMedia(String username) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey("a7QcplYaabjAy7Qw6WsyNAkwy")
            .setOAuthConsumerSecret("1xHSPlDU6eUp7YkkZL9oQioeQGuKiZHtwNuUCmTbARD2MoJLwV");
    twitter = new TwitterFactory(cb.build()).getInstance();
    try {/*from w  w  w .  ja v a  2s  .  co m*/
        token = twitter.getOAuthRequestToken();
    } catch (TwitterException ex) {
        return "Impossible to connect with Twitter";
    }
    return token.getAuthorizationURL();
}

From source file:com.reyk.socialmedia.implementations.TwitterSB.java

@Override
public void postComment(String username, String post) throws EJBException {
    try {/*from   w  ww .  j a  v  a 2s. c  o  m*/
        String fileName = "twitter-" + username + ".properties";
        File file = new File(fileName);
        OutputStream outputStream = null;
        Properties prop = new Properties();
        InputStream inputStream = null;

        try {
            if (file.exists()) {
                inputStream = new FileInputStream(file);
                prop.load(inputStream);
            } else {
                throw new EJBException("There is no configuration int Twitter for " + username);
            }

        } catch (IOException ioEx) {
            ioEx.printStackTrace();
            System.exit(-1);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ignore) {
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ignore) {
                }
            }
        }
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setOAuthConsumerKey("a7QcplYaabjAy7Qw6WsyNAkwy")
                .setOAuthConsumerSecret("1xHSPlDU6eUp7YkkZL9oQioeQGuKiZHtwNuUCmTbARD2MoJLwV")
                .setOAuthAccessToken(prop.getProperty("oauth.accessToken"))
                .setOAuthAccessTokenSecret(prop.getProperty("oauth.accessTokenSecret"));
        twitter = new TwitterFactory(cb.build()).getInstance();
        twitter.updateStatus(post);
    } catch (TwitterException e) {
        throw new EJBException("Error en el twitter sb al twittear", e);
    }
}

From source file:com.rowland.hashtrace.utility.Utility.java

License:Apache License

public static Twitter getTwitter() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
    cb.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
    cb.setOAuthAccessToken(Constants.TWITTER_ACCESS_TOKEN);
    cb.setOAuthAccessTokenSecret(Constants.TWITTER_TOKEN_SECRET).setHttpConnectionTimeout(100000);
    //cb.setUseSSL(true);

    /*/*from w w w  .j a  v a  2  s.c o m*/
     * if() { cb.setHttpProxyHost(httpProxyHost);
     * cb.setHttpProxyPort(httpProxyPort);
     * cb.setHttpProxyUser(httpProxyUser);
     * cb.setHttpProxyPassword(httpProxyPassword);
     *
     * }
     */

    return new TwitterFactory(cb.build()).getInstance();
}

From source file:com.rsinghal.cep.sample.twitter.TwitterBot.java

License:Apache License

public void start() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setJSONStoreEnabled(true);/* w w w  .j a  v a  2 s.  com*/
    twitter = new TwitterFactory(cb.build()).getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    userIdsToTrack = new long[trackTerms.size()];
    for (int i = 0; i < trackTerms.size(); i++) {
        try {
            String screenName = StringUtils.substringAfter(trackTerms.get(i), "@");
            logger.info("Fetching user ID for - " + screenName);
            userIdsToTrack[i] = twitter.showUser(screenName).getId();
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //   twitter = null;
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    twitterStream.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    twitterStream.addListener(listener2);
    // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    twitterStream.filter(new FilterQuery(0, userIdsToTrack, trackTerms.toArray(new String[trackTerms.size()])));

    jedis = new Jedis(redisHostname, redisPort, 1800);
    jedis.connect();
    System.out.println("start() ...");
    /*   // Create an appropriately sized blocking queue
       BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
               
       // create the endpoint
       DefaultStreamingEndpoint endpoint = createEndpoint();
       System.out.println("endpoint created ...");
            
       endpoint.stallWarnings(false);
            
       // create an authentication
       Authentication auth = new OAuth1(consumerKey, consumerSecret, accessToken, accessTokenSecret);
            
       // Create a new BasicClient. By default gzip is enabled.
       client = new ClientBuilder().name("sampleExampleClient")
    .hosts(Constants.STREAM_HOST).endpoint(endpoint)
    .authentication(auth)
    .processor(new StringDelimitedProcessor(queue)).build();
       System.out.println("client created ...");
            
       // Create an executor service which will spawn threads to do the actual
       // work of parsing the incoming messages and
       // calling the listeners on each message
       ExecutorService service = Executors
    .newFixedThreadPool(this.numberOfProcessingThreads);
            
       // Wrap our BasicClient with the twitter4j client
       Twitter4jStatusClient t4jClient = new Twitter4jStatusClient(client,
    queue, Lists.newArrayList(listener2), service);
            
       // Establish a connection
       t4jClient.connect();
               
       System.out.println("connection established ...");
            
       for (int threads = 0; threads < this.numberOfProcessingThreads; threads++) {
          // This must be called once per processing thread
          t4jClient.process();
          System.out.println("thread " + threads + " started ...");
            
       }*/
}

From source file:com.sinfonier.drains.TweetIt.java

License:Apache License

@Override
public void userexecute() {

    ConfigurationBuilder config = new ConfigurationBuilder();
    config.setOAuthConsumerKey(this.CONSUMER_KEY);
    config.setOAuthConsumerSecret(this.CONSUMER_SECRET);
    config.setOAuthAccessToken(this.ACCESS_TOKEN);
    config.setOAuthAccessTokenSecret(this.ACCESS_TOKEN_SECRET);
    config.setJSONStoreEnabled(true);/*from   w w w  .j av  a  2 s  .  c o m*/
    config.setIncludeEntitiesEnabled(true);
    try {
        TwitterFactory tf = new TwitterFactory(config.build());
        Twitter twitter = tf.getInstance();
        Status status = twitter.updateStatus(this.customText + " " + this.getField(this.fieldToTweet));
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
    } catch (TwitterException te) {
        te.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.smart.home.service.TwitterService.java

License:Open Source License

/**
 * Constructor for twitter service//  www. j av  a 2 s  . c o m
 *
 * @param apiKey      twitter API key
 * @param apiSecret   twitter API secret key
 * @param token       twitter access token
 * @param tokenSecret twitter access token secret
 */
public TwitterService(String apiKey, String apiSecret, String token, String tokenSecret) {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(apiKey).setOAuthConsumerSecret(apiSecret)
            .setOAuthAccessToken(token).setOAuthAccessTokenSecret(tokenSecret);
    TwitterFactory factory = new TwitterFactory(cb.build());
    twitter = factory.getInstance();
    twitter.directMessages();
}

From source file:com.social.solution.fragment.MyFragment.java

License:Apache License

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tweet_list, container, false);

    lastTimeStamp = System.currentTimeMillis();

    mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
    mSwipeLayout.setProgressViewOffset(false, 150, 200);
    mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override// w w  w  .  ja  v a 2 s . c  o m
        public void onRefresh() {
            long currentTimeStamp = System.currentTimeMillis();
            if ((currentTimeStamp - lastTimeStamp) / 1000 > 10) {
                System.out.println("load recent pranjal");
                LoadRecentTweets();
            }

        }
    });

    Activity parentActivity = getActivity();
    Fabric.with(getActivity(), new TweetUi());

    Bundle bd = getArguments();
    if (bd != null) {
        filterTweets = bd.getBoolean("filter");
        position = bd.getInt("position");
    } else {
        filterTweets = false;
        position = 0;
    }

    //Toast.makeText(this, "Filter : "+filterTweets+" Position : "+position, Toast.LENGTH_SHORT).show();
    System.out.println("Filter : " + filterTweets + " Position : " + position);

    linlaHeaderProgress = (LinearLayout) view.findViewById(R.id.linlaHeaderProgress);
    listView = (ObservableListView) view.findViewById(R.id.mylist);

    final EnumSet<RequestParameters.NativeAdAsset> desiredAssets = EnumSet.of(
            RequestParameters.NativeAdAsset.TITLE, RequestParameters.NativeAdAsset.TEXT,
            RequestParameters.NativeAdAsset.ICON_IMAGE, RequestParameters.NativeAdAsset.MAIN_IMAGE,
            RequestParameters.NativeAdAsset.CALL_TO_ACTION_TEXT);

    mRequestParameters = new RequestParameters.Builder()
            //.location(location)
            .keywords("food").desiredAssets(desiredAssets).build();

    setmydata(listView, inflater.inflate(R.layout.padding, listView, false));

    listView.setAdapter(tweetadapter);

    linlaHeaderProgress.setBackgroundColor(-1);
    linlaHeaderProgress.setVisibility(View.VISIBLE);

    if (parentActivity instanceof ObservableScrollViewCallbacks) {
        // Scroll to the specified position after layout
        Bundle args = getArguments();
        if (args != null && args.containsKey(ARG_INITIAL_POSITION)) {
            final int initialPosition = args.getInt(ARG_INITIAL_POSITION, 0);
            ScrollUtils.addOnGlobalLayoutListener(listView, new Runnable() {
                @Override
                public void run() {
                    // scrollTo() doesn't work, should use setSelection()
                    listView.setSelection(initialPosition);
                }
            });
        }

        // TouchInterceptionViewGroup should be a parent view other than ViewPager.
        // This is a workaround for the issue #117:
        // https://github.com/ksoichiro/Android-ObservableScrollView/issues/117
        listView.setTouchInterceptionViewGroup((ViewGroup) parentActivity.findViewById(R.id.root));

        listView.setScrollViewCallbacks((ObservableScrollViewCallbacks) parentActivity);
    }

    ConfigurationBuilder config = new ConfigurationBuilder().setOAuthConsumerKey(custkey)
            .setOAuthConsumerSecret(custsecret).setOAuthAccessToken(accesstoken)
            .setOAuthAccessTokenSecret(accesssecret);

    twitter1 = new TwitterFactory(config.build()).getInstance();
    tweetlist = new ArrayList<Tweet>();
    loadingTweets = new ArrayList<Tweet>();

    lastDisplayTweetId = Long.MAX_VALUE;
    firstDisplayTweetId = Long.MIN_VALUE;

    return view;
}

From source file:com.socialnetwork.abhishekchandale.snloginlib.twitter.TwitterSocialNetwork.java

License:Open Source License

private void initTwitterClient() {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(mConsumerKey);
    builder.setOAuthConsumerSecret(mConsumerSecret);

    String accessToken = mSharedPreferences.getString(SAVE_STATE_KEY_OAUTH_TOKEN, null);
    String accessTokenSecret = mSharedPreferences.getString(SAVE_STATE_KEY_OAUTH_SECRET, null);

    TwitterFactory factory = new TwitterFactory(builder.build());

    if (TextUtils.isEmpty(accessToken) && TextUtils.isEmpty(accessTokenSecret)) {
        mTwitter = factory.getInstance();
    } else {/*from  ww w  .  j a v a 2s.  co m*/
        mTwitter = factory.getInstance(new twitter4j.auth.AccessToken(accessToken, accessTokenSecret));
    }
}