List of usage examples for twitter4j TwitterFactory getInstance
public Twitter getInstance()
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.mixare.utils.TwitterClient.java
License:Open Source License
/** * Query the twitter search API using oAuth 2.0 * @return//from ww w .java2 s . co m */ public static String queryData() { ConfigurationBuilder cb = new ConfigurationBuilder(); //to be configured in a properties... cb.setDebugEnabled(true).setOAuthConsumerKey("mt10dv6tTKacqlm14lw5w") .setOAuthConsumerSecret("4kRV1E1XIU3kj4JQj2R5LE1yct0RRaRl9sB5PpPrB0") .setOAuthAccessToken("390019380-IQ5VdvUKvxY9JOsTToEU8ElCabebc76H9X2g3QX4") .setOAuthAccessTokenSecret("ghJn4LTfDr7uHUCsbt6ycmpeVTwwpa3hZnXyEjyZvs"); cb.setJSONStoreEnabled(true); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); Query query = new Query(); query = query.geoCode(new GeoLocation(lat, lon), rad, Query.KILOMETERS); String jsonArrayAsString = "{\"results\":[";//start try { QueryResult result = twitter.search(query); int size = 0; for (Status status : result.getTweets()) { { if (status.getGeoLocation() != null) { String jsonSingleObject = DataObjectFactory.getRawJSON(status); if (size == 0) jsonArrayAsString += jsonSingleObject; else jsonArrayAsString += "," + jsonSingleObject; size++; } } } jsonArrayAsString += "]}";//close array return jsonArrayAsString; } catch (Exception e) { Log.e(Config.TAG, "Error querying twitter data :" + e); e.printStackTrace(); } return null; }
From source file:org.n52.twitter.dao.TwitterAbstractDAO.java
License:Open Source License
public TwitterAbstractDAO(AccessToken accessToken, String oauthConsumerKey, String oauthConsumerSecret) { LOGGER.debug("Using the following default values: Tweets to harvest: '{}', Tweets per request: '{}'", MAX_TWEETS_TO_HARVEST, TWEETS_TO_LOAD_PER_API_REQUEST); TwitterFactory factory = new TwitterFactory(); twitter = factory.getInstance(); twitter.setOAuthConsumer(oauthConsumerKey, oauthConsumerSecret); twitter.setOAuthAccessToken(accessToken); twitter.addRateLimitStatusListener(new RateLimitStatusListener() { @Override// www. ja v a 2 s .c o m public void onRateLimitStatus(RateLimitStatusEvent event) { LOGGER.debug("Remaining requests for the current period: {}", event.getRateLimitStatus().getRemaining()); if (event.getRateLimitStatus().getRemaining() <= 1) { try { LOGGER.debug("Going to sleep for {}s because rate limit is nearly reached.", (event.getRateLimitStatus().getSecondsUntilReset() + 5000)); Thread.sleep(event.getRateLimitStatus().getSecondsUntilReset() * 1000l + 5000); } catch (InterruptedException e) { LOGGER.error("Sleep interrupted", e); } } } @Override public void onRateLimitReached(RateLimitStatusEvent event) { } }); }
From source file:org.onebusaway.admin.service.impl.TwitterServiceImpl.java
License:Apache License
@PostConstruct private void setup() { // nothing to do if we are not configured properly if (StringUtils.isBlank(_consumerKey) || StringUtils.isBlank(_consumerSecret) || StringUtils.isBlank(_accessToken) || StringUtils.isBlank(_accessTokenSecret)) { _log.warn("Twitter service missing necessary configuration, exiting"); return;// www. j a va2 s .c om } try { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(_consumerKey).setOAuthConsumerSecret(_consumerSecret) .setOAuthAccessToken(_accessToken).setOAuthAccessTokenSecret(_accessTokenSecret); TwitterFactory twitterFactory = new TwitterFactory(configurationBuilder.build()); _twitter = twitterFactory.getInstance(); } catch (Exception any) { // don't let this failure prevent startup _log.error("Twitter integraton failed. Check spring configuration"); _log.error("Configuration exception:", any); } }
From source file:org.onehippo.forge.blog.components.socialmedia.TwitterListing.java
License:Apache License
/** * Builds up the {@link Twitter} object needed to communicate trhrough Twitter4J * * @param request current {@link org.hippoecm.hst.core.component.HstRequest} * @return {@link Twitter} or {@literal null} if configuration is missing in the HST *///from w w w . jav a 2 s . com private Twitter getTwitterObject(HstRequest request) { String token = getParameter(TOKEN, request); String tokenSecret = getParameter(TOKEN_SECRET, request); String consumerKey = getParameter(CONSUMER_KEY, request); String consumerSecret = getParameter(CONSUMER_SECRET, request); boolean missingConfiguration = false; if (StringUtils.isBlank(token)) { missingConfiguration = true; log.info("Missing or empty parameter 'token'"); } else if (StringUtils.isBlank(tokenSecret)) { missingConfiguration = true; log.info("Missing or empty parameter 'tokenSecret'"); } else if (StringUtils.isBlank(consumerKey)) { missingConfiguration = true; log.info("Missing or empty parameter 'consumerKey'"); } else if (StringUtils.isBlank(consumerSecret)) { missingConfiguration = true; log.info("Missing or empty parameter 'consumerSecret'"); } if (missingConfiguration) { return null; } ConfigurationBuilder cb = new ConfigurationBuilder().setOAuthAccessToken(token) .setOAuthAccessTokenSecret(tokenSecret).setOAuthConsumerKey(consumerKey) .setOAuthConsumerSecret(consumerSecret); TwitterFactory twitterFactory = new TwitterFactory(cb.build()); return twitterFactory.getInstance(); }
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 ww.j a v a 2 s. c om*/ 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 . ja va 2 s .com*/ * * @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.//w w w. ja v a2 s . 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.ow2.frascati.akka.fabric.peakforecast.lib.TwitterImpl.java
License:Open Source License
@Override public void updateStatus(String message) { try {// w w w .j a v a2s.co m ConfigurationBuilder cb = new ConfigurationBuilder(); //info OAuth settings de l'application twitter tweetpeakforecast enregistr par l'utilisateur @peakforecast cb.setDebugEnabled(true).setOAuthConsumerKey("0PqersXnGOn7AirB13jszw") .setOAuthConsumerSecret("r3qyCuhmwRI90JY04kqcYtn5yEl6yaW1UoRhAY08Q") .setOAuthAccessToken("1598158057-epoKcN3Lfz405zjNZQ2rl5cx74lthvBZ93cCsfj") .setOAuthAccessTokenSecret("6YwDPdjS7OpqDHb6PsmW0beOjCgjITzDGYV89gtQU"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); Status status = twitter.updateStatus(message); System.out.println("Successfully updated the status to [" + status.getText() + "]."); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.rhq.enterprise.server.plugins.alertMicroblog.MicroblogSender.java
License:Open Source License
@Override public SenderResult send(Alert alert) { SenderResult result;//from w w w . j a va 2 s .c o m 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; }