Example usage for twitter4j TwitterException getStatusCode

List of usage examples for twitter4j TwitterException getStatusCode

Introduction

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

Prototype

public int getStatusCode() 

Source Link

Usage

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;
    }// w w  w  .j a  v a 2 s.  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.osframework.maven.plugins.twitter.AbstractTwitterMojo.java

License:Apache License

protected void loadAccessToken(final Twitter twitter) throws TwitterException {
    // Check for stored access token
    File tokenStore = new File(getWorkDirectory(), "auth");
    if (tokenStore.canRead()) {
        Properties p = new Properties();
        InputStream in = null;//from  w  ww  . j ava2 s  . co  m
        try {
            in = new FileInputStream(tokenStore);
            p.load(in);
        } catch (IOException ignore) {
        } finally {
            IOUtil.close(in);
        }
        authToken = new AccessToken(p.getProperty(OAUTH_ACCESS_TOKEN),
                p.getProperty(OAUTH_ACCESS_TOKEN_SECRET));
    }
    // Get access token via user authorization
    else {
        RequestToken requestToken = twitter.getOAuthRequestToken();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (null == authToken) {
            getLog().info("Open the following URL and grant access to your account:");
            getLog().info(requestToken.getAuthorizationURL());
            System.out.print("Enter the PIN (if available) or just hit enter. [PIN]: ");
            try {
                String pin = br.readLine();
                authToken = (0 < pin.length()) ? twitter.getOAuthAccessToken(requestToken, pin)
                        : twitter.getOAuthAccessToken();
            } catch (IOException ioe) {
                getLog().error("Could not read authorization PIN from input");
                throw new TwitterException(ioe);
            } catch (TwitterException te) {
                if (401 == te.getStatusCode()) {
                    getLog().error("Could not acquire access token");
                }
                throw te;
            }
        }
    }
}

From source file:org.sevenleaves.droidsensor.DroidSensorService.java

License:Apache License

private void tweetDeviceFound(String address, String name, String id, String message) {

    SettingsManager settings = SettingsManager.getInstance(DroidSensorService.this);

    if (!isDeviceWillTweet(settings, id)) {

        persistBluetoothDevice(address, name, id, message, false);
        sendMessage(address);//  www  .  ja v a 2  s  .  c om
        _devices.add(address);

        return;
    }

    String tweeted;
    BluetoothDeviceStub bluetooth = BluetoothDeviceStubFactory.createBluetoothServiceStub(this);
    int btClass = bluetooth.getRemoteClass(address);

    try {

        tweeted = TwitterUtils.tweetDeviceFound(address, name, id, message,
                convertSpecialDevice(name, BluetoothUtils.getMajorDeviceClassName(this, btClass)), settings);
    } catch (TwitterException e) {

        if (e.getStatusCode() == 401) {

            String error = "Could not authenticate you.";
            String pref = "Error from Twitter:";

            showDeviceFound(pref + error);
        }

        Log.e(TAG, e.getLocalizedMessage(), e);

        return;
    }

    if (tweeted == null) {

        return;
    }

    Log.d(TAG, address + "(" + name + ")" + " found.");

    persistBluetoothDevice(address, name, id, message, true);
    _devices.add(address);

    sendMessage(address);
    showDeviceFound(tweeted);
}

From source file:org.sonar.plugins.twitter.TwitterPublisher.java

License:Open Source License

private void authenticate(Configuration configuration) throws TwitterException, IOException {

    String key = configuration.getString(USERNAME_PROPERTY);
    String secret = configuration.getString(PASSWORD_PROPERTY);
    twitter.setOAuthConsumer(key, secret);

    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;//  ww w.  j  a  v a 2s.c  o  m
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        LOG.info("Open the following URL and grant access to your account:");
        LOG.info(requestToken.getAuthorizationURL());
        LOG.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()) {
                LOG.error("Unable to get the access token.");
            } else {
                LOG.error("Unexpected Twitter error: " + te.getMessage(), te);
            }
        }
    }
    int id = twitter.verifyCredentials().getId();
    // persist to the accessToken for future reference.
    storeAccessToken(configuration, id, accessToken);

    // unset clear password on the configuration
    configuration.setProperty(USERNAME_PROPERTY, null);
    configuration.setProperty(PASSWORD_PROPERTY, null);
}

From source file:org.springframework.integration.twitter.oauth.ConsoleBasedAccessTokenInitialRequestProcessListener.java

License:Apache License

