Example usage for twitter4j Paging Paging

List of usage examples for twitter4j Paging Paging

Introduction

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

Prototype

public Paging() 

Source Link

Usage

From source file:alberapps.java.noticias.tw.tw4j.ProcesarTwitter4j.java

License:Open Source License

/**
 * Recuperar el timeline del usuario indicado
 *
 * @param twuser//from ww  w  .  j a va  2  s  .c  o m
 * @param url
 * @param elementos
 * @return listado
 */
public List<TwResultado> recuperarTimeline(String twuser, String url, int elementos) throws Exception {

    List<TwResultado> listaResultados = new ArrayList<>();

    Paging pagina = new Paging();

    pagina.setCount(elementos);

    ResponseList<Status> timeline = twitter.getUserTimeline(twuser, pagina);

    listaResultados = new ArrayList<>();

    Status linea = timeline.get(0);

    TwResultado resultado = null;

    for (int i = 0; i < timeline.size(); i++) {

        resultado = new TwResultado();

        resultado.setId(Long.toString(timeline.get(i).getId()));
        resultado.setFechaDate(timeline.get(i).getCreatedAt());

        resultado.setFecha(formatearFechaTw(resultado.getFechaDate()));

        resultado.setNombreCompleto(timeline.get(i).getUser().getName());
        resultado.setUsuario("@" + timeline.get(i).getUser().getScreenName());
        resultado.setMensaje(timeline.get(i).getText());
        resultado.setImagen(timeline.get(i).getUser().getBiggerProfileImageURL());

        resultado.setRetweet(timeline.get(i).isRetweet());

        // Imagen de perfil
        // resultado.setImagenBitmap(recuperaImagen(resultado.getImagen()));

        resultado.setUrl(url);

        resultado.setRespuestaId(timeline.get(i).getInReplyToUserId());

        Log.d("twitter", "resp: " + resultado.getRespuestaId());

        listaResultados.add(resultado);

    }

    //throw new Exception("prueba");

    return listaResultados;

}

From source file:com.cruta.hecas.twitter.MyTwitter.java

public void Tweet() {
    try {/*from  w  ww .jav a2s  .c  o m*/

        System.out.println("voy a enviar");
        Twitter twitter;
        ConfigurationBuilder cb = new ConfigurationBuilder();

        cb.setDebugEnabled(true).setOAuthConsumerKey("4W5InvFtHgtZAQBa6QQeQFWlA")
                .setOAuthConsumerSecret("t3nCC1RKhAcqjZPoHmF4Osa2VzY9kTBt0d4XAn00H49jXHtfgT")
                .setOAuthAccessToken("15616431-NXjouNhzTBYQYQqRHPJnMKakh0RyZSHvhss7RYrTm")
                .setOAuthAccessTokenSecret("gC1hIbqXOU8QYjjcyYKL8P2uW2wVzSu3X5TfBO3iMqdo2");
        twitter = new TwitterFactory(cb.build()).getInstance();

        Paging pagina = new Paging();

        Status tweetEscrito = twitter.updateStatus("Holas desde hecas");
        System.out.println("twett enviado");
    } catch (Exception ex) {
        JSFUtil.errorDialog("Tweet()", ex.getLocalizedMessage());
        System.out.println("error() " + ex.getLocalizedMessage());
    }
}

From source file:com.cruta.hecas.twitter.MyTwitter.java

public void Tweet(String mensaje) {
    try {//ww w.ja v  a  2s  .c o m

        Twitter twitter;
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("4W5InvFtHgtZAQBa6QQeQFWlA")
                .setOAuthConsumerSecret("t3nCC1RKhAcqjZPoHmF4Osa2VzY9kTBt0d4XAn00H49jXHtfgT")
                .setOAuthAccessToken("15616431-NXjouNhzTBYQYQqRHPJnMKakh0RyZSHvhss7RYrTm")
                .setOAuthAccessTokenSecret("gC1hIbqXOU8QYjjcyYKL8P2uW2wVzSu3X5TfBO3iMqdo2");
        twitter = new TwitterFactory(cb.build()).getInstance();

        Paging pagina = new Paging();

        Status tweetEscrito = twitter.updateStatus(mensaje);
        System.out.println("twett enviado");
    } catch (Exception ex) {
        JSFUtil.errorDialog("Tweet()", ex.getLocalizedMessage());
        System.out.println("tweet() " + ex.getLocalizedMessage());
    }
}

