Example usage for twitter4j TwitterException getErrorMessage

List of usage examples for twitter4j TwitterException getErrorMessage

Introduction

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

Prototype

public String getErrorMessage() 

Source Link

Document

Returns error message from the API if available.

Usage

From source file:com.yfiton.notifiers.twitter.TwitterNotifier.java

License:Apache License

@Override
protected void notify(Parameters parameters) throws NotificationException {
    try {//from w w  w. j  a va 2 s  .  co m
        StatusUpdate statusUpdate = new StatusUpdate(status);
        Status status = twitter.updateStatus(statusUpdate);

        log.info("https://twitter.com/" + status.getUser().getScreenName() + "/status/" + status.getId());
    } catch (TwitterException e) {
        throw new NotificationException(new String[] { e.getErrorMessage(),
                "Error code " + e.getErrorCode() + ": https://dev.twitter.com/overview/api/response-codes" },
                e);
    }
}

From source file:de.hoesel.dav.buv.twitter.preferences.TwitterPreferencePage.java

License:Open Source License

protected Control createContents(Composite parent) {
    noDefaultAndApplyButton();//from   w ww . j  a  v  a  2 s  .com
    Composite composite = new Composite(parent, SWT.NONE);
    GridLayout layout = new GridLayout();
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
    layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
    composite.setLayout(layout);

    try {
        user = twitter.verifyCredentials();
        invalidateTwitterAuthentication(composite, user);
    } catch (TwitterException e) {
        if (401 == e.getStatusCode()) {
            // (noch) kein oauth token
        } else {
            Activator.getDefault().getLog()
                    .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getErrorMessage()));
        }

        createNewTwitterAuthentication(composite);

    } catch (Exception e2) {
        createNewTwitterAuthentication(composite);
    }

    return composite;
}

From source file:de.hoesel.dav.buv.twitter.preferences.TwitterPreferencePage.java

License:Open Source License

private void createNewTwitterAuthentication(Composite parent) {

    RequestToken authRequestToken = null;
    try {// w w  w  . ja  va2s  . c  om
        authRequestToken = twitter.getOAuthRequestToken();
    } catch (TwitterException e2) {
        e2.printStackTrace();
        throw new IllegalArgumentException(e2);
    }

    Composite composite = new Composite(parent, SWT.NONE);
    GridLayoutFactory.fillDefaults().numColumns(3).applyTo(composite);

    final String authRequest = authRequestToken.getAuthenticationURL();
    Link link = new Link(composite, SWT.NONE);
    GridDataFactory.fillDefaults().span(3, 1).applyTo(link);
    link.setText(
            "Klicken Sie auf den folgenden Link und gewhren Sie der Anwendung Zugriff auf Ihr Twitter Konto:\n<A href=\""
                    + authRequest + "\">" + authRequest + "</A>");

    link.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            try {
                // Open default external browser
                PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser()
                        .openURL(new URL(authRequest));
                setErrorMessage(null);
            } catch (PartInitException ex) {
                setErrorMessage(ex.getLocalizedMessage());
                Activator.getDefault().getLog()
                        .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getLocalizedMessage()));
            } catch (MalformedURLException ex) {
                setErrorMessage(ex.getLocalizedMessage());
                Activator.getDefault().getLog()
                        .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getLocalizedMessage()));
            }
        }
    });

    Label pinLabel = new Label(composite, SWT.NONE);
    pinLabel.setText("Twitter PIN:");
    GridDataFactory.fillDefaults().grab(false, false).applyTo(pinLabel);
    final Text pinText = new Text(composite, SWT.BORDER);
    GridDataFactory.fillDefaults().grab(true, false).applyTo(pinText);

    final Button pinCheck = new Button(composite, SWT.PUSH);
    pinCheck.setText("Valdieren");
    GridDataFactory.fillDefaults().grab(false, false).applyTo(pinCheck);
    pinCheck.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            try {
                accessToken = twitter.getOAuthAccessToken(pinText.getText());
                if (accessToken != null) {
                    pinCheck.setEnabled(false);
                    pinText.setEnabled(false);
                    setMessage("Twitter Anmeldung erfolgreich.", PreferencePage.INFORMATION);
                } else {
                    pinCheck.setEnabled(true);
                    pinText.setEnabled(true);
                    setMessage("Twitter Anmeldung fehlgeschlagen.", PreferencePage.ERROR);
                }
            } catch (TwitterException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                pinCheck.setEnabled(true);
                pinText.setEnabled(true);
                setMessage("Twitter Anmeldung fehlgeschlagen. " + e1.getErrorMessage(), PreferencePage.ERROR);
            }

        }

    });
}

