Example usage for twitter4j Twitter setOAuthConsumer

List of usage examples for twitter4j Twitter setOAuthConsumer

Introduction

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

Prototype

void setOAuthConsumer(String consumerKey, String consumerSecret);

Source Link

Document

sets the OAuth consumer key and consumer secret

Usage

From source file:org.keycloak.social.twitter.TwitterProvider.java

License:Open Source License

@Override
public SocialUser processCallback(SocialProviderConfig config, AuthCallback callback)
        throws SocialProviderException {
    if (callback.getQueryParam("denied") != null) {
        throw new SocialAccessDeniedException();
    }//w  w w  . j av a 2 s .  co m

    try {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(config.getKey(), config.getSecret());

        String token = callback.getQueryParam("oauth_token");
        String verifier = callback.getQueryParam("oauth_verifier");

        RequestToken requestToken = new RequestToken((String) callback.getAttribute("token"),
                (String) callback.getAttribute("tokenSecret"));

        twitter.getOAuthAccessToken(requestToken, verifier);
        twitter4j.User twitterUser = twitter.verifyCredentials();

        SocialUser user = new SocialUser(Long.toString(twitterUser.getId()), twitterUser.getScreenName());
        user.setName(twitterUser.getName());

        return user;
    } catch (Exception e) {
        throw new SocialProviderException(e);
    }
}

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.mla.cbox.shibboleth.idp.authn.impl.InitializeTwitterContext.java

License:Apache License

@Override
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext,
        @Nonnull final AuthenticationContext authenticationContext) {

    /* Create a new TwitterContext */
    final TwitterContext twitterContext = new TwitterContext();

    /* Set the Twitter integration details for the context */
    twitterContext.setTwitterIntegration(this.twitterIntegration);
    log.debug("{} Created TwitterContext using TwitterIntegration with consumer key {}", getLogPrefix(),
            this.twitterIntegration.getOauthConsumerKey());

    /* Create a new Twitter class instance and add it to the context */
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(this.twitterIntegration.getOauthConsumerKey(),
            this.twitterIntegration.getOauthConsumerSecret());
    twitterContext.setTwitter(twitter);//from  w w w.  j  av  a  2 s  . c o  m

    /* Find the Spring context and from it the current flow execution URL */
    SpringRequestContext springRequestContext = (SpringRequestContext) profileRequestContext
            .getSubcontext(SpringRequestContext.class);
    RequestContext requestContext = springRequestContext.getRequestContext();
    String flowUrl = requestContext.getFlowExecutionUrl();

    /* Construct the callback URL using the flow execution URL and the server details */
    ServletExternalContext externalContext = (ServletExternalContext) requestContext.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getNativeRequest();
    StringBuilder callbackUrlBuilder = new StringBuilder().append(request.getScheme()).append("://")
            .append(request.getServerName()).append(flowUrl).append("&_eventId=proceed");

    String callbackUrl = callbackUrlBuilder.toString();

    /* Query Twitter for the request token and include the callback URL */
    try {
        log.debug("{} Obtaining request token with callback URL {}", getLogPrefix(), callbackUrl);
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);
        twitterContext.setRequestToken(requestToken);
        log.debug("{} Obtained request token", getLogPrefix());
    } catch (TwitterException e) {
        log.error("{} Error obtaining request token from Twitter: {}", getLogPrefix(), e.getErrorMessage());
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        return;
    }

    /* Save the context as a sub context to the authentication context */
    authenticationContext.addSubcontext(twitterContext, true);

    return;
}

From source file:org.n52.twitter.TwitterAccessTokenRetriever.java

License:Open Source License

public static void main(String args[]) throws Exception {
    String[] props = readProperties();
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(props[0], props[1]);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;// w  ww .j  a va2 s.  c om
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        LOGGER.info("Open the following URL and grant access to your account:");
        LOGGER.info(requestToken.getAuthorizationURL());
        LOGGER.info("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                LOGGER.error("Unable to get the access token.");
            } else {
                LOGGER.error(te.getErrorMessage(), te);
            }
        }
    }
    storeAccessToken(accessToken.getToken(), accessToken.getTokenSecret());
}

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 {//from w  w w.  ja v a  2  s . c o  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./*from  w w  w.jav  a2  s .  c o  m*/
 * 
 * @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());
        }
    }
}

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

License:BSD License

/**
 * OK action./*ww  w.  j  a v a  2s  .  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.openhab.action.twitter.internal.TwitterActionService.java

License:Open Source License

/**
 * Creates and returns a Twitter4J Twitter client.
 *
 * @return a new instance of a Twitter4J Twitter client.
 *//*from   w w  w  .  jav a 2s  .c  o m*/
private static twitter4j.Twitter createClient() {
    twitter4j.Twitter client = TwitterFactory.getSingleton();
    client.setOAuthConsumer(consumerKey, consumerSecret);
    return client;
}

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

License:Open Source License

/**
 * Get the twitter RequestToken//  w w  w .j a v a 2 s. c om
 * 
 * @return The twitter RequestToken
 * */
private RequestToken getTwitterRequestToken(String orcid) throws Exception {
    // If it exists, use it once and discard it
    if (requestTokenMap.containsKey(orcid)) {
        RequestToken result = requestTokenMap.get(orcid);
        requestTokenMap.remove(orcid);
        return result;
    } else {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(twitterKey, twitterSecret);
        RequestToken requestToken = twitter.getOAuthRequestToken();
        requestTokenMap.put(orcid, requestToken);
        return requestToken;
    }
}

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

License:Open Source License

/**
 * Get the twitter AccessToken//from w  w  w  . j a  va 2s.co m
 * 
 * @return The twitter AccessToken
 * */
private AccessToken getOAuthAccessToken(String orcid, String pin) throws Exception {
    RequestToken requestToken = getTwitterRequestToken(orcid);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(twitterKey, twitterSecret);
    return twitter.getOAuthAccessToken(requestToken, pin);
}