Example usage for twitter4j.auth AccessToken AccessToken

List of usage examples for twitter4j.auth AccessToken AccessToken

Introduction

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

Prototype

public AccessToken(String token, String tokenSecret) 

Source Link

Usage

From source file:controllers.modules.CorpusModule.java

License:Open Source License

public static Result update(UUID corpus) {
    OpinionCorpus corpusObj = null;//w  w w  . j  a  va 2  s  .  c o  m
    if (corpus != null) {
        corpusObj = fetchResource(corpus, OpinionCorpus.class);
    }
    OpinionCorpusFactory corpusFactory = null;

    MultipartFormData formData = request().body().asMultipartFormData();
    if (formData != null) {
        // if we have a multi-part form with a file.
        if (formData.getFiles() != null) {
            // get either the file named "file" or the first one.
            FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"),
                    Iterables.getFirst(formData.getFiles(), null));
            if (filePart != null) {
                corpusFactory = (OpinionCorpusFactory) new OpinionCorpusFactory().setFile(filePart.getFile())
                        .setFormat(FilenameUtils.getExtension(filePart.getFilename()));
            }
        }
    } else {
        // otherwise try as a json body.
        JsonNode json = request().body().asJson();
        if (json != null) {
            OpinionCorpusFactoryModel optionsVM = Json.fromJson(json, OpinionCorpusFactoryModel.class);
            if (optionsVM != null) {
                corpusFactory = optionsVM.toFactory();
            } else {
                throw new IllegalArgumentException();
            }

            if (optionsVM.grabbers != null) {
                if (optionsVM.grabbers.twitter != null) {
                    if (StringUtils.isNotBlank(optionsVM.grabbers.twitter.query)) {
                        TwitterFactory tFactory = new TwitterFactory();
                        Twitter twitter = tFactory.getInstance();
                        twitter.setOAuthConsumer(
                                Play.application().configuration().getString("twitter4j.oauth.consumerKey"),
                                Play.application().configuration().getString("twitter4j.oauth.consumerSecret"));
                        twitter.setOAuthAccessToken(new AccessToken(
                                Play.application().configuration().getString("twitter4j.oauth.accessToken"),
                                Play.application().configuration()
                                        .getString("twitter4j.oauth.accessTokenSecret")));

                        Query query = new Query(optionsVM.grabbers.twitter.query);
                        query.count(ObjectUtils.defaultIfNull(optionsVM.grabbers.twitter.limit, 10));
                        query.resultType(Query.RECENT);
                        if (StringUtils.isNotEmpty(corpusFactory.getLanguage())) {
                            query.lang(corpusFactory.getLanguage());
                        } else if (corpusObj != null) {
                            query.lang(corpusObj.getLanguage());
                        }

                        QueryResult qr;
                        try {
                            qr = twitter.search(query);
                        } catch (TwitterException e) {
                            throw new IllegalArgumentException();
                        }

                        StringBuilder tweets = new StringBuilder();
                        for (twitter4j.Status status : qr.getTweets()) {
                            // quote for csv, normalize space, and remove higher unicode characters. 
                            String text = StringEscapeUtils.escapeCsv(StringUtils
                                    .normalizeSpace(status.getText().replaceAll("[^\\u0000-\uFFFF]", "")));
                            tweets.append(text + System.lineSeparator());
                        }

                        corpusFactory.setContent(tweets.toString());
                        corpusFactory.setFormat("txt");
                    }
                }
            }
        } else {
            // if not json, then just create empty.
            corpusFactory = new OpinionCorpusFactory();
        }
    }

    if (corpusFactory == null) {
        throw new IllegalArgumentException();
    }

    if (corpus == null && StringUtils.isEmpty(corpusFactory.getTitle())) {
        corpusFactory.setTitle("Untitled corpus");
    }

    corpusFactory.setOwnerId(SessionedAction.getUsername(ctx())).setExistingId(corpus).setEm(em());

    DocumentCorpusModel corpusVM = null;
    corpusObj = corpusFactory.create();
    if (!em().contains(corpusObj)) {
        em().persist(corpusObj);

        corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
        corpusVM.populateSize(em(), corpusObj);
        return created(corpusVM.asJson());
    }

    for (PersistentObject obj : corpusObj.getDocuments()) {
        if (em().contains(obj)) {
            em().merge(obj);
        } else {
            em().persist(obj);
        }
    }
    em().merge(corpusObj);

    corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
    corpusVM.populateSize(em(), corpusObj);
    return ok(corpusVM.asJson());
}

From source file:de.fhb.twitalyse.spout.TwitterStreamSpout.java

License:Open Source License

