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:org.opencrx.kernel.portal.wizard.TwitterUpdateStatusWizardController.java

License:BSD License

/**
 * OK action./*from  ww  w.  j av a2s  .  c  o  m*/
 * 
 * @param formFields
 * @param serviceAccountId
 * @throws ServiceException
 */
public void doOK(@FormParameter(forms = "TwitterUpdateStatusForm") Map<String, Object> formFields,
        @RequestParameter(name = "serviceAccountId") String serviceAccountId) throws ServiceException {
    PersistenceManager pm = this.getPm();
    this.doRefresh(formFields, serviceAccountId);
    RefObject_1_0 obj = this.getObject();
    javax.jdo.PersistenceManager rootPm = pm.getPersistenceManagerFactory()
            .getPersistenceManager(org.opencrx.kernel.generic.SecurityKeys.ROOT_PRINCIPAL, null);
    org.opencrx.kernel.home1.jmi1.UserHome userHome = UserHomes.getInstance().getUserHome(obj.refGetPath(), pm);
    serviceAccountId = (String) formFields.get("serviceAccountId");
    String text = (String) formFields.get("org:opencrx:kernel:base:Note:text");
    if ((serviceAccountId != null) && (serviceAccountId.length() > 0) && (text != null)
            && (text.length() > 0)) {
        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.TwitterAccount twitterAccount = (org.opencrx.kernel.home1.jmi1.TwitterAccount) userHome
                .getEMailAccount(serviceAccountId);
        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);
            try {
                @SuppressWarnings("unused")
                Status status = twitter.updateStatus(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();
                            org.opencrx.kernel.activity1.cci2.ActivityProcessTransitionQuery processTransitionQuery = (org.opencrx.kernel.activity1.cci2.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());
        }
    }
}

From source file:org.orcid.core.manager.impl.OrcidSocialManagerImpl.java

License:Open Source License

/**
 * Tweet a message to the specified profile
 * /*from   w  w w  .j  av  a  2 s.co  m*/
 * @param entity
 *            An entity containing the user information and the twitter
 *            credentials
 * @return true if it was able to tweet the updates
 * */
@SuppressWarnings("unchecked")
private boolean tweet(OrcidSocialEntity entity) {
    String jsonCredentials = decrypt(entity.getEncryptedCredentials());
    Map<String, String> credentials = (HashMap<String, String>) JSON.parse(jsonCredentials);
    Twitter twitter = new TwitterFactory().getInstance();

    twitter.setOAuthConsumer(twitterKey, twitterSecret);
    AccessToken accessToken = new AccessToken(credentials.get(TWITTER_USER_KEY),
            credentials.get(TWITTER_USER_SECRET));

    twitter.setOAuthAccessToken(accessToken);
    try {
        twitter.updateStatus(buildUpdateMessage(entity.getId().getOrcid()));
    } catch (Exception e) {
        LOGGER.error("Unable to tweet on profile {}", entity.getId().getOrcid());
        return false;
    }

    return true;
}

From source file:org.osframework.maven.plugins.twitter.AbstractTwitterMojo.java

License:Apache License

private Twitter getAuthenticatedTwitter() throws TwitterException {
    if (StringUtils.isBlank(consumerKey) || StringUtils.isBlank(consumerSecret)) {
        throw new TwitterException("Missing required credentials");
    }/*from  w  w w.jav  a  2s . c  om*/
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    loadAccessToken(twitter);
    twitter.setOAuthAccessToken(authToken);
    return twitter;
}

From source file:org.primefaces.examples.service.TwitterAPIService.java

License:Apache License

public List<Status> getTweets(String username) {
    List<Status> tweets = null;

    try {/*from ww w  .j  a va 2  s . c o  m*/
        if (username != null && !username.equals("")) {
            Twitter twitter = new TwitterFactory().getInstance();
            twitter.setOAuthConsumer(twitter_consumer_key, twitter_consumer_secret);
            twitter.setOAuthAccessToken(new AccessToken(access_token, access_token_secret));
            Paging p = new Paging(1, 200);
            tweets = twitter.getUserTimeline(username, p);
        }
    } catch (Exception e) {
        logger.severe(e.getMessage());
    }

    return tweets;
}

From source file:org.rhq.enterprise.server.plugins.alertMicroblog.MicroblogSender.java

License:Open Source License

