List of usage examples for twitter4j.conf ConfigurationBuilder setOAuthAccessToken
public ConfigurationBuilder setOAuthAccessToken(String oAuthAccessToken)
From source file:org.vsepml.storm.twitter.StormTwitterStreamSpout.java
License:Apache License
@Override public void open(Map map, TopologyContext topologyContext, SpoutOutputCollector spoutOutputCollector) { this.collector = spoutOutputCollector; queue = new LinkedBlockingQueue<Status>(1000); StatusListener listener = new StatusListener() { public void onStatus(Status status) { queue.offer(status);/*from ww w. j ava 2 s . com*/ } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } @Override public void onScrubGeo(long l, long l1) { } @Override public void onStallWarning(StallWarning stallWarning) { } public void onException(Exception ex) { ex.printStackTrace(); } }; ConfigurationBuilder twitterConf = new ConfigurationBuilder(); twitterConf.setIncludeEntitiesEnabled(true); twitterConf.setUseSSL(true); twitterConf.setUserStreamRepliesAllEnabled(true); twitterConf.setOAuthAccessToken(accessToken); twitterConf.setOAuthAccessTokenSecret(accessTokenSecret); twitterConf.setOAuthConsumerKey(consumerKey); twitterConf.setOAuthConsumerSecret(consumerSecret); twitterStream = new TwitterStreamFactory(twitterConf.build()).getInstance(); twitterStream.addListener(listener); // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously. twitterStream.sample(); }
From source file:org.wso2.carbon.connector.twitter.TwitterClientLoader.java
License:Open Source License
public Twitter loadApiClient() throws TwitterException { Twitter twitter;//w w w. ja v a2s. c o m if (messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_CONSUMER_KEY) != null && messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_CONSUMER_SECRET) != null && messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_ACCESS_TOKEN) != null && messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_ACCESS_TOKEN_SECRET) != null) { ConfigurationBuilder build = new ConfigurationBuilder(); build.setJSONStoreEnabled(true); build.setOAuthAccessToken( messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_ACCESS_TOKEN).toString()); build.setOAuthAccessTokenSecret(messageContext .getProperty(TwitterConnectConstants.TWITTER_USER_ACCESS_TOKEN_SECRET).toString()); build.setOAuthConsumerKey( messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_CONSUMER_KEY).toString()); build.setOAuthConsumerSecret( messageContext.getProperty(TwitterConnectConstants.TWITTER_USER_CONSUMER_SECRET).toString()); twitter = new TwitterFactory(build.build()).getInstance(); twitter.verifyCredentials(); } else { twitter = new TwitterFactory().getInstance(); } return twitter; }
From source file:Origin.Mypage.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TwitterException { response.setContentType("text/html;charset=UTF-8"); /* TODO output your page here. You may use following sample code. */ ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true);/*from ww w . j a v a 2 s. c om*/ cb.setOAuthConsumerKey(CONSUMER_KEY); cb.setOAuthConsumerSecret(CONSUMER_SECRET); cb.setOAuthAccessToken(ACCESS_TOKEN); cb.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); User user = twitter.verifyCredentials(); request.setCharacterEncoding("UTF-8"); HttpSession hs = request.getSession(); UserData ud = (UserData) hs.getAttribute("ud"); String search = ud.getLine() + "?"; //String search= request.getParameter("searchtweet"); Query query = new Query(); query.setCount(100); query.setQuery(search); QueryResult queryresult = null; try { queryresult = twitter.search(query); } catch (TwitterException e1) { e1.printStackTrace(); } ArrayList<String> userID = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { userID.add(tweet.getUser().getScreenName()); } ArrayList<String> profileimg = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { profileimg.add(tweet.getUser().getBiggerProfileImageURL()); } ArrayList<String> username = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { username.add(tweet.getUser().getName() + "<br>" + "@" + tweet.getUser().getScreenName()); } ArrayList<String> usernameURL = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { username.add(tweet.getUser().getURL()); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss"); ArrayList<String> resulttweet = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { resulttweet.add(tweet.getText() + "<br>" + sdf.format(tweet.getCreatedAt())); } request.setAttribute("search", search); request.setAttribute("userID", userID); request.setAttribute("profileimg", profileimg); request.setAttribute("username", username); request.setAttribute("resulttweet", resulttweet); request.setAttribute("usernameURL", usernameURL); request.getRequestDispatcher("/mypage.jsp").forward(request, response); }
From source file:Origin.Searchtweet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TwitterException { response.setContentType("text/html;charset=UTF-8"); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true);//from ww w . j av a 2 s . c o m cb.setOAuthConsumerKey(CONSUMER_KEY); cb.setOAuthConsumerSecret(CONSUMER_SECRET); cb.setOAuthAccessToken(ACCESS_TOKEN); cb.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); User user = twitter.verifyCredentials(); request.setCharacterEncoding("UTF-8"); String search = "?" + request.getParameter("searchtweet"); //String search= request.getParameter("searchtweet"); Query query = new Query(); query.setCount(100); query.setQuery(search); QueryResult queryresult = null; try { queryresult = twitter.search(query); } catch (TwitterException e1) { e1.printStackTrace(); } ArrayList<String> userID = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { userID.add(tweet.getUser().getScreenName()); } ArrayList<String> profileimg = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { profileimg.add(tweet.getUser().getBiggerProfileImageURL()); } ArrayList<String> username = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { username.add(tweet.getUser().getName() + "<br>" + "@" + tweet.getUser().getScreenName()); } ArrayList<String> usernameURL = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { username.add(tweet.getUser().getURL()); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss"); ArrayList<String> resulttweet = new ArrayList<>(); for (Status tweet : queryresult.getTweets()) { resulttweet.add(tweet.getText() + "<br>" + sdf.format(tweet.getCreatedAt())); } request.setAttribute("search", search); request.setAttribute("userID", userID); request.setAttribute("profileimg", profileimg); request.setAttribute("username", username); request.setAttribute("resulttweet", resulttweet); request.setAttribute("usernameURL", usernameURL); request.getRequestDispatcher("/searchtweet.jsp").forward(request, response); }
From source file:Origin.Timeline.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true);//from ww w . j av a 2 s . com cb.setOAuthConsumerKey(CONSUMER_KEY); cb.setOAuthConsumerSecret(CONSUMER_SECRET); cb.setOAuthAccessToken(ACCESS_TOKEN); cb.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET); try { Twitter twitter = new TwitterFactory(cb.build()).getInstance(); User user = twitter.verifyCredentials(); Paging paging = new Paging(1, 200); ResponseList<Status> userstatus = twitter.getHomeTimeline(paging); request.setAttribute("userstatus", userstatus); request.getRequestDispatcher("/timeline.jsp").forward(request, response); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } }
From source file:Origin.Tweet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TwitterException { response.setContentType("text/html;charset=UTF-8"); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true);// w ww . j a va 2s .co m cb.setOAuthConsumerKey(CONSUMER_KEY); cb.setOAuthConsumerSecret(CONSUMER_SECRET); cb.setOAuthAccessToken(ACCESS_TOKEN); cb.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET); try { Twitter twitter = new TwitterFactory(cb.build()).getInstance(); User user = twitter.verifyCredentials(); HttpSession session = request.getSession(); request.setCharacterEncoding("UTF-8"); //String tweet = encode(request.getParameter("tweet")); String tweet = request.getParameter("tweet"); Status status = twitter.updateStatus(tweet); session.setAttribute("tweet", tweet); request.getRequestDispatcher("/tweet.jsp").forward(request, response); } catch (TwitterException e1) { e1.printStackTrace(); } }
From source file:Principal.Tracker_Twitter.java
License:Minecraft Mod Public
public void guardarResultados_Twitter(List<ObjetoBuscar> lista, BD base, int contadorBase, int TokenIndice) throws NoSuchAlgorithmException, KeyManagementException { int nuevoContadorBase = 0; if (contadorBase >= lista.size()) { System.out.println("Termino en:" + contadorBase); } else {/*from w ww . j a v a 2 s. c om*/ System.out.println("---------------------------------------------------------------------:P"); TrustManager[] trustAllCerts = { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); System.out.println("Token : " + TokenIndice); System.out.println(consumerKey[TokenIndice]); try { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey(consumerKey[TokenIndice]); cb.setOAuthConsumerSecret(this.consumerSecret[TokenIndice]); cb.setOAuthAccessToken(this.token[TokenIndice]); cb.setOAuthAccessTokenSecret(this.tokenSecret[TokenIndice]); Twitter unauthenticatedTwitter = new TwitterFactory(cb.build()).getInstance(); for (int numtTweets = contadorBase; numtTweets < contadorBase + 5; numtTweets++) { if (((ObjetoBuscar) lista.get(numtTweets)).getUrl().equals("") || ((ObjetoBuscar) lista.get(numtTweets)).getUrl() == null) { } else { System.out.println("Usuario: " + ((ObjetoBuscar) lista.get(numtTweets)).getUrl()); String usuariosinArroba = ((ObjetoBuscar) lista.get(numtTweets)).getUrl().replace("@", ""); System.out.println("" + usuariosinArroba); try { User usuario = unauthenticatedTwitter.showUser(usuariosinArroba); List<Status> ret = unauthenticatedTwitter.getRetweetsOfMe(); List<Status> favoritos = unauthenticatedTwitter.getFavorites(); Paging paging = new Paging(1, 1000); ResponseList<Status> statuses = unauthenticatedTwitter.getUserTimeline(usuario.getId(), paging); System.out.println("Followers: " + usuario.getFollowersCount()); System.out.println("Yo sigo: " + usuario.getFriendsCount()); List<String> listaTweets = new ArrayList(); List<Long> ListaRettewts = new ArrayList(); List<Integer> ListaFavoritos = new ArrayList(); List<Integer> ListaMenciones = new ArrayList(); List<Date> ListaFecha = new ArrayList(); List<Long> ListaIds = new ArrayList(); for (Status sta : statuses) { ListaIds.add(Long.valueOf(sta.getId())); listaTweets.add(sta.getText()); ListaRettewts.add(Long.valueOf(Long.parseLong(sta.getRetweetCount() + ""))); ListaMenciones.add(Integer.valueOf(sta.getUserMentionEntities().length)); ListaFecha.add(sta.getCreatedAt()); ListaFavoritos.add(Integer.valueOf(sta.getFavoriteCount())); } for (int i = 0; i < listaTweets.size(); i++) { base.guardarTrackTwitter_Log((Long) ListaIds.get(i), ((ObjetoBuscar) lista.get(numtTweets)).getUrl(), (String) listaTweets.get(i), (Date) ListaFecha.get(i), (Long) ListaRettewts.get(i), ((Integer) ListaFavoritos.get(i)).intValue(), ((Integer) ListaMenciones.get(i)).intValue()); } } catch (Exception e) { System.err.println("Entro al Try por :" + e); } nuevoContadorBase = numtTweets; } } System.out.println("Numero de Contador Base:" + nuevoContadorBase); guardarResultados_Twitter(lista, base, nuevoContadorBase + 1, TokenIndice + 1); } catch (NumberFormatException e) { System.err.println("Fallo por :" + e); } } }
From source file:Recursos.Notificacion.java
/** * Constructor de la clase Notificacion/*from www .ja v a2s. c o m*/ * * inicializa todos los medios para hacer la coneccion de la cuenta del * twitter conn la aplicaccion */ public Notificacion() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey("STFH7e9yQ8K7pIgs7oZSmsUB8"); cb.setOAuthConsumerSecret("6Uj5BMITSyd17UNFxTLi47k39KkOMuwIszCgXkc8AC3mNJEp3U"); cb.setOAuthAccessToken("133844036-u3qdbqgsxlSMeNWa5NzFrSCbnjAI7ExrRDHFrWw9"); cb.setOAuthAccessTokenSecret("5m7rBhbEQmll0bGtPGC3sqE3mo3emjmrjKrCBg26t9jhG"); twitter = new TwitterFactory(cb.build()).getInstance(); }
From source file:social.controller.PostToSocial.java
@Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); boolean face = false; boolean twit = false; try {// w w w.ja v a2 s. c o m getSqlMethodsInstance().session = request.getSession(); Integer user_id = (Integer) getSqlMethodsInstance().session.getAttribute("UID"); String htmlString = (String) getSqlMethodsInstance().session.getAttribute("htmlString"); String isFacebook = request.getParameter("isFacebook"); String isTwitter = request.getParameter("isTwitter"); String getImageFile = request.getParameter("imageToPost"); String getFile = request.getParameter("imagePost"); String url = request.getParameter("url"); String file_image_path = AppConstants.LAYOUT_IMAGES_HOME + File.separator + getImageFile; // String file_image_path = getServletContext().getRealPath("") + "/temp/"+getImageFile; String imagePostURL = ServletUtil.getServerName(request.getServletContext()); //String imagePostURL = AppConstants.LAYOUT_IMAGES_HOME + getImageFile; if (isFacebook.equalsIgnoreCase("true")) { String accessToken = request.getParameter("accesstoken"); String posttext = request.getParameter("postText"); String title = request.getParameter("title"); String description = request.getParameter("description"); String url1 = request.getParameter("url"); facebook = new FacebookFactory().getInstance(); facebook.setOAuthAppId("592852577521569", "a87cc0c30d792fa5dd0aaef6b43994ef"); facebook.setOAuthPermissions("publish_actions, publish_pages,manage_pages"); // File file = new File(file_image_path); facebook.setOAuthAccessToken(new AccessToken(accessToken)); if (title == "") { Media media = new Media(new File(file_image_path)); PhotoUpdate update = new PhotoUpdate(media); update.message(posttext); facebook.postPhoto(update); } else { logger.info(title); PostUpdate post = new PostUpdate(posttext).picture(new URL( imagePostURL + "DownloadImage?image_type=LAYOUT_IMAGES&image_name=" + getImageFile)) .name(title).link(new URL(url1)).description(description); facebook.postFeed(post); } try { getSqlMethodsInstance().setSocialPostHistory(user_id, htmlString, false, true, getImageFile); } catch (Exception ex) { Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, ex.getCause()); Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, ex.getMessage()); } } if (isTwitter.equalsIgnoreCase("true")) { try { AccessToken accTok = null; String shortUrl = ""; ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder(); twitterConfigBuilder.setDebugEnabled(true); twitterConfigBuilder.setOAuthConsumerKey("K7TJ3va8cyAeh6oN3Hia91S2o"); twitterConfigBuilder .setOAuthConsumerSecret("IWUt2aDVTHgUc8N0qI0cF1Z1dTAEQ7CSgnBymZNr3BPSmtkNHL"); twitterConfigBuilder.setOAuthAccessToken(request.getParameter("twittweraccestoken")); twitterConfigBuilder.setOAuthAccessTokenSecret(request.getParameter("twitterTokenSecret")); Twitter twitter = new TwitterFactory(twitterConfigBuilder.build()).getInstance(); String statusMessage = request.getParameter("text").replace("bit.ly/1XOkJo", ""); shortUrl = request.getParameter("shorturl"); if (shortUrl.length() > 0) { String StatusMessageWithoutUrl = statusMessage.substring(0, statusMessage.length()); if (StatusMessageWithoutUrl.length() + shortUrl.length() < 140) { statusMessage = StatusMessageWithoutUrl + " " + shortUrl; } else { int urlLength = shortUrl.length() + 1; int statusLength = 115 - urlLength; statusMessage = StatusMessageWithoutUrl.substring(0, statusLength); statusMessage = statusMessage + " " + shortUrl; } } File file = new File(file_image_path); int count = statusMessage.length(); StatusUpdate status = new StatusUpdate(statusMessage); // set the image to be uploaded here. status.setMedia(file); twitter.updateStatus(status); try { getSqlMethodsInstance().setSocialPostHistory(user_id, htmlString, false, true, getImageFile); } catch (Exception ex) { Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, ex.getCause()); Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, ex.getMessage()); } } catch (TwitterException te) { PrintWriter out1 = response.getWriter(); out1.println("Twitter Exception: " + te.getMessage()); Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, te.getCause()); Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, te.getMessage()); } catch (Exception e) { Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, e); Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, e.getMessage()); } } } catch (FacebookException e) { Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, e.getCause()); Logger.getLogger(PostToSocial.class.getName()).log(Level.SEVERE, null, e.getMessage()); } }
From source file:source.TwitterSource.java
License:Apache License
/** * The initialization method for the Source. The context contains all the * Flume configuration info, and can be used to retrieve any configuration * values necessary to set up the Source. * * @param context Key-value store used to pass configuration information * throughout the system.// w w w . j ava 2s . co m */ @Override public void configure(Context context) { consumerKey = context.getString(TwitterSourceConstants.CONSUMER_KEY); consumerSecret = context.getString(TwitterSourceConstants.CONSUMER_SECRET); accessToken = context.getString(TwitterSourceConstants.ACCESS_TOKEN); accessTokenSecret = context.getString(TwitterSourceConstants.ACCESS_TOKEN_SECRET); String swString = context.getString(TwitterSourceConstants.SW_LNG_LAT); String neString = context.getString(TwitterSourceConstants.NE_LNG_LAT); if (swString != null && neString != null) { String[] sw = swString.split(","); String[] ne = neString.split(","); if (sw.length == 2 && ne.length == 2) { for (int i = 0; i < 2; i++) { locations[0][i] = Double.parseDouble(sw[i].trim()); locations[1][i] = Double.parseDouble(ne[i].trim()); } } else { locations = null; } } else { locations = null; } String keywordString = context.getString(TwitterSourceConstants.KEYWORDS); if (keywordString != null) { keywords = keywordString.split(","); for (int i = 0; i < keywords.length; i++) { keywords[i] = keywords[i].trim(); } } ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey(consumerKey); cb.setOAuthConsumerSecret(consumerSecret); cb.setOAuthAccessToken(accessToken); cb.setOAuthAccessTokenSecret(accessTokenSecret); cb.setJSONStoreEnabled(true); cb.setIncludeEntitiesEnabled(true); cb.setIncludeRTsEnabled(true); twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); }