Example usage for twitter4j Twitter setOAuthAccessToken

List of usage examples for twitter4j Twitter setOAuthAccessToken

Introduction

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

Prototype

void setOAuthAccessToken(AccessToken accessToken);

Source Link

Document

Sets the access token

Usage

From source file:net.lacolaco.smileessence.twitter.TwitterApi.java

License:Open Source License

public Twitter getTwitter() {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthAccessToken(new AccessToken(token, tokenSecret));
    return twitter;
}

From source file:nz.net.speakman.android.dreamintweets.activities.MainActivity.java

License:Apache License

private void showScreenName() {
    new AsyncTask<Void, Void, String>() {

        @Override//from   w ww  .j a va 2 s  . c o  m
        protected String doInBackground(Void... params) {
            String screenname = null;
            try {
                Twitter twitter = ((DreamApplication) getApplication()).getTwitter();
                twitter.setOAuthAccessToken(new DreamPreferences(MainActivity.this).getAccessToken());
                screenname = twitter.getScreenName();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
            } catch (TwitterException e) {
                // TODO Auto-generated catch block
            }
            return screenname;
        }

        @Override
        protected void onPostExecute(String result) {
            TextView tv = (TextView) findViewById(R.id.signed_in_as_text);
            if (tv != null && result != null) {
                tv.setText(getString(R.string.main_activity_signed_in_as, result));
                tv.setVisibility(View.VISIBLE);
            }
        }

    }.execute();
}

From source file:org.encuestame.business.service.AbstractBaseService.java

License:Apache License

/**
 * Get Access Token.//from  ww  w  .  j  a v  a2s  .c o  m
 * @param token
 * @param tokenSecret
 * @param pin
 * @return
 * @throws TwitterException
 */
@SuppressWarnings("unused")
private AccessToken getAccessToken(final Twitter twitter, final String token, final String tokenSecret)
        throws TwitterException {

    final AccessToken accessToken = twitter.getOAuthAccessToken(token, tokenSecret);
    log.info(String.format("Auth Token {%s Token Secret {%s ", accessToken.getToken(),
            accessToken.getTokenSecret()));
    twitter.setOAuthAccessToken(accessToken);
    if (accessToken != null) {
        log.info(String.format("Got access token for user %s", accessToken.getScreenName()));
    }
    return accessToken;
}

From source file:org.examproject.tweet.service.SimpleTweetService.java

License:Apache License

private Twitter getTwitter() {
    TwitterFactory factory = new TwitterFactory();
    Twitter twitter = factory.getInstance();
    twitter.setOAuthConsumer(authValue.getConsumerKey(), authValue.getConsumerSecret());
    twitter.setOAuthAccessToken(new AccessToken(authValue.getOauthToken(), authValue.getOauthTokenSecret()));
    return twitter;
}

From source file:org.exoplatform.extensions.twitter.services.TwitterService.java

License:Open Source License

/**
 * /*from   w  w  w  .j  av a2  s.  c o  m*/
 * @param userId
 * @return 
 */
public Twitter getTwitter(String userId) {
    Twitter twitter = null;
    UserSocialNetworkPreferences prefs = this.getUserPreferences(userId);
    if (prefs != null) {
        String token = prefs.getToken();
        String tokenSecret = prefs.getTokenSecret();
        if (token != null && tokenSecret != null) {
            AccessToken accessToken = new AccessToken(token, tokenSecret);
            twitter = new TwitterFactory().getInstance();
            twitter.setOAuthConsumer(consumerKey, secretKey);
            twitter.setOAuthAccessToken(accessToken);
        }
    }
    return twitter;
}

From source file:org.getlantern.firetweet.fragment.support.AccountsDashboardFragment.java

License:Open Source License

