Example usage for twitter4j TwitterException getMessage

List of usage examples for twitter4j TwitterException getMessage

Introduction

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

Prototype

@Override
    public String getMessage() 

Source Link

Usage

From source file:SearchTweets.java

License:Apache License

/**
 * Usage: java twitter4j.examples.search.SearchTweets [query]
 *
 * @param args/*  ww w  .j  a  v a2  s . co m*/
 */
public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println("java twitter4j.examples.search.SearchTweets [query]");
        System.exit(-1);
    }
    Twitter twitter = new TwitterFactory().getInstance();
    try {
        Query query = new Query(args[0]);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
            }
        } while ((query = result.nextQuery()) != null);
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:SendDirectMessage.java

License:Apache License

/**
 * Usage: java twitter4j.examples.directMessage.DirectMessage [recipient screen name] [message]
 *
 * @param args String[]//  w w  w.j a  v  a 2s .c o  m
 */
public static void main(String[] args) {
    if (args.length < 2) {
        System.out.println(
                "Usage: java twitter4j.examples.directmessage.SendDirectMessage [recipient screen name] [message]");
        System.exit(-1);
    }
    Twitter twitter = new TwitterFactory().getInstance();
    try {
        DirectMessage message = twitter.sendDirectMessage(args[0], args[1]);
        System.out.println("Direct message successfully sent to " + message.getRecipientScreenName());
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to send a direct message: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:Register.java

License:Open Source License

/**
 * Usage: java twitter4j.examples.tweets.UpdateStatus [text]
 *
 * @param args message//w  w  w .  ja  v a2  s .c o m
 */
public static void main(String[] args) {
    try {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("wIb1qVNc0CNXQJxduYIXw")
                .setOAuthConsumerSecret("vTES3U9862wYaxFRdMyD1LRatkq2R42mDyOjXLHIdk");

        Twitter twitter = new TwitterFactory(cb.build()).getInstance();
        AccessToken accessToken = null;
        try {
            // get request token.
            // this will throw IllegalStateException if access token is already available
            RequestToken requestToken = twitter.getOAuthRequestToken();

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            while (null == accessToken) {
                System.out.println("Open the following URL and grant access to your account:");
                System.out.println(requestToken.getAuthorizationURL());
                System.out.print("Enter the PIN(if available) and hit enter after you granted access. [PIN]:");
                String pin = br.readLine();
                try {
                    if (pin.length() > 0) {
                        accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                    } else {
                        accessToken = twitter.getOAuthAccessToken(requestToken);
                    }
                } catch (TwitterException te) {
                    if (401 == te.getStatusCode()) {
                        System.out.println("Unable to get the access token.");
                    } else {
                        te.printStackTrace();
                    }
                }
            }
            System.out.println("Access granted to Twitter.");
            System.out.println("Access token: " + accessToken.getToken());
            System.out.println("Access token secret: " + accessToken.getTokenSecret());
        } catch (IllegalStateException ie) {
            // access token is already available, or consumer key/secret is not set.
            if (!twitter.getAuthorization().isEnabled()) {
                System.out.println("OAuth consumer key/secret is not set.");
                System.exit(-1);
            }
        }
        twitter.updateStatus("Minecraft server successfully registered at " + (new Date()).toString());
        System.out.println("Successfully connected to Twitter.");

        // Write the properties file
        PrintWriter pw = new PrintWriter(new FileWriter("../TwitterEvents.properties"));
        pw.println("accessToken=" + accessToken.getToken());
        pw.println("accessTokenSecret=" + accessToken.getTokenSecret());
        pw.close();

        System.out.println("Your TwitterEvents.properties file has been created with your access tokens.");
        System.out.println("Start Minecraft server to load the remaining default values.");
        System.out.println("Then reload TwitterEvents if you make any changes.");
        System.exit(0);
    } catch (TwitterException te) {
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.out
                .println("Try revoking access to the hModEvents application from your Twitter settings page.");
        System.exit(-1);
    } catch (IOException ioe) {
        System.out.println("Failed to read the system input.");
        System.exit(-1);
    }
}

From source file:DestroyFriendship.java

License:Apache License

/**
 * Usage: java twitter4j.examples.friendship.DestroyFriendship [screen name]
 *
 * @param args message//from  w  ww. j  av  a2 s .  co  m
 */
public void destroyFriendship() {

    ShowFriendshi df = new ShowFriendshi();

    ArrayList<Long> getFilteredtarget = df.showFriendship();

    try {
        Twitter twitter = new TwitterFactory().getInstance();
        User user;
        String get;
        DefaultListModel m1 = new DefaultListModel();
        for (Long target : getFilteredtarget) {

            user = twitter.showUser(target);
            get = user.getScreenName();

            if (!get.equalsIgnoreCase("prometheanBrain") && !get.equalsIgnoreCase("tweetrackdevs")) {
                m1.addElement(get);
                twitter.destroyFriendship(target);
            }

            System.out.println("Successfully unfollowed [" + target + "].");
        }
        MainActivity.deletedList.setModel(m1);

    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to unfollow: " + te.getMessage());

    }
}

From source file:GetFriendsIDs.java

License:Apache License

/**
 * Usage: java twitter4j.examples.friendsandfollowers.GetFriendsIDs [screen name]
 *
 * @param args message//  w w  w  .  j a v  a  2s.  co  m
 */
public ArrayList<Long> getFriendsId() {
    ArrayList<Long> friendsid = new ArrayList<Long>();
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        long cursor = -1;
        IDs ids;
        System.out.println("Listing following ids.");

        do {

            ids = twitter.getFriendsIDs(cursor);

            for (long id : ids.getIDs()) {

                friendsid.add(id);
            }
        } while ((cursor = ids.getNextCursor()) != 0);
        System.out.println("done");
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get friends' ids: " + te.getMessage());

    }

    return friendsid;
}

From source file:ShowFriendshi.java

License:Apache License

/**
 * Usage: java twitter4j.examples.friendship.ShowFriendship  [source screen name] [target screen name]
 *
 * @param args message//from   w w w .  ja v a2s .  c  om
 */
public ArrayList<Long> showFriendship() {
    GetFriendsIDs getFriendsId = new GetFriendsIDs();
    ArrayList<Long> target = getFriendsId.getFriendsId();
    ArrayList<Long> filteredTarget = new ArrayList<Long>();
    Collections.shuffle(target);
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        int authenticatedUserId = (int) twitter.getId();
        if (target.size() < 50) {

            for (int i = 0; i < target.size(); i++) {
                Relationship relationship = twitter.showFriendship(authenticatedUserId, target.get(i));
                if (!relationship.isSourceFollowedByTarget()) {

                    filteredTarget.add(target.get(i));
                }

            }

        } else {
            for (int i = 0; i < 50; i++) {
                Relationship relationship = twitter.showFriendship(authenticatedUserId, target.get(i));
                if (!relationship.isSourceFollowedByTarget()) {

                    filteredTarget.add(target.get(i));
                }

            }

        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to show friendship: " + te.getMessage());

    }

    return filteredTarget;
}

From source file:account.GetRateLimitStatus.java

License:Apache License

public static ConstVars getRateLimit(String[] args) {

    ConstVars StaticVars = new ConstVars();

    try {//from  www .  j av a  2 s.  c o m

        // init Twitter OAuth
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(args[1]).setOAuthConsumerSecret(args[2])
                .setOAuthAccessToken(args[3]).setOAuthAccessTokenSecret(args[4]);

        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        // it returns RateLimits of all end-points
        Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus();

        // get RateLimit of required end-point
        RateLimitStatus status = rateLimitStatus.get(args[0]);
        String Endpoint = args[0];
        int Limit = status.getLimit();

        int Remaining = status.getRemaining();
        int ResetTimeInSeconds = status.getResetTimeInSeconds();
        int SecondsUntilReset = status.getSecondsUntilReset();

        // set and return rate limit info to ConstVars's variables
        StaticVars.Endpoint = Endpoint;
        StaticVars.Limit = Limit;
        StaticVars.Remaining = Remaining;
        StaticVars.ResetTimeInSeconds = ResetTimeInSeconds;
        StaticVars.SecondsUntilReset = SecondsUntilReset;

    } catch (TwitterException te) {
        if (args.length == 6) {
            System.err
                    .println("Failed to get rate limit status of " + args[5] + " because: " + te.getMessage());
        } else {
            System.err.println("Failed to get rate limit status because: " + te.getMessage());
        }
    }
    return StaticVars;
}

From source file:alberapps.java.noticias.tw.ProcesarTwitter.java

License:Open Source License

/**
 * Procesar a partir de los timeline de cada uno
 *
 * @return listado//  w  w w  .  j  a va 2  s.c  o  m
 */
public static List<TwResultado> procesar(List<Boolean> cargar, String cantidad) {

    List<TwResultado> lista;

    try {

        // Iniciar
        ProcesarTwitter4j procesar4j = new ProcesarTwitter4j();
        procesar4j.setUp();

        lista = procesar4j.recuperarTimeline("alberapps", tw_alberapps_ruta, Integer.parseInt(cantidad));

        if (cargar.get(0)) {

            lista.addAll(procesar4j.recuperarTimeline("Alicante_City", tw_alicante_ruta,
                    Integer.parseInt(cantidad)));

        }

        if (cargar.get(1)) {

            lista.addAll(procesar4j.recuperarTimeline("campelloturismo", tw_campello_ruta,
                    Integer.parseInt(cantidad)));

        }

        if (cargar.get(2)) {

            lista.addAll(
                    procesar4j.recuperarTimeline("aytoraspeig", tw_sanvi_ruta, Integer.parseInt(cantidad)));

        }

        if (cargar.get(3)) {

            lista.addAll(
                    procesar4j.recuperarTimeline("sant_joan", tw_santjoan_ruta, Integer.parseInt(cantidad)));

        }

        if (cargar.get(4)) {
            // Tram
            lista.addAll(
                    procesar4j.recuperarTimeline("tramdealicante", tw_tram_ruta, Integer.parseInt(cantidad)));
        }

        if (lista != null && !lista.isEmpty()) {

            // Ordenar por fecha
            Collections.sort(lista);

        } else {

            return null;

        }

    } catch (TwitterException e) {
        //88 rate limit exceeded
        TwResultado resultado = new TwResultado();

        resultado.setError(Integer.toString(e.getErrorCode()));
        resultado.setMensajeError(e.getErrorMessage());

        lista = new ArrayList<>();

        lista.add(resultado);

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

        TwResultado resultado = new TwResultado();

        resultado.setError("100");
        resultado.setMensajeError(e.getMessage());

        lista = new ArrayList<>();

        lista.add(resultado);

        e.printStackTrace();

    }

    return lista;

}

From source file:alberapps.java.noticias.tw.ProcesarTwitter.java

License:Open Source License

/**
 * Recuperar a partir de lista de twitter
 *
 * @return listado/*from w  w  w  .  ja  v a 2s  . c o  m*/
 */
public static List<TwResultado> procesarConLista(List<Boolean> cargar, String cantidad) {

    List<TwResultado> lista;

    try {

        // Iniciar
        ProcesarTwitter4j procesar4j = new ProcesarTwitter4j();
        procesar4j.setUp();

        lista = procesar4j.recuperarTimeline("alberapps", tw_alberapps_ruta, Integer.parseInt("5"));

        lista.addAll(procesar4j.recuperarListaUsuario("alberapps", tw_alberapps_ruta, Integer.parseInt("15")));

        //lista = procesar4j.recuperarTimeline("alberapps", tw_alberapps_ruta, Integer.parseInt(cantidad));

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

        if (!cargar.get(0)) {

            //lista.addAll(procesar4j.recuperarTimeline("Alicante_City", tw_alicante_ruta, Integer.parseInt(cantidad)));

            TwResultado buscar = new TwResultado();
            buscar.setUsuario("@Alicante_City");
            listaBorrar.add(buscar);

        }

        if (!cargar.get(1)) {

            //lista.addAll(procesar4j.recuperarTimeline("campelloturismo", tw_campello_ruta, Integer.parseInt(cantidad)));

            TwResultado buscar = new TwResultado();
            buscar.setUsuario("@CampelloTurismo");
            listaBorrar.add(buscar);

        }

        if (!cargar.get(2)) {

            //lista.addAll(procesar4j.recuperarTimeline("aytoraspeig", tw_sanvi_ruta, Integer.parseInt(cantidad)));

            TwResultado buscar = new TwResultado();
            buscar.setUsuario("@aytoraspeig");
            listaBorrar.add(buscar);

        }

        if (!cargar.get(3)) {

            //lista.addAll(procesar4j.recuperarTimeline("sant_joan", tw_santjoan_ruta, Integer.parseInt(cantidad)));

            TwResultado buscar = new TwResultado();
            buscar.setUsuario("@sant_joan");
            listaBorrar.add(buscar);

        }

        if (!cargar.get(4)) {
            // Tram
            //lista.addAll(procesar4j.recuperarTimeline("tramdealicante", tw_tram_ruta, Integer.parseInt(cantidad)));

            TwResultado buscar = new TwResultado();
            buscar.setUsuario("@TramdeAlicante");
            listaBorrar.add(buscar);

        }

        //Ordenar la lista por fecha
        if (lista != null && !lista.isEmpty()) {

            //Eliminar resultados indicados
            if (listaBorrar != null && !listaBorrar.isEmpty()) {
                lista.removeAll(listaBorrar);
            }

            // Ordenar por fecha
            Collections.sort(lista);

        } else {

            return null;

        }

    } catch (TwitterException e) {
        //88 rate limit exceeded
        TwResultado resultado = new TwResultado();

        resultado.setError(Integer.toString(e.getErrorCode()));
        resultado.setMensajeError(e.getErrorMessage());

        lista = new ArrayList<>();

        lista.add(resultado);

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

        TwResultado resultado = new TwResultado();

        resultado.setError("100");
        resultado.setMensajeError(e.getMessage());

        lista = new ArrayList<>();

        lista.add(resultado);

        e.printStackTrace();

    }

    return lista;

}

From source file:alberapps.java.noticias.tw.ProcesarTwitter.java

License:Open Source License

/**
 * listado tram/*from w  w  w  .ja v a2s  .  c o m*/
 *
 * @return listado
 */
public static List<TwResultado> procesarTram() {

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

    try {
        List<TwResultado> listaInicial;

        // Iniciar
        ProcesarTwitter4j procesar4j = new ProcesarTwitter4j();
        procesar4j.setUp();

        // Tram
        listaInicial = procesar4j.recuperarTimeline("tramdealicante", tw_tram_ruta, 15);

        // Eliminar las que sean de conversacion y retweet
        for (int i = 0; i < listaInicial.size(); i++) {

            if (listaInicial.get(i).getRespuestaId() == -1 && !listaInicial.get(i).isRetweet()) {
                lista.add(listaInicial.get(i));
            }

        }

        if (lista.size() < 2) {

            lista.clear();

            listaInicial = procesar4j.recuperarTimeline("tramdealicante", tw_tram_ruta, 25);

            // Eliminar las que sean de conversacion y retweet
            for (int i = 0; i < listaInicial.size(); i++) {

                if (listaInicial.get(i).getRespuestaId() == -1 && !listaInicial.get(i).isRetweet()) {
                    lista.add(listaInicial.get(i));
                }

            }

        }

        if (lista != null && !lista.isEmpty()) {

            // Ordenar por fecha
            Collections.sort(lista);

        } else {

            return null;

        }

    } catch (TwitterException e) {
        //88 rate limit exceeded
        TwResultado resultado = new TwResultado();

        resultado.setError(Integer.toString(e.getErrorCode()));
        resultado.setMensajeError(e.getErrorMessage());

        lista = new ArrayList<>();

        lista.add(resultado);

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

        TwResultado resultado = new TwResultado();

        resultado.setError("100");
        resultado.setMensajeError(e.getMessage());

        lista = new ArrayList<>();

        lista.add(resultado);

        e.printStackTrace();

    }

    return lista;

}