public static void main(String[] args) throws Exception {
    File twitterProps = new File(SystemUtils.getUserHome(), "Desktop/twitter.properties");

    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new FileSystemResource(twitterProps));
    propertiesFactoryBean.afterPropertiesSet();
    Properties props = propertiesFactoryBean.getObject();

    String key = StringUtils.trim(props.getProperty("twitter.oauth.consumerKey"));
    String secret = StringUtils.trim(props.getProperty("twitter.oauth.consumerSecret"));

    ConsoleBasedAccessTokenInitialRequestProcessListener consoleBasedAccessTokenInitialRequestProcessListener = new ConsoleBasedAccessTokenInitialRequestProcessListener();

    Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance(key, secret);

    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;/*  ww  w.  j a  v  a  2s  .  co  m*/
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    while (null == accessToken) {
        String pin = consoleBasedAccessTokenInitialRequestProcessListener
                .openUrlAndReturnPin(requestToken.getAuthorizationURL());

        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }

    consoleBasedAccessTokenInitialRequestProcessListener.persistReturnedAccessToken(accessToken);

}

From source file:org.twitter.oauth.java

public static void main(String args[]) throws Exception {
    // The factory instance is re-useable and thread safe.
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer("SjLUa1Pwrs81nIAGiR4f1l4I7", "ISAXBmzqzYLKWQXAaOe09j34APvVOyxahHghLBSvvR0Psnhozl");
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;//from   www  .  ja  va 2s. c o m
    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 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()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }
    //persist to the accessToken for future reference.
    storeAccessToken((int) twitter.verifyCredentials().getId(), accessToken);
    Status status = twitter.updateStatus(args[0]);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
}

From source file:org.yamaLab.TwitterConnector.GetAccessToken.java

License:Apache License

/**                                                                         
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]   
 *                                                                          
 * @param args message                                                      
 *///from  w w  w  . j  a v a 2  s .  c om
public static void main(String[] args) {
    File file = new File("TweetByWikiEx2.properties");
    Properties prop = new Properties();
    InputStream is = null;
    OutputStream os = null;
    try { /* try-0 */
        if (file.exists()) {
            is = new FileInputStream(file);
            prop.load(is);
        }
        if (args.length < 2) {
            if (null == prop.getProperty("oauth.consumerKey")
                    && null == prop.getProperty("oauth.consumerSecret")) {
                // consumer key/secret are not set in twitter4j.properties  
                System.out.println(
                        "Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]");
                System.exit(-1);
            }
        } else {
            prop.setProperty("oauth.consumerKey", args[0]);
            prop.setProperty("oauth.consumerSecret", args[1]);
            os = new FileOutputStream("twitter4j.properties");
            prop.store(os, "twitter4j.properties");
        }
    } catch (IOException ioe) { /* try-0 */
        ioe.printStackTrace();
        System.exit(-1);
    } finally { /* try-0 */
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException ignore) {
            }
        }
        try { /* try-1 in try-0 */
            Twitter twitter = new TwitterFactory().getInstance();
            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) { /* while */
                System.out.println("Open the following URL and grant access to your account:");
                System.out.println(requestToken.getAuthorizationURL());
                try { /* try-1 */
                    Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
                } catch (UnsupportedOperationException ignore) {
                } catch (IOException ignore) {
                } catch (URISyntaxException e) {
                    throw new AssertionError(e);
                } /* try-1 */
                System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
                String pin = br.readLine();
                try { /* try-3  in try-0 */
                    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();
                    }
                } /* try-3  in try-0 */
            } /* while */
            System.out.println("Got access token.");
            System.out.println("Access token: " + accessToken.getToken());
            System.out.println("Access token secret: " + accessToken.getTokenSecret());
            try { /* try-2  in try 0 */
                prop.setProperty("oauth.accessToken", accessToken.getToken());
                prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret());
                os = new FileOutputStream(file);
                prop.store(os, "twitter4j.properties");
                os.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
                System.exit(-1);
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException ignore) {
                    }
                }
            }
            System.out.println("Successfully stored access token to " + file.getAbsolutePath() + ".");
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get accessToken: " + te.getMessage());
            System.exit(-1);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            System.out.println("Failed to read the system input.");
            System.exit(-1);
        } /* try-1 in try-0 */
    } /* try-0 */
}

From source file:radnet.ConfigWindow.java

private void twit_submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_twit_submitActionPerformed
    // TODO add your handling code here:

    if (twit_submit.getText() == "Verify Pin") {
        try {// w w  w .j  a  v  a2 s .c o  m
            if (twit_password.getText().length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, twit_password.getText());
                // prepare for twitter data dump

                System.out.println(accessToken.getScreenName());
                System.out.println(accessToken.getUserId());
                System.out.println(accessToken.getToken());
                System.out.println(accessToken.getTokenSecret());
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    } else {
        try {
            twitter = TwitterFactory.getSingleton();
            twitter.setOAuthConsumer("aC3MoxJN7AN23kHjVwf7Gq92H",
                    "JA0yGiAeBZsUfafVKuNoQ8kUY9nYqr7WCR5bp4LRMAxnKRM46a");
            requestToken = twitter.getOAuthRequestToken();
            accessToken = null;

            twit_password.setEnabled(true);
            twit_submit.setText("Verify Pin");
            Desktop.getDesktop().browse(java.net.URI.create(requestToken.getAuthenticationURL()));
        } catch (Exception ex) {
            System.out.println("An unhandled exception has occured.");
        }
    }
}