From source file:com.dwdesign.tweetings.loader.Twitter4JStatusLoader.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from w w  w .  j  a  v  a2  s  . c om*/
public SynchronizedStateSavedList<ParcelableStatus, Long> loadInBackground() {
    final SynchronizedStateSavedList<ParcelableStatus, Long> data = getData();
    List<Status> statuses = null;

    final Context context = getContext();
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final int load_item_limit = prefs.getInt(PREFERENCE_KEY_LOAD_ITEM_LIMIT,
            PREFERENCE_DEFAULT_LOAD_ITEM_LIMIT);
    try {
        final Paging paging = new Paging();
        paging.setCount(load_item_limit);
        if (mMaxId > 0) {
            paging.setMaxId(mMaxId);
        }
        if (mSinceId > 0) {
            paging.setSinceId(mSinceId);
        }
        statuses = getStatuses(paging);
    } catch (final TwitterException e) {
        e.printStackTrace();
    }
    if (statuses != null) {
        final boolean insert_gap = load_item_limit == statuses.size() && data.size() > 0;
        final Status min_status = statuses.size() > 0 ? Collections.min(statuses) : null;
        final long min_status_id = min_status != null ? min_status.getId() : -1;
        for (final Status status : statuses) {
            final long id = status.getId();
            deleteStatus(id);
            data.add(new ParcelableStatus(status, mAccountId,
                    min_status_id > 0 && min_status_id == id && insert_gap,
                    mInlineImagePreviewDisplayOption == INLINE_IMAGE_PREVIEW_DISPLAY_OPTION_CODE_LARGE_HIGH));
        }
    }
    try {
        final List<ParcelableStatus> statuses_to_remove = new ArrayList<ParcelableStatus>();
        for (final ParcelableStatus status : data) {
            if (isFiltered(context, status.screen_name, status.source, status.text_plain) && !status.is_gap) {
                statuses_to_remove.add(status);
            }
        }
        data.removeAll(statuses_to_remove);
        Collections.sort(data);
    } catch (final ConcurrentModificationException e) {
        Log.w(LOGTAG, e);
    }
    return data;
}

From source file:com.javielinux.api.loaders.LoadMoreTweetDownLoader.java

License:Apache License