@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    this.collector = collector;

    // enable JSONStore
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setJSONStoreEnabled(true);/*  w w w . j  a  v  a 2 s. c  om*/

    TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory(cb.build());
    twitterStream = twitterStreamFactory.getInstance();

    AccessToken givenAccessToken = new AccessToken(TOKEN, TOKEN_SECRET);
    twitterStream.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECURE);
    twitterStream.setOAuthAccessToken(givenAccessToken);
    twitterStream.addListener(this);
    twitterStream.sample();
}

From source file:de.jetwick.tw.TwitterSearch.java

License:Apache License

/**
 * Connect with twitter to get a new personalized twitter4j instance.
 *
 * @throws RuntimeException if verification or connecting failed
 *///from   w  w  w.jav  a2 s.  c  o m
public TwitterSearch initTwitter4JInstance(String token, String tokenSecret, boolean verify) {
    if (consumerKey == null)
        throw new NullPointerException("Please use init consumer settings!");

    setupProperties();
    AccessToken aToken = new AccessToken(token, tokenSecret);
    twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(aToken);
    try {
        //            RequestToken requestToken = t.getOAuthRequestToken();
        //            System.out.println("TW-URL:" + requestToken.getAuthorizationURL());
        if (verify)
            twitter.verifyCredentials();

        String str = "<user>";
        try {
            str = twitter.getScreenName();
        } catch (Exception ex) {
        }
        logger.info("create new TwitterSearch for " + str + " with verifification:" + verify);
    } catch (TwitterException ex) {
        // rate limit only exceeded
        if (ex.getStatusCode() == 400)
            return this;

        throw new RuntimeException(ex);
    }
    return this;
}

From source file:de.jetwick.tw.TwitterSearchOffline.java

License:Apache License

@Override
public AccessToken oAuthOnCallBack(String oauth_verifierParameter) throws TwitterException {
    return new AccessToken("123-token", "tokenSecret");
}

From source file:de.vanita5.twittnuker.util.Utils.java

License:Open Source License

public static Authorization getTwitterAuthorization(final Context context,
        final AccountWithCredentials account) {
    if (context == null || account == null)
        return null;
    switch (account.auth_type) {
    case Accounts.AUTH_TYPE_OAUTH:
    case Accounts.AUTH_TYPE_XAUTH: {
        final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME,
                Context.MODE_PRIVATE);
        // Here I use old consumer key/secret because it's default
        // key for older
        // versions
        final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY_2);
        final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET_2);
        final ConfigurationBuilder cb = new ConfigurationBuilder();
        if (!isEmpty(account.api_url_format)) {
            final String versionSuffix = account.no_version_suffix ? null : "/1.1/";
            cb.setRestBaseURL(getApiUrl(account.api_url_format, "api", versionSuffix));
            cb.setOAuthBaseURL(getApiUrl(account.api_url_format, "api", "/oauth/"));
            cb.setUploadBaseURL(getApiUrl(account.api_url_format, "upload", versionSuffix));
            if (!account.same_oauth_signing_url) {
                cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
                cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
                cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
            }//www . j  a v a 2  s . co  m
        }
        if (!isEmpty(account.consumer_key) && !isEmpty(account.consumer_secret)) {
            cb.setOAuthConsumerKey(account.consumer_key);
            cb.setOAuthConsumerSecret(account.consumer_secret);
        } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
            cb.setOAuthConsumerKey(prefConsumerKey);
            cb.setOAuthConsumerSecret(prefConsumerSecret);
        } else {
            cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY_2);
            cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET_2);
        }
        final OAuthAuthorization auth = new OAuthAuthorization(cb.build());
        auth.setOAuthAccessToken(new AccessToken(account.oauth_token, account.oauth_token_secret));
        return auth;
    }
    case Accounts.AUTH_TYPE_BASIC: {
        final String screenName = account.screen_name;
        final String username = account.basic_auth_username;
        final String loginName = username != null ? username : screenName;
        final String password = account.basic_auth_password;
        if (isEmpty(loginName) || isEmpty(password))
            return null;
        return new BasicAuthorization(loginName, password);
    }
    default: {
        return null;
    }
    }
}

From source file:de.vanita5.twittnuker.util.Utils.java

License:Open Source License