From source file:social.controller.GetTwitterToken.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w w w .  ja va  2s . c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //        processRequest(request, response);
    String pin = request.getParameter("pin");
    AccessToken accessToken = null;
    String user_name = "";
    try {
        if (pin.length() > 0) {
            accessToken = twitter.getOAuthAccessToken(requestToken, pin);
        } else {
            accessToken = twitter.getOAuthAccessToken();
        }
        twitter4j.User user = twitter.showUser(twitter.getScreenName());
        user_name = user.getName();
    } catch (TwitterException te) {
        if (401 == te.getStatusCode()) {
            logger.log(Level.SEVERE, "Unable to get the access token.", te);
        } else {
            logger.log(Level.SEVERE, "", te);
        }
    }

    token = accessToken.getToken();
    tokenSecret = accessToken.getTokenSecret();
    response.setContentType("text/plain");
    response.getWriter().write(token + "," + tokenSecret + "," + user_name);

}

From source file:spammerwadgets.AutoOAuthAccess.java

License:Apache License

public static void main(String[] args) {
    File file = new File(fileName);
    Properties prop = new Properties();
    InputStream is = null;/*  www  .  j  av a 2  s .c om*/
    OutputStream os = null;

    prop.setProperty("oauth.consumerKey", "E7uuluwC0ZsAFbV9pHimQ");
    prop.setProperty("oauth.consumerSecret", "c7amwRvOgb4icJArTRfgU8m2G64mbpVioqgmPDT4Yg");
    prop.setProperty("username", "AdrienneccDusti");
    prop.setProperty("password", "SIRENSSUBROUTINE");

    try {
        if (file.exists()) {
            is = new FileInputStream(file);
            prop.load(is);
        }
        if (args.length < 4) {
            if (null == prop.getProperty("oauth.consumerKey")
                    && null == prop.getProperty("oauth.consumerSecret") && null == prop.getProperty("username")
                    && null == prop.getProperty("password")) {
                // consumer key/secret are not set in twitter4j.properties
                System.out.println(
                        "Usage: java twitter4j.examples.oauth.AutoOAuthAccess [consumer key] [consumer secret][username] [password]");
                System.exit(-1);
            }
        } else {
            prop.setProperty("oauth.consumerKey", args[0]);
            prop.setProperty("oauth.consumerSecret", args[1]);
            prop.setProperty("username", args[2]);
            prop.setProperty("password", args[3]);
            os = new FileOutputStream(fileName);
            prop.store(os, fileName);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(-1);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException ignore) {
            }
        }
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        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;

        while (null == accessToken) {
            System.out.println("Open the following URL and grant access to your account:");
            String url = requestToken.getAuthorizationURL();
            System.out.println(url);

            /*
            BufferedReader urlbr = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
            String strTemp = "";
            while(null != (strTemp = urlbr.readLine())){
               System.out.println(strTemp);
            }
                    
                    
            try {
            Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
            } catch (IOException ignore) {
            } catch (URISyntaxException e) {
            throw new AssertionError(e);
            }
            System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
            String pin = br.readLine();
                    
            */

            // Alternatively, we will generate the POST request automatically
            // Firstly, we parse the webpage of the authotizationURL
            Document doc = Jsoup.connect(url).get();

            Element form = doc.getElementById("oauth_form");

            System.out.println(form.toString());

            String action = form.attr("action");

            String authenticity_token = form.select("input[name=authenticity_token]").attr("value");
            String oauth_token = form.select("input[name=oauth_token]").attr("value");

            // Then submit the authentication webpage
            Document doc2 = Jsoup.connect(action).data("authenticity_token", authenticity_token)
                    .data("oauth_token", oauth_token)
                    .data("session[username_or_email]", prop.getProperty("username"))
                    .data("session[password]", prop.getProperty("password")).post();

            System.out.println(doc2.toString());

            Element oauth_pin = doc2.getElementsByTag("code").first();
            String pin = oauth_pin.text();
            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());

        try {
            prop.setProperty("oauth.accessToken", accessToken.getToken());
            prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret());
            os = new FileOutputStream(file);
            prop.store(os, fileName);
            os.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            System.exit(-1);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ignore) {
                }
            }
        }
        System.out.println("Successfully stored access token to " + file.getAbsolutePath() + ".");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get accessToken: " + te.getMessage());
        System.exit(-1);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.out.println("Failed to read the system input.");
        System.exit(-1);
    }
}