@Override
public BaseResponse loadInBackground() {

    try {//  w  w  w . java  2  s  .co  m

        LoadMoreTweetDownResponse response = new LoadMoreTweetDownResponse();

        PreferenceManager.setDefaultValues(getContext(), R.xml.preferences, false);
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getContext());
        int maxDownloadTweet = Integer.parseInt(pref.getString("prf_n_max_download", "60"));
        if (maxDownloadTweet <= 0)
            maxDownloadTweet = 60;

        ConnectionManager.getInstance().open(getContext());

        Twitter twitter = ConnectionManager.getInstance().getTwitter(request.getUserId());

        Paging p = new Paging();
        p.setCount(maxDownloadTweet);
        p.setSinceId(request.getSinceId());
        p.setMaxId(request.getMaxId());

        ResponseList<Status> statii = null;

        try {
            statii = twitter.getHomeTimeline(p);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }

        boolean breakTimeline = false;

        if (statii != null && statii.size() >= maxDownloadTweet - 10) {
            p = new Paging(1, 10);
            p.setSinceId(request.getSinceId());
            p.setMaxId(statii.get(statii.size() - 1).getId());
            if (twitter.getHomeTimeline().size() > 0) {
                breakTimeline = true;
                response.setHasMoreTweets(true);
            }
        }

        if (statii != null) {

            if (statii.size() > 0) {

                try {
                    DataFramework.getInstance().open(getContext(), Utils.packageName);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                List<InfoTweet> tweets = new ArrayList<InfoTweet>();
                for (Status status : statii) {
                    tweets.add(new InfoTweet(status));
                }
                response.setTweets(tweets);

                long nextId = 1;
                Cursor c = DataFramework.getInstance().getCursor("tweets_user",
                        new String[] { DataFramework.KEY_ID }, null, null, null, null,
                        DataFramework.KEY_ID + " desc", "1");
                if (!c.moveToFirst()) {
                    c.close();
                    nextId = 1;
                } else {
                    long Id = c.getInt(0) + 1;
                    c.close();
                    nextId = Id;
                }

                try {
                    boolean isFirst = true;
                    for (int i = statii.size() - 1; i >= 0; i--) {
                        User u = statii.get(i).getUser();
                        if (u != null) {
                            ContentValues args = new ContentValues();
                            args.put(DataFramework.KEY_ID, "" + nextId);
                            args.put("type_id", TweetTopicsUtils.TWEET_TYPE_TIMELINE);
                            args.put("user_tt_id", "" + request.getUserId());
                            if (u.getProfileImageURL() != null) {
                                args.put("url_avatar", u.getProfileImageURL().toString());
                            } else {
                                args.put("url_avatar", "");
                            }
                            args.put("username", u.getScreenName());
                            args.put("fullname", u.getName());
                            args.put("user_id", "" + u.getId());
                            args.put("tweet_id", Utils.fillZeros("" + statii.get(i).getId()));
                            args.put("source", statii.get(i).getSource());
                            args.put("to_username", statii.get(i).getInReplyToScreenName());
                            args.put("to_user_id", "" + statii.get(i).getInReplyToUserId());
                            args.put("date", String.valueOf(statii.get(i).getCreatedAt().getTime()));
                            if (statii.get(i).getRetweetedStatus() != null) {
                                args.put("is_retweet", 1);
                                args.put("retweet_url_avatar", statii.get(i).getRetweetedStatus().getUser()
                                        .getProfileImageURL().toString());
                                args.put("retweet_username",
                                        statii.get(i).getRetweetedStatus().getUser().getScreenName());
                                args.put("retweet_source", statii.get(i).getRetweetedStatus().getSource());
                                String t = Utils.getTwitLoger(statii.get(i).getRetweetedStatus());
                                if (t.equals("")) {
                                    args.put("text", statii.get(i).getRetweetedStatus().getText());
                                    args.put("text_urls",
                                            Utils.getTextURLs(statii.get(i).getRetweetedStatus()));
                                } else {
                                    args.put("text", t);
                                }
                                args.put("is_favorite", 0);
                            } else {
                                String t = Utils.getTwitLoger(statii.get(i));
                                if (t.equals("")) {
                                    args.put("text", statii.get(i).getText());
                                    args.put("text_urls", Utils.getTextURLs(statii.get(i)));
                                } else {
                                    args.put("text", t);
                                }

                                if (statii.get(i).isFavorited()) {
                                    args.put("is_favorite", 1);
                                }
                            }

                            if (statii.get(i).getGeoLocation() != null) {
                                args.put("latitude", statii.get(i).getGeoLocation().getLatitude());
                                args.put("longitude", statii.get(i).getGeoLocation().getLongitude());
                            }
                            args.put("reply_tweet_id", statii.get(i).getInReplyToStatusId());

                            if (breakTimeline && isFirst)
                                args.put("has_more_tweets_down", 1);

                            DataFramework.getInstance().getDB().insert("tweets_user", null, args);

                            nextId++;

                            if (isFirst)
                                isFirst = false;
                        }

                    }

                } catch (SQLException e) {
                    e.printStackTrace();
                }

                DataFramework.getInstance().close();

            }

        }

        return response;

    } catch (TwitterException twitterException) {
        twitterException.printStackTrace();
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setError(twitterException, twitterException.getMessage());
        return errorResponse;
    } catch (Exception exception) {
        exception.printStackTrace();
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setError(exception, exception.getMessage());
        return errorResponse;
    }

}

From source file:com.joanzapata.android.twitter.service.TwitterService.java

License:Apache License

public List<Status> getTweetsBefore(String username, Status beforeTweet) {
    try {/*from w  ww  .  j  a  v  a  2 s.c  o m*/
        final Paging paging = new Paging().count(TWEET_COUNT);
        if (beforeTweet != null)
            paging.maxId(beforeTweet.getId() - 1);
        final ResponseList<Status> userTimeline = twitter.getUserTimeline(username, paging);
        if (userTimeline == null)
            return new ArrayList<Status>();
        return userTimeline;
    } catch (TwitterException e) {
        Log.e(TAG, "", e);
        return null;
    }
}

From source file:com.joshlong.esb.springintegration.modules.social.twitter.TwitterMessageSource.java

License:Apache License