public static Authorization getTwitterAuthorization(final Context context, final long accountId) {

    final String where = Where.equals(new Column(Accounts.ACCOUNT_ID), accountId).getSQL();
    final Cursor c = ContentResolverUtils.query(context.getContentResolver(), Accounts.CONTENT_URI,
            Accounts.COLUMNS, where, null, null);
    if (c == null)
        return null;
    try {/*  ww w .j  a  v  a  2s  .  c  o  m*/
        if (!c.moveToFirst())
            return null;

        switch (c.getInt(c.getColumnIndexOrThrow(Accounts.AUTH_TYPE))) {
        case Accounts.AUTH_TYPE_OAUTH:
        case Accounts.AUTH_TYPE_XAUTH: {
            final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME,
                    Context.MODE_PRIVATE);
            final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY_2);
            final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET_2);
            final ConfigurationBuilder cb = new ConfigurationBuilder();
            final String apiUrlFormat = c.getString(c.getColumnIndex(Accounts.API_URL_FORMAT));
            final String consumerKey = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_KEY)));
            final String consumerSecret = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_SECRET)));
            final boolean sameOAuthSigningUrl = c
                    .getInt(c.getColumnIndex(Accounts.SAME_OAUTH_SIGNING_URL)) == 1;
            if (!isEmpty(apiUrlFormat)) {
                cb.setRestBaseURL(getApiUrl(apiUrlFormat, "api", "/1.1/"));
                cb.setOAuthBaseURL(getApiUrl(apiUrlFormat, "api", "/oauth/"));
                cb.setUploadBaseURL(getApiUrl(apiUrlFormat, "upload", "/1.1/"));
                if (!sameOAuthSigningUrl) {
                    cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
                    cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
                    cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
                }
            }
            if (!isEmpty(consumerKey) && !isEmpty(consumerSecret)) {
                cb.setOAuthConsumerKey(consumerKey);
                cb.setOAuthConsumerSecret(consumerSecret);
            } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
                cb.setOAuthConsumerKey(prefConsumerKey);
                cb.setOAuthConsumerSecret(prefConsumerSecret);
            } else {
                cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY_2);
                cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET_2);
            }
            final OAuthAuthorization auth = new OAuthAuthorization(cb.build());
            final String token = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN));
            final String tokenSecret = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN_SECRET));
            auth.setOAuthAccessToken(new AccessToken(token, tokenSecret));
            return auth;
        }
        case Accounts.AUTH_TYPE_BASIC: {
            final String screenName = c.getString(c.getColumnIndexOrThrow(Accounts.SCREEN_NAME));
            final String username = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_USERNAME));
            final String loginName = username != null ? username : screenName;
            final String password = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_PASSWORD));
            if (isEmpty(loginName) || isEmpty(password))
                return null;
            return new BasicAuthorization(loginName, password);
        }
        default: {
            return null;
        }
        }
    } finally {
        c.close();
    }
}

From source file:de.vanita5.twittnuker.util.Utils.java

License:Open Source License

