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:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Tweet with Image, Uploaded to Twitter
 *//* ww w . j a v a  2 s . c o m*/
@SimpleFunction(description = "This sends a tweet as the logged-in user with the "
        + "specified Text and a path to the image to be uploaded, which will be trimmed if it " + "exceeds "
        + MAX_CHARACTERS + " characters. "
        + "If an image is not found or invalid, only the text will be tweeted."
        + "<p><u>Requirements</u>: This should only be called after the "
        + "<code>IsAuthorized</code> event has been raised, indicating that the "
        + "user has successfully logged in to Twitter.</p>")
public void TweetWithImage(final String status, final String imagePath) {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "TweetWithImage", ErrorMessages.ERROR_TWITTER_SET_STATUS_FAILED,
                "Need to login?");
        return;
    }

    AsynchUtil.runAsynchronously(new Runnable() {
        public void run() {
            try {
                String cleanImagePath = imagePath;
                // Clean up the file path if necessary
                if (cleanImagePath.startsWith("file://")) {
                    cleanImagePath = imagePath.replace("file://", "");
                }
                File imageFilePath = new File(cleanImagePath);
                if (imageFilePath.exists()) {
                    StatusUpdate theTweet = new StatusUpdate(status);
                    theTweet.setMedia(imageFilePath);
                    twitter.updateStatus(theTweet);
                } else {
                    form.dispatchErrorOccurredEvent(Twitter.this, "TweetWithImage",
                            ErrorMessages.ERROR_TWITTER_INVALID_IMAGE_PATH);
                }
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "TweetWithImage",
                        ErrorMessages.ERROR_TWITTER_SET_STATUS_FAILED, e.getMessage());
            }
        }
    });

}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Gets the most recent messages where your username is mentioned.
 *///from  w w  w  . j av  a 2 s . co  m
@SimpleFunction(description = "Requests the " + MAX_MENTIONS_RETURNED + " most "
        + "recent mentions of the logged-in user.  When the mentions have been "
        + "retrieved, the system will raise the <code>MentionsReceived</code> "
        + "event and set the <code>Mentions</code> property to the list of " + "mentions."
        + "<p><u>Requirements</u>: This should only be called after the "
        + "<code>IsAuthorized</code> event has been raised, indicating that the "
        + "user has successfully logged in to Twitter.</p>")
public void RequestMentions() {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "RequestMentions",
                ErrorMessages.ERROR_TWITTER_REQUEST_MENTIONS_FAILED, "Need to login?");
        return;
    }
    AsynchUtil.runAsynchronously(new Runnable() {
        List<Status> replies = Collections.emptyList();

        public void run() {
            try {
                replies = twitter.getMentionsTimeline();
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "RequestMentions",
                        ErrorMessages.ERROR_TWITTER_REQUEST_MENTIONS_FAILED, e.getMessage());
            } finally {
                handler.post(new Runnable() {
                    public void run() {
                        mentions.clear();
                        for (Status status : replies) {
                            mentions.add(status.getUser().getScreenName() + " " + status.getText());
                        }
                        MentionsReceived(mentions);
                    }
                });
            }
        }
    });
}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Gets who is following you.//from  ww w  .ja  v  a 2  s. com
 */
@SimpleFunction
public void RequestFollowers() {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "RequestFollowers",
                ErrorMessages.ERROR_TWITTER_REQUEST_FOLLOWERS_FAILED, "Need to login?");
        return;
    }
    AsynchUtil.runAsynchronously(new Runnable() {
        List<User> friends = new ArrayList<User>();

        public void run() {
            try {
                IDs followerIDs = twitter.getFollowersIDs(-1);
                for (long id : followerIDs.getIDs()) {
                    // convert from the IDs returned to the User
                    friends.add(twitter.showUser(id));
                }
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "RequestFollowers",
                        ErrorMessages.ERROR_TWITTER_REQUEST_FOLLOWERS_FAILED, e.getMessage());
            } finally {
                handler.post(new Runnable() {
                    public void run() {
                        followers.clear();
                        for (User user : friends) {
                            followers.add(user.getName());
                        }
                        FollowersReceived(followers);
                    }
                });
            }
        }
    });
}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Gets the most recent messages sent directly to you.
 *//*from w ww.j  av a2s.co  m*/