public Message<Tweet> receive() {
    Assert.state(this.twitterMessageType != null, "the twitterMessageType can't be null!");
    Assert.state(cachedStatuses != null, "the cachedStatuses can't be null!");

    if (cachedStatuses.peek() == null) {
        Paging paging = new Paging();
        paging.setCount(getPagingCount());

        if (-1 != lastStatusIdRetreived) {
            paging.sinceId(lastStatusIdRetreived);
        }/*from   w ww.  ja  v  a 2 s . c  o m*/

        try {
            List<Status> statuses = new ArrayList<Status>();

            switch (getTwitterMessageType()) {
            case DM:
                throw new UnsupportedOperationException("we don't support receiving direct mentions yet!");

            case FRIENDS:
                statuses = twitter.getFriendsTimeline(paging);

                break;

            case MENTIONS:
                statuses = twitter.getMentions(paging);

                break;
            }

            if (cachedStatuses.peek() == null) {
                for (Status status : statuses) {
                    this.cachedStatuses.add(buildTweetFromStatus(status));
                }
            }
        } catch (TwitterException e) {
            logger.info(ExceptionUtils.getFullStackTrace(e));
            throw new RuntimeException(e);
        }
    }

    if (cachedStatuses.peek() != null) {
        // size() == 0 would be more obvious a test, but size() isn't constant time
        Tweet cachedStatus = cachedStatuses.poll();
        lastStatusIdRetreived = cachedStatus.getTweetId();

        return MessageBuilder.withPayload(cachedStatus).build();
    }

    return null;
}

From source file:com.marpies.ane.twitter.functions.GetDirectMessagesFunction.java

License:Apache License

private Paging getPaging(int count, long sinceID, long maxID) {
    Paging paging = null;/*from  w w  w  .  ja v a 2  s  . co  m*/
    if (count != 20) {
        paging = new Paging();
        paging.setCount(count);
    }
    if (sinceID >= 0) {
        paging = (paging == null) ? new Paging() : paging;
        paging.setSinceId(sinceID);
    }
    if (maxID >= 0) {
        paging = (paging == null) ? new Paging() : paging;
        paging.setMaxId(maxID);
    }
    return paging;
}

From source file:com.marpies.ane.twitter.functions.GetSentDirectMessagesFunction.java

License:Apache License

private Paging getPaging(int count, long sinceID, long maxID, int page) {
    Paging paging = null;/*  ww w.  j a  v  a2 s.co  m*/
    if (count != 20) {
        paging = new Paging();
        paging.setCount(count);
    }
    if (sinceID >= 0) {
        paging = (paging == null) ? new Paging() : paging;
        paging.setSinceId(sinceID);
    }
    if (maxID >= 0) {
        paging = (paging == null) ? new Paging() : paging;
        paging.setMaxId(maxID);
    }
    if (page > 0) {
        paging = (paging == null) ? new Paging() : paging;
        paging.setPage(page);
    }
    return paging;
}

From source file:com.stronquens.amgtwitter.ControllerTwitter.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w w.ja  va  2  s  . com*/
 *
 * @param request servlet request
 * @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");
    try (PrintWriter out = response.getWriter()) {
        // Obtenemos parametros de la peticion
        String op = request.getParameter("op");
        String accesToken = request.getParameter("token");
        String accesTokenSecret = request.getParameter("secret");

        // Inicializamos variables
        String jsonResult = "";
        Twitter twitter = null;
        ConfigurationBuilder configBuilder = new ConfigurationBuilder();
        Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy HH:mm:ss").create();

        // Se crea la instancia de twitter segun los parametros de ususario
        if (!"".equalsIgnoreCase(accesToken) && !"".equalsIgnoreCase(accesTokenSecret)) {
            try {
                configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf")
                        .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW")
                        .setOAuthAccessToken(accesToken).setOAuthAccessTokenSecret(accesTokenSecret);
                twitter = new TwitterFactory(configBuilder.build()).getInstance();
            } catch (Exception e) {
                System.out.println(e);
            }
        } else {
            try {
                configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf")
                        .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW");
                twitter = new TwitterFactory(configBuilder.build()).getInstance();
            } catch (Exception e) {
                System.out.println(e);
            }
        }

        // Se realizan las diferentes operaciones
        switch (op) {
        case "timeline":
            try {
                Paging pagina = new Paging();
                pagina.setCount(25);
                ResponseList listado = twitter.getHomeTimeline(pagina);
                jsonResult = gson.toJson(listado);
            } catch (TwitterException ex) {
                System.out.println(ex);
            }
            break;
        case "usersettings":
            try {
                jsonResult = gson.toJson(twitter.showUser(twitter.getId()));
            } catch (TwitterException ex) {
                System.out.println(ex);
            }
            break;
        case "pruebas":
            try {
                jsonResult = gson.toJson(twitter.showUser(twitter.getId()));
            } catch (TwitterException ex) {
                System.out.println(ex);
            }
            break;
        default:
            jsonResult = "{\"eror\":\"la operacion no existe\"}";
        }
        // Se devuelven los valores
        out.println(jsonResult);
    }
}