From source file:org.celstec.arlearn2.oauth.OauthTwitterWorker.java

License:Open Source License

public void redirectToTwitterForAuthentication(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(client_id, client_secret);
    RequestToken token = null;// ww w .jav  a 2s  .  co  m
    try {
        token = twitter.getOAuthRequestToken(redirect_uri);
        req.getSession().setAttribute("requestToken", token);
        String loginUrl = token.getAuthenticationURL() + "&force_login=true";
        resp.sendRedirect(loginUrl);
    } catch (TwitterException e) {
        e.printStackTrace();
        log.log(Level.SEVERE, e.getErrorMessage(), e);
    }
}

From source file:org.fenixedu.bennu.social.domain.api.TwitterAPI.java

License:Open Source License

@Override
public String getAuthenticationUrlForUser(User user) {

    try {//from   w w  w . j a va  2s . c o m
        TwitterFactory tf = new TwitterFactory();
        Twitter twitter = tf.getInstance();
        twitter.setOAuthConsumer(getClientId(), getClientSecret());

        RequestToken oauthRequestToken = twitter.getOAuthRequestToken(getCallbackURL());

        String oauthToken = oauthRequestToken.getToken();
        String oauthTokenSecret = oauthRequestToken.getTokenSecret();
        String authorizationURL = oauthRequestToken.getAuthorizationURL();

        LOGGER.info("Received OauthToken. Token: " + oauthToken + ", TokenSecret: " + oauthTokenSecret
                + ", AuthenticationURL: " + authorizationURL);

        TwitterUser twitterUser = new TwitterService().getAuthenticatedUser(user);
        twitterUser.setOauthToken(oauthToken);
        twitterUser.setOauthTokenSecret(oauthTokenSecret);

        return authorizationURL;

    } catch (TwitterException e) {
        LOGGER.error("Received TwitterException:" + e.getErrorMessage());
        e.printStackTrace();
        return "";
    }
}

From source file:org.mla.cbox.shibboleth.idp.authn.impl.InitializeTwitterContext.java

License:Apache License

@Override
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext,
        @Nonnull final AuthenticationContext authenticationContext) {

    /* Create a new TwitterContext */
    final TwitterContext twitterContext = new TwitterContext();

    /* Set the Twitter integration details for the context */
    twitterContext.setTwitterIntegration(this.twitterIntegration);
    log.debug("{} Created TwitterContext using TwitterIntegration with consumer key {}", getLogPrefix(),
            this.twitterIntegration.getOauthConsumerKey());

    /* Create a new Twitter class instance and add it to the context */
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(this.twitterIntegration.getOauthConsumerKey(),
            this.twitterIntegration.getOauthConsumerSecret());
    twitterContext.setTwitter(twitter);// ww  w  .jav a 2 s . c om

    /* Find the Spring context and from it the current flow execution URL */
    SpringRequestContext springRequestContext = (SpringRequestContext) profileRequestContext
            .getSubcontext(SpringRequestContext.class);
    RequestContext requestContext = springRequestContext.getRequestContext();
    String flowUrl = requestContext.getFlowExecutionUrl();

    /* Construct the callback URL using the flow execution URL and the server details */
    ServletExternalContext externalContext = (ServletExternalContext) requestContext.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getNativeRequest();
    StringBuilder callbackUrlBuilder = new StringBuilder().append(request.getScheme()).append("://")
            .append(request.getServerName()).append(flowUrl).append("&_eventId=proceed");

    String callbackUrl = callbackUrlBuilder.toString();

    /* Query Twitter for the request token and include the callback URL */
    try {
        log.debug("{} Obtaining request token with callback URL {}", getLogPrefix(), callbackUrl);
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);
        twitterContext.setRequestToken(requestToken);
        log.debug("{} Obtained request token", getLogPrefix());
    } catch (TwitterException e) {
        log.error("{} Error obtaining request token from Twitter: {}", getLogPrefix(), e.getErrorMessage());
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        return;
    }

    /* Save the context as a sub context to the authentication context */
    authenticationContext.addSubcontext(twitterContext, true);

    return;
}

From source file:org.n52.twitter.dao.TwitterAbstractDAO.java

License:Open Source License

/**
 * @throws TwitterException - when Twitter service or network is unavailable
 * @throws DecodingException //from w ww . j  a  v  a 2s  . c  om
 */
