Example usage for twitter4j.conf ConfigurationBuilder setOAuthConsumerKey

List of usage examples for twitter4j.conf ConfigurationBuilder setOAuthConsumerKey

Introduction

In this page you can find the example usage for twitter4j.conf ConfigurationBuilder setOAuthConsumerKey.

Prototype

public ConfigurationBuilder setOAuthConsumerKey(String oAuthConsumerKey) 

Source Link

Usage

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 w w  w  . j  a v a2s  .  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   w  ww .  j a v  a2s . 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();
        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);//from  w ww .  j  a va 2  s. c o  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.  ja v  a2s  .  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// w w w .j a  v a2  s .  com
 *
 * 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:Servlet.TwitterAuthServlet.java

License:Apache License

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/* w  w  w  .ja v  a2  s  . co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setOAuthConsumerKey(TwitterApp.CONSUMER_KEY);
    cb.setOAuthConsumerSecret(TwitterApp.CONSUMER_SECRET);

    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    request.getSession().setAttribute("twitter", twitter);
    try {
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/callback");

        System.out.println(callbackURL);

        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());

        System.out.println("Authentication " + requestToken.getAuthenticationURL());
        System.out.println("Authorization " + requestToken.getAuthorizationURL());

        request.getSession().setAttribute("requestToken", requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());
    } catch (TwitterException e) {
        throw new ServletException(e);
    }
}

From source file:servlets.TwitterConnectionServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    System.out.println("Start TwitterConnectionServlet.doGet");

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(UtilTwitter.CONSUMER_KEY);
    builder.setOAuthConsumerSecret(UtilTwitter.CONSUMER_SECRET);

    TwitterFactory factory = new TwitterFactory(builder.build());
    Twitter twitter = factory.getInstance();

    RequestToken requestToken;/*w  w  w. ja va  2  s . co m*/

    try {
        requestToken = twitter.getOAuthRequestToken(UtilTwitter.CALL_BACK_URL);
        String url = requestToken.getAuthenticationURL();

        System.out.println("End TwitterConnectionServlet.doGet");
        response.sendRedirect(url);
    } catch (TwitterException e) {
        e.printStackTrace();
    }
}

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 {//from w  w w.j a va2  s. co 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 .java  2s .c  o 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();

}

From source file:toninbot.ToninBot.java

/**
 * @param args the command line arguments
 *///  w  ww.  j  a  va2s . c  o m
public static void main(String[] args) {

    AccessToken accessToken = new AccessToken(Credenciales.token, Credenciales.tokenSecret);
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(Credenciales.consumerKey);
    builder.setOAuthConsumerSecret(Credenciales.consumerSecret);

    Configuration configuration = builder.build();
    TwitterStreamFactory twStreamFactory = new TwitterStreamFactory(configuration);
    TwitterStream twitterStream = twStreamFactory.getInstance();
    twitterStream.setOAuthAccessToken(accessToken);

    ToninStatusListener listener = new ToninStatusListener();
    twitterStream.addListener(listener);

    FilterQuery filtre = new FilterQuery();
    filtre.follow(184742273L, 2841338087L);//Allegue y proyectoPSIa1
    //filtre.follow(2841338087L);//proyectoPSIa1

    twitterStream.filter(filtre);
}