@Override
public void onListItemClick(final ListView l, final View v, final int position, final long id) {
    final ListAdapter adapter = mAdapter.getAdapter(position);
    final Object item = mAdapter.getItem(position);
    if (adapter instanceof AccountOptionsAdapter) {
        final ParcelableAccount account = mAccountsAdapter.getSelectedAccount();
        if (account == null || !(item instanceof OptionItem))
            return;
        final OptionItem option = (OptionItem) item;
        switch (option.id) {
        case MENU_SEARCH: {
            final Intent intent = new Intent(getActivity(), QuickSearchBarActivity.class);
            intent.putExtra(EXTRA_ACCOUNT_ID, account.account_id);
            startActivity(intent);//  w w  w  . ja va  2  s  .c  o  m
            closeAccountsDrawer();
            break;
        }
        case MENU_COMPOSE: {
            final Intent composeIntent = new Intent(INTENT_ACTION_COMPOSE);
            composeIntent.setClass(getActivity(), ComposeActivity.class);
            composeIntent.putExtra(EXTRA_ACCOUNT_IDS, new long[] { account.account_id });
            startActivity(composeIntent);
            break;
        }
        case MENU_FAVORITES: {
            openUserFavorites(getActivity(), account.account_id, account.account_id, account.screen_name);
            break;
        }
        case MENU_LISTS: {
            openUserLists(getActivity(), account.account_id, account.account_id, account.screen_name);
            break;
        }
        case MENU_EDIT: {
            final Bundle bundle = new Bundle();
            bundle.putLong(EXTRA_ACCOUNT_ID, account.account_id);
            final Intent intent = new Intent(INTENT_ACTION_EDIT_USER_PROFILE);
            intent.setClass(getActivity(), UserProfileEditorActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);
            break;
        }
        }
    } else if (adapter instanceof AppMenuAdapter) {
        if (!(item instanceof OptionItem))
            return;
        final OptionItem option = (OptionItem) item;
        switch (option.id) {
        case MENU_ACCOUNTS: {
            final Intent intent = new Intent(getActivity(), AccountsManagerActivity.class);
            startActivity(intent);
            break;
        }
        case MENU_DRAFTS: {
            final Intent intent = new Intent(INTENT_ACTION_DRAFTS);
            intent.setClass(getActivity(), DraftsActivity.class);
            startActivity(intent);
            break;
        }
        case MENU_SIGNOUT: {
            // destroy Twitter instance and delete oauth access token
            final Twitter mTwitter = new TwitterFactory().getInstance();
            mTwitter.setOAuthConsumer(Accounts.CONSUMER_KEY, Accounts.CONSUMER_SECRET);
            mTwitter.setOAuthAccessToken(null);
            mTwitter.shutdown();

            // remove existing account
            mAccountsAdapter.setAccounts(null);
            Utils.removeAccounts(getActivity().getApplicationContext());

            // close existing activity
            closeActivity();

            // display sign in activity
            final Intent signInIntent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
            signInIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(signInIntent);
            break;
        }
        case MENU_SETTINGS: {
            final Intent intent = new Intent(getActivity(), SettingsActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivityForResult(intent, REQUEST_SETTINGS);
            break;
        }
        }
        closeAccountsDrawer();
    }
}

From source file:org.jwebsocket.plugins.twitter.TwitterPlugIn.java

License:Apache License

/**
 * posts a Twitter message on behalf of a OAtuh authenticated user by using
 * the retrieved AccessToken and its verifier.
 *
 * @param aConnector/*w  ww .  ja  va 2 s.  c  om*/
 * @param aToken
 */
private void tweet(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();

    // instantiate response token
    Token lResponse = lServer.createResponse(aToken);
    String lMsg = aToken.getString("message");
    try {
        // to send tweet we need an authenticated user
        Twitter lTwitter = (Twitter) aConnector.getVar(TWITTER_VAR);
        RequestToken lReqToken = (RequestToken) aConnector.getVar(OAUTH_REQUEST_TOKEN);
        String lVerifier = aConnector.getString(OAUTH_VERIFIER);

        if (lTwitter == null) {
            lResponse.setInteger("code", -1);
            lResponse.setString("msg", "Not yet authenticated against Twitter!");
        } else if (lReqToken == null) {
            lResponse.setInteger("code", -1);
            lResponse.setString("msg", "No Access Token available!");
        } else if (lVerifier == null) {
            lResponse.setInteger("code", -1);
            lResponse.setString("msg", "No Access Verifier available!");
        } else if (lMsg == null || lMsg.length() <= 0) {
            lResponse.setInteger("code", -1);
            lResponse.setString("msg", "No message passed for tweet.");
        } else {
            AccessToken lAccessToken = lTwitter.getOAuthAccessToken(lReqToken, lVerifier);
            lTwitter.setOAuthAccessToken(lAccessToken);

            lTwitter.updateStatus(lMsg);
            lMsg = "Twitter status successfully updated for user '" + lTwitter.getScreenName() + "'.";
            lResponse.setString("msg", lMsg);
            if (mLog.isInfoEnabled()) {
                mLog.info(lMsg);
            }
        }
    } catch (Exception lEx) {
        lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage();
        mLog.error(lMsg);
        lResponse.setInteger("code", -1);
        lResponse.setString("msg", lMsg);
    }

    // send response to requester
    lServer.sendToken(aConnector, lResponse);
}

From source file:org.minesales.infres6.narvisAPITwiterConsole.communications.twitter.AccessTwitter.java

public static Twitter loadAccessTwitter() {
    String token = "2754794936-VRDsXE6ZxnBQeUTbprYHGEOVQcYJc1mvyNaBfyC";
    String tokenSecret = "Sb7nwzWtlmOw6CRcqRoSlXkvonZGXiLTOp9sBAlv4fDOy";
    AccessToken accessToken = new AccessToken(token, tokenSecret);
    TwitterFactory factory = new TwitterFactory();
    Twitter twitter = factory.getInstance();
    twitter.setOAuthConsumer("CkQjh66TbG4FYfry1OTrTb4tS", "v8vbUPtFAkIfSUN2KICf8GDEZ91fumVuY5mzMAmT84Ag2bVnvD");
    twitter.setOAuthAccessToken(accessToken);
    return twitter;
}

From source file:org.opencrx.application.twitter.SendDirectMessageWorkflow.java

License:BSD License

@Override
public void execute(WorkflowTarget wfTarget, ContextCapable targetObject, WfProcessInstance wfProcessInstance)
        throws ServiceException {
    PersistenceManager pm = JDOHelper.getPersistenceManager(wfProcessInstance);
    PersistenceManager rootPm = pm.getPersistenceManagerFactory()
            .getPersistenceManager(SecurityKeys.ROOT_PRINCIPAL, null);
    try {//w  ww.j  av  a2  s.co  m
        UserHome userHome = (UserHome) pm.getObjectById(wfProcessInstance.refGetPath().getParent().getParent());
        String providerName = userHome.refGetPath().get(2);
        String segmentName = userHome.refGetPath().get(4);
        ComponentConfiguration configuration = TwitterUtils.getComponentConfiguration(providerName, segmentName,
                rootPm);
        Map<String, Object> params = WorkflowHelper.getWorkflowParameters(wfProcessInstance);
        // Find default twitter account
        TwitterAccountQuery twitterAccountQuery = (TwitterAccountQuery) pm.newQuery(TwitterAccount.class);
        twitterAccountQuery.thereExistsIsDefault().isTrue();
        twitterAccountQuery.thereExistsIsActive().isTrue();
        List<TwitterAccount> twitterAccounts = userHome.getEMailAccount(twitterAccountQuery);
        TwitterAccount twitterAccount = twitterAccounts.isEmpty() ? null : twitterAccounts.iterator().next();
        String subject = null;
        String text = null;
        if (twitterAccount == null) {
            subject = "ERROR: " + Notifications.getInstance().getNotificationSubject(pm, targetObject,
                    wfProcessInstance.refGetPath(), userHome, params, true // useSendMailSubjectPrefix
            );
            text = "ERROR: direct message not sent. No default twitter account\n";
        } else {
            // Send direct message
            subject = Notifications.getInstance().getNotificationSubject(pm, targetObject,
                    wfProcessInstance.refGetPath(), userHome, params, true //this.useSendMailSubjectPrefix
            );
            String tinyUrl = TinyUrlUtils
                    .getTinyUrl(Notifications.getInstance().getAccessUrl(targetObject.refGetPath(), userHome));
            if (tinyUrl != null) {
                if (subject.length() > TwitterUtils.MESSAGE_SIZE - 30 - 4) {
                    subject = subject.substring(0, TwitterUtils.MESSAGE_SIZE - 30 - 4) + "...";
                }
                subject += " " + tinyUrl;
            } else {
                if (subject.length() > TwitterUtils.MESSAGE_SIZE - 3) {
                    subject = subject.substring(0, TwitterUtils.MESSAGE_SIZE - 3) + "...";
                }
            }
            TwitterFactory twitterFactory = new TwitterFactory(

            );
            AccessToken accessToken = new AccessToken(twitterAccount.getAccessToken(),
                    twitterAccount.getAccessTokenSecret());
            Twitter twitter = twitterFactory.getInstance();
            twitter.setOAuthConsumer(TwitterUtils.getConsumerKey(twitterAccount, configuration),
                    TwitterUtils.getConsumerSecret(twitterAccount, configuration));
            twitter.setOAuthAccessToken(accessToken);
            SysLog.detail("Send direct message message");
            DirectMessage message = twitter.sendDirectMessage(twitterAccount.getName(), subject);
            SysLog.detail("Done", message);
        }
        WorkflowHelper.createLogEntry(wfProcessInstance, subject, text);
    } catch (Exception e) {
        SysLog.warning("Can not send direct message");
        ServiceException e0 = new ServiceException(e);
        SysLog.detail(e0.getMessage(), e0.getCause());
        WorkflowHelper.createLogEntry(wfProcessInstance, "Can not send direct message: Exception",
                e.getMessage());
        throw e0;
    } finally {
        if (rootPm != null) {
            rootPm.close();
        }
    }
}

From source file:org.opencrx.kernel.portal.wizard.TwitterSendMessageWizardController.java

License:BSD License

/**
 * OK action.//  ww w . jav a 2 s  .c  om
 * 
 * @param formFields
 * @throws ServiceException
 */
public void doOK(@FormParameter(forms = "TwitterSendMessageForm") Map<String, Object> formFields)
        throws ServiceException {
    PersistenceManager pm = this.getPm();
    RefObject_1_0 obj = this.getObject();
    this.doRefresh(formFields);
    String toUsers = (String) formFields.get("org:opencrx:kernel:base:SendAlertParams:toUsers");
    String text = (String) formFields.get("org:opencrx:kernel:base:Note:text");
    if ((toUsers != null) && !toUsers.isEmpty() && (text != null) && !text.isEmpty()) {
        javax.jdo.PersistenceManager rootPm = pm.getPersistenceManagerFactory()
                .getPersistenceManager(org.opencrx.kernel.generic.SecurityKeys.ROOT_PRINCIPAL, null);
        org.opencrx.kernel.admin1.jmi1.ComponentConfiguration configuration = org.opencrx.application.twitter.TwitterUtils
                .getComponentConfiguration(this.getProviderName(), this.getSegmentName(), rootPm);
        // Find default twitter account
        org.opencrx.kernel.home1.jmi1.UserHome userHome = UserHomes.getInstance().getUserHome(obj.refGetPath(),
                pm);
        TwitterAccountQuery twitterAccountQuery = (TwitterAccountQuery) pm.newQuery(TwitterAccount.class);
        twitterAccountQuery.thereExistsIsDefault().isTrue();
        twitterAccountQuery.thereExistsIsActive().isTrue();
        List<TwitterAccount> twitterAccounts = userHome.getEMailAccount(twitterAccountQuery);
        TwitterAccount twitterAccount = twitterAccounts.isEmpty() ? null : twitterAccounts.iterator().next();
        if (twitterAccount != null) {
            TwitterFactory twitterFactory = new TwitterFactory();
            AccessToken accessToken = new AccessToken(twitterAccount.getAccessToken(),
                    twitterAccount.getAccessTokenSecret());
            Twitter twitter = twitterFactory.getInstance();
            twitter.setOAuthConsumer(TwitterUtils.getConsumerKey(twitterAccount, configuration),
                    TwitterUtils.getConsumerSecret(twitterAccount, configuration));
            twitter.setOAuthAccessToken(accessToken);
            StringTokenizer users = new StringTokenizer(toUsers, " ,", false);
            while (users.hasMoreTokens()) {
                String user = users.nextToken();
                try {
                    @SuppressWarnings("unused")
                    DirectMessage message = twitter.sendDirectMessage(user, text);
                } catch (Exception e) {
                    new ServiceException(e).log();
                }
            }
            // Send alert if invoked on user's home
            String title = NOTE_TITLE_PREFIX + " [" + twitterAccount.getName() + "] @ " + new Date();
            if (obj instanceof org.opencrx.kernel.home1.jmi1.UserHome) {
                org.opencrx.kernel.home1.jmi1.UserHome user = (org.opencrx.kernel.home1.jmi1.UserHome) obj;
                Base.getInstance().sendAlert(user, // target
                        user.refGetPath().getBase(), title, text, (short) 2, // importance
                        0, // resendDelayInSeconds
                        null // reference
                );
            }
            // Attach message as Note                
            else if (obj instanceof org.opencrx.kernel.generic.jmi1.CrxObject) {
                try {
                    pm.currentTransaction().begin();
                    org.opencrx.kernel.generic.jmi1.CrxObject crxObject = (org.opencrx.kernel.generic.jmi1.CrxObject) obj;
                    org.opencrx.kernel.generic.jmi1.Note note = pm
                            .newInstance(org.opencrx.kernel.generic.jmi1.Note.class);
                    note.setTitle(title);
                    note.setText(text);
                    crxObject.addNote(Base.getInstance().getUidAsString(), note);
                    pm.currentTransaction().commit();
                    // FollowUp if obj is an activity
                    if (obj instanceof Activity) {
                        try {
                            Activity activity = (Activity) obj;
                            ActivityProcess activityProcess = activity.getActivityType().getControlledBy();
                            ActivityProcessTransitionQuery processTransitionQuery = (ActivityProcessTransitionQuery) pm
                                    .newQuery(
                                            org.opencrx.kernel.activity1.cci2.ActivityProcessTransition.class);
                            processTransitionQuery.thereExistsPrevState().equalTo(activity.getProcessState());
                            processTransitionQuery.orderByNewPercentComplete().ascending();
                            List<ActivityProcessTransition> processTransitions = activityProcess
                                    .getTransition(processTransitionQuery);
                            if (!processTransitions.isEmpty()) {
                                ActivityProcessTransition processTransition = processTransitions.iterator()
                                        .next();
                                pm.currentTransaction().begin();
                                @SuppressWarnings("unused")
                                ActivityFollowUp followUp = Activities.getInstance().doFollowUp(activity, title,
                                        text, processTransition, null, // reportingContact
                                        null // parentProcessInstance
                                );
                                pm.currentTransaction().commit();
                            }
                        } catch (Exception e) {
                            try {
                                pm.currentTransaction().rollback();
                            } catch (Exception e0) {
                            }
                        }
                    }
                } catch (Exception e) {
                    try {
                        pm.currentTransaction().rollback();
                    } catch (Exception e0) {
                    }
                }
            }
            this.forward("Cancel", this.getRequest().getParameterMap());
        }
    }
}