protected Collection<TwitterMessage> executeApiRequest(Query query) throws TwitterException, DecodingException {
    LinkedList<TwitterMessage> tweets = new LinkedList<>();
    long lastID = Long.MAX_VALUE;
    int requestCount = 0;

    query.setResultType(ResultType.mixed);

    while (tweets.size() < MAX_TWEETS_TO_HARVEST) {
        if (MAX_TWEETS_TO_HARVEST - tweets.size() > TWEETS_TO_LOAD_PER_API_REQUEST) {
            query.setCount(TWEETS_TO_LOAD_PER_API_REQUEST);
        } else {
            query.setCount(MAX_TWEETS_TO_HARVEST - tweets.size());
        }
        try {
            QueryResult result = twitter.search(query);
            requestCount++;
            if (result.getTweets().isEmpty()) {
                break;
            }
            for (Status tweet : result.getTweets()) {
                TwitterMessage message = TwitterMessage.create(tweet);
                if (message != null) {
                    tweets.add(message);
                }
                if (tweet.getId() < lastID) {
                    lastID = tweet.getId();
                }
            }
            query.setMaxId(lastID - 1);
            LOGGER.debug("Progress: " + tweets.size() + "/" + MAX_TWEETS_TO_HARVEST + "(Requests: "
                    + requestCount + ")");
        } catch (TwitterException e) {
            LOGGER.error(e.getErrorMessage(), e);
            throw e;
        }
    }

    LOGGER.debug("Result count :" + tweets.size());

    return tweets;
}

From source file:org.n52.twitter.TwitterAccessTokenRetriever.java

License:Open Source License

public static void main(String args[]) throws Exception {
    String[] props = readProperties();
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(props[0], props[1]);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;/*from w ww  .ja va 2  s .  c  o m*/
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        LOGGER.info("Open the following URL and grant access to your account:");
        LOGGER.info(requestToken.getAuthorizationURL());
        LOGGER.info("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                LOGGER.error("Unable to get the access token.");
            } else {
                LOGGER.error(te.getErrorMessage(), te);
            }
        }
    }
    storeAccessToken(accessToken.getToken(), accessToken.getTokenSecret());
}

From source file:org.onebusaway.admin.service.impl.TwitterServiceImpl.java

License:Apache License

public String updateStatus(String statusMessage) throws IOException {
    if (statusMessage == null) {
        _log.info("nothing to tweet!  Exiting");
        return null;
    }//from  w  ww .  j  a  v  a  2s.c  o  m

    Map<String, String> params = new HashMap<>();
    _log.info("tweeting: " + statusMessage);
    params.put("status", statusMessage);

    if (_twitter == null) {
        throw new IOException("Invalid Configuration:  Missing consumer / access keys in spring configuration");
    }

    String response = null;
    try {
        Status status = _twitter.updateStatus(statusMessage);
        if (status != null) {
            response = "Successfully tweeted \"" + status.getText() + "\" at " + status.getCreatedAt();
        }
    } catch (TwitterException te) {
        _log.error(te.getExceptionCode() + ":" + ":" + te.getStatusCode() + te.getErrorMessage());
        throw new IOException(te);
    }
    return response;
}

From source file:org.umit.icm.mobile.notifications.NotificationService.java

License:Open Source License

/**
 * Initializes the notification manager and calls 
 * {@link NotificationService#showNotification(String)}
 *//*from   w  w  w.  j  a v  a  2  s .  c o  m*/

@Override
public void onCreate() {
    super.onCreate();

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            String message = bundle.getString("notification");
            if (intent.getAction().equals("org.umit.icm.mobile.NOTIFICATION_SERVICE")) {
                showNotification(message);
            }
        }
    };

    registerReceiver(receiver, new IntentFilter("org.umit.icm.mobile.NOTIFICATION_SERVICE"));

    BroadcastReceiver twitterReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            String message = bundle.getString("twitter");
            if (intent.getAction().equals("org.umit.icm.mobile.TWITTER_SERVICE")) {
                try {
                    Globals.twitterUpdate.sendTweet(message + " " + Constants.TWITTER_HASHTAG);
                } catch (TwitterException e) {
                    // TODO Auto-generated catch block
                    String text = "Twitter: " + e.getErrorMessage();
                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (RuntimeException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    };

    registerReceiver(twitterReceiver, new IntentFilter("org.umit.icm.mobile.TWITTER_SERVICE"));

}