@SimpleFunction(description = "Requests the " + MAX_MENTIONS_RETURNED + " most "
        + "recent direct messages sent to the logged-in user.  When the "
        + "messages have been retrieved, the system will raise the "
        + "<code>DirectMessagesReceived</code> event and set the "
        + "<code>DirectMessages</code> property to the list of messages."
        + "<p><u>Requirements</u>: This should only be called after the "
        + "<code>IsAuthorized</code> event has been raised, indicating that the "
        + "user has successfully logged in to Twitter.</p>")
public void RequestDirectMessages() {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "RequestDirectMessages",
                ErrorMessages.ERROR_TWITTER_REQUEST_DIRECT_MESSAGES_FAILED, "Need to login?");
        return;
    }
    AsynchUtil.runAsynchronously(new Runnable() {
        List<DirectMessage> messages = Collections.emptyList();

        @Override
        public void run() {
            try {
                messages = twitter.getDirectMessages();
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "RequestDirectMessages",
                        ErrorMessages.ERROR_TWITTER_REQUEST_DIRECT_MESSAGES_FAILED, e.getMessage());
            } finally {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        directMessages.clear();
                        for (DirectMessage message : messages) {
                            directMessages.add(message.getSenderScreenName() + " " + message.getText());
                        }
                        DirectMessagesReceived(directMessages);
                    }
                });
            }
        }

    });
}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Sends a direct message to a specified username.
 *//*from w  w w.j  a va 2 s.c om*/
@SimpleFunction(description = "This sends a direct (private) message to the specified "
        + "user.  The message will be trimmed if it exceeds " + MAX_CHARACTERS + "characters. "
        + "<p><u>Requirements</u>: This should only be called after the "
        + "<code>IsAuthorized</code> event has been raised, indicating that the "
        + "user has successfully logged in to Twitter.</p>")
public void DirectMessage(final String user, final String message) {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "DirectMessage",
                ErrorMessages.ERROR_TWITTER_DIRECT_MESSAGE_FAILED, "Need to login?");
        return;
    }
    AsynchUtil.runAsynchronously(new Runnable() {
        public void run() {
            try {
                twitter.sendDirectMessage(user, message);
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "DirectMessage",
                        ErrorMessages.ERROR_TWITTER_DIRECT_MESSAGE_FAILED, e.getMessage());
            }
        }
    });
}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Starts following a user.//from   w ww .j a  v  a 2s  . c o  m
 */
@SimpleFunction
public void Follow(final String user) {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "Follow", ErrorMessages.ERROR_TWITTER_FOLLOW_FAILED,
                "Need to login?");
        return;
    }
    AsynchUtil.runAsynchronously(new Runnable() {
        public void run() {
            try {
                twitter.createFriendship(user);
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "Follow",
                        ErrorMessages.ERROR_TWITTER_FOLLOW_FAILED, e.getMessage());
            }
        }
    });
}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Stops following a user.//from  w  ww .  ja v a  2 s  .c  o m
 */
@SimpleFunction
public void StopFollowing(final String user) {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "StopFollowing",
                ErrorMessages.ERROR_TWITTER_STOP_FOLLOWING_FAILED, "Need to login?");
        return;
    }
    AsynchUtil.runAsynchronously(new Runnable() {
        public void run() {
            try {
                twitter.destroyFriendship(user);
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "StopFollowing",
                        ErrorMessages.ERROR_TWITTER_STOP_FOLLOWING_FAILED, e.getMessage());
            }
        }
    });
}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Gets the most recent 20 messages in the user's timeline.
 *//*from   w ww .java  2s. c  o m*/
@SimpleFunction
public void RequestFriendTimeline() {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "RequestFriendTimeline",
                ErrorMessages.ERROR_TWITTER_REQUEST_FRIEND_TIMELINE_FAILED, "Need to login?");
        return;
    }
    AsynchUtil.runAsynchronously(new Runnable() {
        List<Status> messages = Collections.emptyList();

        public void run() {
            try {
                messages = twitter.getHomeTimeline();
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "RequestFriendTimeline",
                        ErrorMessages.ERROR_TWITTER_REQUEST_FRIEND_TIMELINE_FAILED, e.getMessage());
            } finally {
                handler.post(new Runnable() {
                    public void run() {
                        timeline.clear();
                        for (Status message : messages) {
                            List<String> status = new ArrayList<String>();
                            status.add(message.getUser().getScreenName());
                            status.add(message.getText());
                            timeline.add(status);
                        }
                        FriendTimelineReceived(timeline);
                    }
                });
            }
        }
    });
}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Search for tweets or labels/* w  ww  .  j av a 2s.  c  o  m*/
 */