public static Twitter getTwitterInstance(final Context context, final long accountId,
        final boolean includeEntities, final boolean includeRetweets, final boolean apacheHttp,
        final String mediaProvider, final String mediaProviderAPIKey) {
    if (context == null)
        return null;
    final TwittnukerApplication app = TwittnukerApplication.getInstance(context);
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final int connection_timeout = prefs.getInt(KEY_CONNECTION_TIMEOUT, 10) * 1000;
    final boolean enableGzip = prefs.getBoolean(KEY_GZIP_COMPRESSING, true);
    final boolean ignoreSSLError = prefs.getBoolean(KEY_IGNORE_SSL_ERROR, false);
    final boolean enableProxy = prefs.getBoolean(KEY_ENABLE_PROXY, false);
    // Here I use old consumer key/secret because it's default key for older
    // versions/*from  w w  w.  ja  v  a2s  . c  om*/
    final String where = Where.equals(new Column(Accounts.ACCOUNT_ID), accountId).getSQL();
    final Cursor c = ContentResolverUtils.query(context.getContentResolver(), Accounts.CONTENT_URI,
            Accounts.COLUMNS, where, null, null);
    if (c == null)
        return null;
    try {
        if (!c.moveToFirst())
            return null;
        final ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setHostAddressResolverFactory(new TwidereHostResolverFactory(app));
        if (apacheHttp) {
            cb.setHttpClientFactory(new TwidereHttpClientFactory(app));
        }
        cb.setHttpConnectionTimeout(connection_timeout);
        cb.setGZIPEnabled(enableGzip);
        cb.setIgnoreSSLError(ignoreSSLError);
        if (enableProxy) {
            final String proxy_host = prefs.getString(KEY_PROXY_HOST, null);
            final int proxy_port = ParseUtils.parseInt(prefs.getString(KEY_PROXY_PORT, "-1"));
            if (!isEmpty(proxy_host) && proxy_port > 0) {
                cb.setHttpProxyHost(proxy_host);
                cb.setHttpProxyPort(proxy_port);
            }
        }
        final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY_2);
        final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET_2);
        final String apiUrlFormat = c.getString(c.getColumnIndex(Accounts.API_URL_FORMAT));
        final String consumerKey = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_KEY)));
        final String consumerSecret = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_SECRET)));
        final boolean sameOAuthSigningUrl = c.getInt(c.getColumnIndex(Accounts.SAME_OAUTH_SIGNING_URL)) == 1;
        final boolean noVersionSuffix = c.getInt(c.getColumnIndex(Accounts.NO_VERSION_SUFFIX)) == 1;
        if (!isEmpty(apiUrlFormat)) {
            final String versionSuffix = noVersionSuffix ? null : "/1.1/";
            cb.setRestBaseURL(getApiUrl(apiUrlFormat, "api", versionSuffix));
            cb.setOAuthBaseURL(getApiUrl(apiUrlFormat, "api", "/oauth/"));
            cb.setUploadBaseURL(getApiUrl(apiUrlFormat, "upload", versionSuffix));
            if (!sameOAuthSigningUrl) {
                cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
                cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
                cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
            }
        }
        if (isOfficialConsumerKeySecret(context, consumerKey, consumerSecret)) {
            setMockOfficialUserAgent(context, cb);
        } else {
            setUserAgent(context, cb);
        }

        if (!isEmpty(mediaProvider)) {
            cb.setMediaProvider(mediaProvider);
        }
        if (!isEmpty(mediaProviderAPIKey)) {
            cb.setMediaProviderAPIKey(mediaProviderAPIKey);
        }
        cb.setIncludeEntitiesEnabled(includeEntities);
        cb.setIncludeRTsEnabled(includeRetweets);
        cb.setIncludeReplyCountEnabled(true);
        cb.setIncludeDescendentReplyCountEnabled(true);
        switch (c.getInt(c.getColumnIndexOrThrow(Accounts.AUTH_TYPE))) {
        case Accounts.AUTH_TYPE_OAUTH:
        case Accounts.AUTH_TYPE_XAUTH: {
            if (!isEmpty(consumerKey) && !isEmpty(consumerSecret)) {
                cb.setOAuthConsumerKey(consumerKey);
                cb.setOAuthConsumerSecret(consumerSecret);
            } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
                cb.setOAuthConsumerKey(prefConsumerKey);
                cb.setOAuthConsumerSecret(prefConsumerSecret);
            } else {
                cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY_2);
                cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET_2);
            }
            final String token = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN));
            final String tokenSecret = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN_SECRET));
            if (isEmpty(token) || isEmpty(tokenSecret))
                return null;
            cb.setOAuthAccessToken(token);
            cb.setOAuthAccessTokenSecret(tokenSecret);
            return new TwitterFactory(cb.build()).getInstance(new AccessToken(token, tokenSecret));
        }
        case Accounts.AUTH_TYPE_BASIC: {
            final String screenName = c.getString(c.getColumnIndexOrThrow(Accounts.SCREEN_NAME));
            final String username = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_USERNAME));
            final String loginName = username != null ? username : screenName;
            final String password = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_PASSWORD));
            if (isEmpty(loginName) || isEmpty(password))
                return null;
            return new TwitterFactory(cb.build()).getInstance(new BasicAuthorization(loginName, password));
        }
        case Accounts.AUTH_TYPE_TWIP_O_MODE: {
            return new TwitterFactory(cb.build()).getInstance(new TwipOModeAuthorization());
        }
        default: {
            return null;
        }
        }
    } finally {
        c.close();
    }
}

From source file:es.upm.oeg.examples.watson.servlets.TwitterAnalysisServlet.java