@Override
public SenderResult send(Alert alert) {

    SenderResult result;/* w  w w . java2  s .c om*/
    String consumerKey = preferences.getSimpleValue("consumerKey", CONS_KEY);
    String consumerSecret = preferences.getSimpleValue("consumerSecret", CONS_SECRET);
    String accessTokenFilePath = preferences.getSimpleValue("accessTokenFilePath", "/path/to/token.ser");

    try {
        TwitterFactory tFactory = new TwitterFactory();
        AccessToken accessToken = restoreAccessToken(accessTokenFilePath);

        log.debug("loading accessToken from " + accessTokenFilePath);
        log.debug("token: [" + accessToken.getToken() + "]");
        log.debug("tokenSecret: [" + accessToken.getTokenSecret() + "]");

        Twitter twitter = tFactory.getInstance();
        twitter.setOAuthConsumer(consumerKey, consumerSecret);
        twitter.setOAuthAccessToken(accessToken);

        AlertManagerLocal alertManager = LookupUtil.getAlertManager();
        StringBuilder b = new StringBuilder("Alert ");
        b.append(alert.getId()).append(":'"); // Alert id
        b.append(alert.getAlertDefinition().getResource().getName());
        b.append("' (");
        b.append(alert.getAlertDefinition().getResource().getId());
        b.append("): ");
        b.append(alertManager.prettyPrintAlertConditions(alert, true));
        b.append("-by " + this.alertParameters.getSimpleValue("twittedBy", "@RHQ")); // TODO not for production :-)
        // TODO use some alert url shortening service

        String msg = b.toString();
        if (msg.length() > 140)
            msg = msg.substring(0, 140);

        Status status = twitter.updateStatus(msg);

        result = SenderResult.getSimpleSuccess("Send notification - msg-id: " + status.getId());
    } catch (TwitterException e) {

        log.warn("Notification via Microblog failed!", e);
        result = SenderResult.getSimpleFailure("Sending failed :" + e.getMessage());

    } catch (IOException e) {
        log.error("Notification via Microblog failed!", e);
        result = SenderResult.getSimpleFailure("Sending failed :" + e.getMessage());
    }
    return result;
}

From source file:org.sakaiproject.profile2.logic.ProfileExternalIntegrationLogicImpl.java

License:Educational Community License

/**
  * {@inheritDoc}// w  ww .  j a  va 2 s . c  om
  */
public String getTwitterName(ExternalIntegrationInfo info) {

    if (info == null) {
        return null;
    }

    //get values
    String token = info.getTwitterToken();
    String secret = info.getTwitterSecret();

    if (StringUtils.isNotBlank(token) && StringUtils.isNotBlank(secret)) {

        //global config
        Map<String, String> config = getTwitterOAuthConsumerDetails();

        //token for user
        AccessToken accessToken = new AccessToken(token, secret);

        //setup
        TwitterFactory factory = new TwitterFactory();
        Twitter twitter = factory.getInstance();
        twitter.setOAuthConsumer(config.get("key"), config.get("secret"));
        twitter.setOAuthAccessToken(accessToken);

        //check
        try {
            return twitter.verifyCredentials().getScreenName();
        } catch (TwitterException e) {
            log.error("Error retrieving Twitter credentials: " + e.getClass() + ": " + e.getMessage());
        }
    }
    return null;
}

From source file:org.sakaiproject.profile2.logic.ProfileExternalIntegrationLogicImpl.java

License:Educational Community License

/**
  * {@inheritDoc}//from ww  w. j a v a 2 s.com
  */