@SimpleFunction(description = "This searches Twitter for the given String query."
        + "<p><u>Requirements</u>: This should only be called after the "
        + "<code>IsAuthorized</code> event has been raised, indicating that the "
        + "user has successfully logged in to Twitter.</p>")
public void SearchTwitter(final String query) {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "SearchTwitter", ErrorMessages.ERROR_TWITTER_SEARCH_FAILED,
                "Need to login?");
        return;
    }
    AsynchUtil.runAsynchronously(new Runnable() {
        List<Status> tweets = Collections.emptyList();

        public void run() {
            try {
                tweets = twitter.search(new Query(query)).getTweets();
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "SearchTwitter",
                        ErrorMessages.ERROR_TWITTER_SEARCH_FAILED, e.getMessage());
            } finally {
                handler.post(new Runnable() {
                    public void run() {
                        searchResults.clear();
                        for (Status tweet : tweets) {
                            searchResults.add(tweet.getUser().getName() + " " + tweet.getText());
                        }
                        SearchSuccessful(searchResults);
                    }
                });
            }
        }
    });
}

From source file:com.google.minijoe.sys.Eval.java

License:Apache License

public void evalNative(int index, JsArray stack, int sp, int parCount) {
    switch (index) {
    case ID_HTTP_GET:
        try {//from  w  w w  . j a v  a  2s .  co m
            String url = stack.getString(sp + 2);
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            stack.setObject(sp, response.body().string());
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        break;

    case ID_POST_JSON:
        try {
            OkHttpClient client = new OkHttpClient();

            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                    stack.getString(sp + 3));
            Request request = new Request.Builder().url(stack.getString(sp + 2)).post(body).build();
            Response response = client.newCall(request).execute();
            stack.setObject(sp, response.body().string());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        break;

    case ID_CRAWLER:
        try {
            Crawler.startCrawler(stack.getString(sp + 2));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        break;

    case ID_CURL:
        new Thread(new Curl()).start();
        break;

    case ID_EXTRACT_HTML:

        try {
            Readability readability = new Readability(new URL(stack.getString(sp + 2)), stack.getInt(sp + 3));
            readability.init();
            stack.setObject(sp, readability.outerHtml());
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        break;

    case ID_EVAL:
        try {
            stack.setObject(sp, eval(stack.getString(sp + 2),
                    stack.isNull(sp + 3) ? stack.getJsObject(sp) : stack.getJsObject(sp + 3)));
        } catch (Exception e) {
            throw new RuntimeException("" + e);
        }

        break;

    case ID_COMPILE:
        try {
            File file = new File(stack.getString(sp + 2));
            DataInputStream dis = new DataInputStream(new FileInputStream(file));
            byte[] data = new byte[(int) file.length()];
            dis.readFully(data);
            String code = new String(data, "UTF-8");
            Eval.compile(code, System.out);
            dis.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_LOAD:
        try {
            File file = new File(stack.getString(sp + 2));
            DataInputStream dis = new DataInputStream(new FileInputStream(file));
            byte[] data = new byte[(int) file.length()];
            dis.readFully(data);
            String code = new String(data, "UTF-8");
            //xxx.js
            Eval.eval(code, Eval.createGlobal());
            dis.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_GEN_SITEMAP:

        try {
            // create web sitemap for web http://www.javavids.com
            WebSitemapGenerator webSitemapGenerator = new WebSitemapGenerator("http://www.javavids.com");
            // add some URLs
            webSitemapGenerator.addPage(new WebPage().setName("index.php").setPriority(1.0)
                    .setChangeFreq(ChangeFreq.NEVER).setLastMod(new Date()));
            webSitemapGenerator.addPage(new WebPage().setName("latest.php"));
            webSitemapGenerator.addPage(new WebPage().setName("contact.php"));
            // generate sitemap and save it to file /var/www/sitemap.xml
            File file = new File("/var/www/sitemap.xml");
            webSitemapGenerator.constructAndSaveSitemap(file);
            // inform Google that this sitemap has changed
            webSitemapGenerator.pingGoogle();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_WHOIS:
        try {
            stack.setObject(sp, Whois.getRawWhoisResults(stack.getString(sp + 2)));
        } catch (WhoisException e) {
            stack.setObject(sp, "Whois Exception " + e.getMessage());
        } catch (HostNameValidationException e) {
            stack.setObject(sp, "Whois host name invalid " + e.getMessage());
        }
        break;

    case ID_PAGERANK:
        stack.setObject(sp, PageRank.getPR(stack.getString(sp + 2)));
        break;

    case ID_SEND_TWITTER:
        try {
            Twitter twitter = new TwitterFactory().getInstance();
            try {
                // get request token.
                // this will throw IllegalStateException if access token is already available
                RequestToken requestToken = twitter.getOAuthRequestToken();
                System.out.println("Got request token.");
                System.out.println("Request token: " + requestToken.getToken());
                System.out.println("Request token secret: " + requestToken.getTokenSecret());
                AccessToken accessToken = null;

                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("Got access token.");
                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);
                }
            }
            Status status = twitter.updateStatus(stack.getString(sp + 2));
            System.out.println("Successfully updated the status to [" + status.getText() + "].");
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get timeline: " + te.getMessage());
            System.exit(-1);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            System.out.println("Failed to read the system input.");
            System.exit(-1);
        }
        break;

    case ID_EXTRACT_TEXT:
        try {
            String url = stack.getString(sp + 2);
            String selector = stack.getString(sp + 3);

            Document doc = Jsoup.connect(url).userAgent("okhttp").timeout(5 * 1000).get();

            HtmlToPlainText formatter = new HtmlToPlainText();

            if (selector != null) {
                Elements elements = doc.select(selector);
                StringBuffer sb = new StringBuffer();
                for (Element element : elements) {
                    String plainText = formatter.getPlainText(element);
                    sb.append(plainText);
                }
                stack.setObject(sp, sb.toString());
            } else {
                stack.setObject(sp, formatter.getPlainText(doc));

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_LIST_LINKS:
        try {
            String url = stack.getString(sp + 2);
            print("Fetching %s...", url);

            Document doc = Jsoup.connect(url).get();
            Elements links = doc.select("a[href]");
            Elements media = doc.select("[src]");
            Elements imports = doc.select("link[href]");

            print("\nMedia: (%d)", media.size());
            for (Element src : media) {
                if (src.tagName().equals("img"))
                    print(" * %s: <%s> %sx%s (%s)", src.tagName(), src.attr("abs:src"), src.attr("width"),
                            src.attr("height"), trim(src.attr("alt"), 20));
                else
                    print(" * %s: <%s>", src.tagName(), src.attr("abs:src"));
            }

            print("\nImports: (%d)", imports.size());
            for (Element link : imports) {
                print(" * %s <%s> (%s)", link.tagName(), link.attr("abs:href"), link.attr("rel"));
            }

            print("\nLinks: (%d)", links.size());
            for (Element link : links) {
                print(" * a: <%s>  (%s)", link.attr("abs:href"), trim(link.text(), 35));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_LOG:
        log.info(stack.getString(sp + 2));
        break;

    case ID_SEND_MAIL:
        try {
            // put your e-mail address here
            final String yourAddress = "guilherme.@gmail.com";

            // configure programatically your mail server info
            EmailTransportConfiguration.configure("smtp.server.com", true, false, "username", "password");

            // and go!
            new EmailMessage().from("demo@guilhermechapiewski.com").to(yourAddress)
                    .withSubject("Fluent Mail API").withAttachment("file_name").withBody("Demo message").send();

        } catch (Exception ex) {
            stack.setObject(sp, "[ERROR]" + ex.getMessage());
        }
        break;

    case ID_SNAPPY:
        try {
            String input = "Hello snappy-java! Snappy-java is a JNI-based wrapper of "
                    + "Snappy, a fast compresser/decompresser.";
            byte[] compressed = Snappy.compress(input.getBytes("UTF-8"));
            byte[] uncompressed = Snappy.uncompress(compressed, 0, compressed.length);

            String result = new String(uncompressed, "UTF-8");
            System.out.println(result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        break;

    case ID_OPENBROWSER:
        new Thread(new Runnable() {
            public void run() {
                openBrowser();
            }
        }).start();
        break;

    case ID_HELP:
        Enumeration ex = this.keys();
        while (ex.hasMoreElements()) {
            String key = (String) ex.nextElement();
            Object val = this.getRawInPrototypeChain(key);
            if (val instanceof JsFunction) {
                System.out.println(key + "---" + ((JsFunction) val).description);
            } else {
                System.out.println(key + "---" + val);
            }
        }
        break;

    default:
        super.evalNative(index, stack, sp, parCount);
    }
}