License:Apache License

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///  w  w  w .  jav  a 2 s .  co  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String twitterUsername = request.getParameter("twitter_name");
    // The factory instance is re-useable and thread safe.
    Twitter twitter = new TwitterFactory().getInstance();
    env = System.getenv();
    consumer_key = env.get("TWITTER_CONSUMER_KEY");
    consumer_secret = env.get("TWITTER_CONSUMER_SECRET");
    access_token = env.get("TWITTER_ACCESS_TOKEN");
    access_key = env.get("TWITTER_ACCESS_KEY");

    AccessToken accessToken = new AccessToken(access_token, access_key);

    try {
        twitter.setOAuthConsumer(consumer_key, consumer_secret);
        twitter.setOAuthAccessToken(accessToken);

        twitter4j.User a_name = twitter.showUser(twitterUsername);
        int followerCount = a_name.getFollowersCount();
        List<Status> retweets = twitter.getUserTimeline(twitterUsername, new Paging(1, 20)); // get the first twenty tweets
        int retweetCount = 0;
        List<String> langs = new ArrayList<>();
        List<String> translated = new ArrayList<>();

        StringBuilder aggregatedTextBuilder = new StringBuilder();
        String personalityInsights = null;

        for (Status tweet : retweets) {
            String tweetText = tweet.getText();
            try {
                String lang = languageIdentification.getLang(tweetText);
                langs.add(lang);
                String englishText;
                //TODO do the same for french and portuguese
                if (LanguageIdentificationService.ES_ES.equals(lang)) {
                    englishText = machineTranslation.translate(tweetText, MachineTranslationService.ES_TO_EN);
                } else if (LanguageIdentificationService.FR_FR.equals(lang)) {
                    englishText = machineTranslation.translate(tweetText, MachineTranslationService.FR_TO_EN);
                } else if (LanguageIdentificationService.PT_BR.equals(lang)) {
                    englishText = machineTranslation.translate(tweetText, MachineTranslationService.PT_TO_EN);
                } else {
                    englishText = tweetText;
                }
                translated.add(englishText);
                aggregatedTextBuilder.append(englishText);

                personalityInsights = personalityInsightsService.analyse(aggregatedTextBuilder.toString());

            } catch (Exception e) {
                // Log something and return an error message
                logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
                request.setAttribute("error", e.getMessage());
            }

        }

        request.setAttribute("t_name", twitterUsername);
        request.setAttribute("rtweets", retweets);
        request.setAttribute("langs", langs);
        request.setAttribute("translated", translated);
        request.setAttribute("personalityInsights", personalityInsights);
        request.setAttribute("aggregatedText", aggregatedTextBuilder.toString());

        request.getRequestDispatcher("/myTweets.jsp").forward(request, response);
    } catch (TwitterException e) {

        e.printStackTrace();
        if (e.getErrorCode() == 215 || e.getErrorCode() == 32) {
            response.sendRedirect("../index.html?message=errorcode215");
        } else if (e.getErrorCode() == -1 || e.getErrorCode() == 34) {
            response.sendRedirect("../index.html?message=errorcode-1");
        } else {
            response.sendRedirect("../index.html?message=errorcode99");
        }
        //throw new ServletException("Encountered a problem fetching data from Twitter - " + e.getErrorMessage());
    }
}

From source file:foo.bar.twitter.sample01.Sample01Activity.java

License:Apache License

/**
 * start button clicked/*from   ww w.j a  v  a  2s  .  c  o m*/
 * @param v
 */
public void onClickStartButton(View v) {
    Log.d("DEBUG", "Start button clicked!");

    if (!isAuthorized) {
        Log.d("DEBUG", "not authorized");
        return;
    }

    bt_start.setEnabled(false); //start button disabled
    bt_cancel.setEnabled(true); //cancel button enabled

    if (isAuthorized) {
        twitterStream = new TwitterStreamFactory().getInstance();
        twitterStream.setOAuthConsumer(ConstantValue.CONSUMER_KEY, ConstantValue.CONSUMER_SECRET);
        twitterStream.setOAuthAccessToken(new AccessToken(token, tokenSecret));
        StatusListener listener = new StatusListener() {
            @Override
            public void onException(Exception arg0) {
                ;//no process
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice arg0) {
                ;//no process
            }

            @Override
            public void onScrubGeo(long arg0, long arg1) {
                ;//no process
            }

            @Override
            public void onStatus(Status status) {
                String tweet = status.getText();
                Log.d("DEBUG", "tweet: " + tweet);
            }

            @Override
            public void onTrackLimitationNotice(int arg0) {
                ;//no process
            }
        };
        twitterStream.addListener(listener);
        String[] trackArray = { ConstantValue.HASH_TAG };
        twitterStream.filter(new FilterQuery(0, null, trackArray));
    }
}

From source file:free.chessclub.bot.TwitterManager.java

License:Apache License

public void connect() {
    try {// ww  w .  j  a  va 2s. co  m
        File configInfo = new File("twitter_Auth.cfg");
        Scanner fileReader = new Scanner(configInfo);
        String consumerKeyStr = fileReader.nextLine().trim();
        String consumerSecretStr = fileReader.nextLine().trim();
        String accessTokenStr = fileReader.nextLine().trim();
        String tokenSecretStr = fileReader.nextLine().trim();
        //String pinStr = fileReader.nextLine().trim();

        twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(consumerKeyStr, consumerSecretStr);
        twitter.setOAuthAccessToken(new AccessToken(accessTokenStr, tokenSecretStr));
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.out.println("Failed to read the system input.");
        System.exit(-1);
    }
}