public void sendMessageToTwitter(final String userUuid, String message) {
    //setup class thread to call later
    class TwitterUpdater implements Runnable {
        private Thread runner;
        private String userUuid;
        private String userToken;
        private String userSecret;
        private String message;

        public TwitterUpdater(String userUuid, String userToken, String userSecret, String message) {
            this.userUuid = userUuid;
            this.userToken = userToken;
            this.userSecret = userSecret;
            this.message = message;

            runner = new Thread(this, "Profile2 TwitterUpdater thread");
            runner.start();
        }

        //do it!
        public synchronized void run() {

            //global config
            Map<String, String> config = getTwitterOAuthConsumerDetails();

            //token for user
            AccessToken accessToken = new AccessToken(userToken, userSecret);

            //setup
            TwitterFactory factory = new TwitterFactory();
            Twitter twitter = factory.getInstance();
            twitter.setOAuthConsumer(config.get("key"), config.get("secret"));
            twitter.setOAuthAccessToken(accessToken);

            try {
                twitter.updateStatus(message);
                log.info("Twitter status updated for: " + userUuid);

                //post update event
                sakaiProxy.postEvent(ProfileConstants.EVENT_TWITTER_UPDATE, "/profile/" + userUuid, true);
            } catch (TwitterException e) {
                log.error(
                        "ProfileLogic.sendMessageToTwitter() failed. " + e.getClass() + ": " + e.getMessage());
            }
        }
    }

    //is twitter enabled
    if (!sakaiProxy.isTwitterIntegrationEnabledGlobally()) {
        return;
    }

    //get user info
    ExternalIntegrationInfo info = getExternalIntegrationInfo(userUuid);
    String token = info.getTwitterToken();
    String secret = info.getTwitterSecret();
    if (StringUtils.isBlank(token) || StringUtils.isBlank(secret)) {
        return;
    }

    //PRFL-423 limit to 140 chars
    //Hardcoded limit because 140 is the Twitter requirement so no need to make configurable
    message = ProfileUtils.truncate(message, 140, false);

    //instantiate class to send the data
    new TwitterUpdater(userUuid, token, secret, message);
}

From source file:org.tomochika1985.twitter.AppSession.java

License:Apache License

public boolean login(String pin, Response response) {
    try {/*from  w  w w .  j  av  a  2  s.c  om*/
        if (requestToken == null) {
            throw new IllegalStateException("requestToken is missing.");
        }

        Twitter client = new TwitterClient();
        client.setOAuthConsumer(consumerKey, consumerSecret);

        AccessToken accessToken = client.getOAuthAccessToken(requestToken, pin);
        client.setOAuthAccessToken(accessToken);
        this.twitterSession = client;
        dirty();
        return true;
    } catch (TwitterException ex) {
        LOGGER.error("Can not setup OAuth Access Token to Twitter object.", ex);
        return false;
    }
}

From source file:org.tynamo.examples.federatedaccounts.pages.Index.java

License:Apache License

@RequiresPermissions("twitter")
Block onActionFromListTweets() throws TwitterException {
    OauthAccessToken accessToken = securityService.getSubject().getPrincipals()
            .oneByType(TwitterAccessToken.class);
    Twitter twitter = twitterFactory.getInstance();
    twitter.setOAuthConsumer(oauthClientId, oauthClientSecret);
    twitter.setOAuthAccessToken((AccessToken) accessToken.getCredentials());
    tweets = twitter.getHomeTimeline();/* w  ww  . j a  va2 s  .  c  om*/
    return tweetResults.getBody();

}

From source file:org.wso2.fasttrack.project.roadlk.rest.DatasetGenerator.java

License:Open Source License

/**
 * @param consumerKey//from  ww w. j a  va 2 s  . c om
 *            Twitter Consumer Key (API Key)
 * @param consumerSecret
 *            Twitter Consumer Secret (API Secret)
 * @param accessToken
 *            Twitter Access Token
 * @param accessTokenSecret
 *            Twitter Access Token Secret
 * @param pageLimit
 *            Maximum pages to be retrieved
 * @throws IOException
 * @throws TwitterException
 */
@SuppressWarnings("resource")
public void generateDataset(String consumerKey, String consumerSecret, String accessToken,
        String accessTokenSecret, int pageLimit) throws IOException, TwitterException {
    // Twitter object of Twitter4J library
    Twitter twitter = TwitterFactory.getSingleton();

    // Twitter API authentication
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    PrintWriter printWriter = null;

    try {
        printWriter = new PrintWriter(new BufferedWriter(new FileWriter("dataset.txt", true)));
    } catch (IOException e) {
        throw new IOException(e);
    }

    LOGGER.debug("Twitter feed extraction started.");

    for (int i = 1; i < pageLimit; i = i + 1) {

        Paging paging = new Paging(i, 100);
        ResponseList<Status> statuses = null;

        try {
            statuses = twitter.getUserTimeline("road_lk", paging);
        } catch (TwitterException e) {
            //LOGGER.error("TwitterException occurred." + e.getMessage());
            throw new TwitterException(e);
        }

        for (Status status : statuses) {
            printWriter.println(status.getCreatedAt() + ": " + status.getText());
        }
    }
    printWriter.close();
    LOGGER.debug("Twitter feed extraction completed.");
}