Example usage for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

List of usage examples for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

Introduction

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

Prototype

ConfigurationBuilder

Source Link

Usage

From source file:fr.istic.taa.jaxrs.StatusEndpoint.java

License:Apache License

@GET
@Path("/sendTweet")
@Produces(MediaType.APPLICATION_JSON)/*from  ww w . ja v a2  s.  co m*/
public String sendTweet() throws IOException, TwitterException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("jUTzyyI3zjBqiKQqhfQyFeqpm")
            .setOAuthConsumerSecret("gMkOSO9EYqlzrnq35kdoZIqvX12sJwP1wHKMqo6uYbvq2q0LGl")
            .setOAuthAccessToken("89767958-C2cLIz69SpdR6wmQGdzE8rQSXAMzIVBpYOuaZGmHQ")
            .setOAuthAccessTokenSecret("oG7FQJMQsX2OHKxcaHjUxgZI94ZqUShGi0qCAsI50xfpZ");
    TwitterFactory tf = new TwitterFactory(cb.build());

    Twitter twitter = tf.getInstance();

    String recipientId;
    recipientId = "@nassssssiim";

    String message;
    message = "test";

    DirectMessage message1 = twitter.sendDirectMessage(recipientId, message);
    System.out.println(" to @" + message1.getRecipientScreenName());
    return " to @" + message1.getRecipientScreenName();

}

From source file:generatetwittertokens.GenerateTwitterTokens.java

License:Open Source License

public static void main(String[] args) {
    String username = "";

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setOAuthConsumerKey(consumerKey);
    configurationBuilder.setOAuthConsumerSecret(consumerSecret);

    try {//w ww  .  j  a v  a  2 s  .c om
        Twitter twitter = new TwitterFactory(configurationBuilder.build()).getInstance();
        RequestToken requestToken = twitter.getOAuthRequestToken();
        AccessToken accessToken = null;

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        while (accessToken == null) {
            System.out.println("PhantomBot Twitter API Connection Tool\r\n\r\n"
                    + "This tool will request access to read and write to your Twitter account.\r\n"
                    + "You will be presented with a URL to open in your local browser to approve\r\n"
                    + "access, however, this application will attempt to launch a browser for\r\n"
                    + "you automatically.\r\n\r\n"
                    + "You will be presented with a PIN that you must provide back to this\r\n"
                    + "application. After that is completed, Twitter will generate OAuth keys\r\n"
                    + "which will be stored in the PhantomBot directory as twitter.txt.\r\n\r\n"
                    + "Do keep this file safe! The keys are the same as a password to your Twitter\r\n"
                    + "account!\r\n\r\n" + "You may regenerate the OAuth keys at any time if needed.\r\n");

            System.out.println("Open the following URL in your browser if a browser does not automatically\r\n"
                    + "launch within a few seconds:");
            System.out.println("    " + requestToken.getAuthorizationURL() + "\r\n");

            /*
             * Attempt to launch a local browser.  Ignore exceptions, except if the URL is bad.
             */
            try {
                Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
            } catch (UnsupportedOperationException ignore) {
            } catch (IOException ignore) {
            } catch (URISyntaxException e) {
                throw new AssertionError(e);
            }

            /*
             * Request the username from the user.
             */
            username = "";
            while (username.length() < 1) {
                System.out.print("Provide your Twitter username: ");
                try {
                    username = bufferedReader.readLine();
                } catch (IOException ex) {
                    username = "";
                    System.out.println("Failed to read input. Please try again.");
                }
            }

            /*
             * Request the PIN from the user.
             */
            String pin = "";
            while (pin.length() < 1) {
                System.out.print("Enter the PIN provided by Twitter: ");
                try {
                    pin = bufferedReader.readLine();
                    accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                } catch (TwitterException ex) {
                    if (ex.getStatusCode() == 401) {
                        pin = "";
                        System.out.println("Twitter failed to provide access tokens.  Please try again.");
                    } else {
                        System.out.println("Twitter returned an error:\r\n" + ex.getMessage());
                        System.exit(1);
                    }
                } catch (IOException ex) {
                    pin = "";
                    System.out.println("Failed to read input. Please try again.");
                }
            }

        }

        System.out.println("Twitter has provided PhantomBot with OAuth Access Tokens.");

        String twitterData = "";
        try {
            twitterData = "# Twitter Configuration File\r\n"
                    + "# Generated by PhantomBot GenerateTwitterTokens\r\n"
                    + "# If new tokens are required, run the application again.\r\n" + "#\r\n"
                    + "# PROTECT THIS FILE AS IF IT HAD YOUR TWITTER PASSWORD IN IT!\r\n" + "twitter_username="
                    + username + "\r\n" + "twitter_access_token=" + accessToken.getToken() + "\r\n"
                    + "twitter_secret_token=" + accessToken.getTokenSecret() + "\r\n";
            Files.write(Paths.get("./twitter.txt"), twitterData.getBytes(StandardCharsets.UTF_8),
                    StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
            System.out.println("Data has been successfully stored in twitter.txt.");
        } catch (IOException ex) {
            System.out.println("Unable to create twitter.txt.\r\nPlease create with the following content:\r\n"
                    + twitterData);
            System.exit(1);
        }
    } catch (TwitterException ex) {
        System.out.println("Twitter returned an error:\r\n" + ex.getMessage());
        System.exit(1);
    }
}

From source file:gohai.simpletweet.SimpleTweet.java

License:Apache License

protected void createInstance() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    if (oAuthConsumerKey != null) {
        cb.setOAuthConsumerKey(oAuthConsumerKey);
    }//from ww w  . j a v  a 2  s . c om
    if (oAuthConsumerSecret != null) {
        cb.setOAuthConsumerSecret(oAuthConsumerSecret);
    }
    if (oAuthAccessToken != null) {
        cb.setOAuthAccessToken(oAuthAccessToken);
    }
    if (oAuthAccessTokenSecret != null) {
        cb.setOAuthAccessTokenSecret(oAuthAccessTokenSecret);
    }
    twitter = new TwitterFactory(cb.build()).getInstance();
}

From source file:GUI.Authorization.java

License:Open Source License

/**
 * Creates new form Authorization and configures Twitter4J in order to
 * log in with Twitter properly/*from w  ww  . jav  a  2 s .c om*/
 */
public Authorization() {
    initComponents();

    // Related to the window appearance
    this.setTitle("TQuest Login");
    this.setLocationRelativeTo(null);

    // Hides the PIN-related controls
    pinField.setVisible(false);
    goButton.setVisible(false);
    infoLabel4.setVisible(false);

    // Twitter4J and app configuration
    configBuilder = new ConfigurationBuilder();
    configBuilder.setDebugEnabled(rootPaneCheckingEnabled);
    configBuilder.setOAuthConsumerKey(OAuthCK);
    configBuilder.setOAuthConsumerSecret(OAuthCS);
    OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
    try {
        requestToken = OAuthTwitter.getOAuthRequestToken();
        System.out.println("Request token obtained succesfully");
        authURL = requestToken.getAuthorizationURL();
    } catch (TwitterException ex) {
        Logger.getLogger(Authorization.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:humbala.Bonbon.java

public Bonbon() {
    cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("bY3RaVuqzxNCKzDwXBvA")
            .setOAuthConsumerSecret("NmheZVfBwch4kxV3zjdjKPJvnX2bS41etPcnnUuyA")
            .setOAuthAccessToken("71545295-oiuSiTfwjwxudUBn3hJs1OtgDm4HtUjeFb9cgwaEH")
            .setOAuthAccessTokenSecret("7IDOPyQAB04pGKexoXNo0PVq6l8GoZNlAcSs5PRxqQ1sE")
            .setHttpProxyHost("cache.itb.ac.id").setHttpProxyPort(8080).setHttpProxyUser("tirtawr")
            .setHttpProxyPassword("satepadang");
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();/*  w w  w  .j  ava  2  s. com*/
}

From source file:inujini_.hatate.service.OauthService.java

License:MIT License

/**
 * Oauth?./*from   www  .  ja  v a2  s. c  om*/
 * @param intent
 * @throws IllegalStateException intent?consumerKey?consumerKey???????????.
 */
private void startOauth(Intent intent) {
    // validate
    if (!intent.hasExtra(KEY_CONSUMER_KEY) || !intent.hasExtra(KEY_CONSUMER_SECRET)) {
        IllegalStateException e = new IllegalStateException(
                "In startOauth, intent's extra must have consumerKey and consumerSecret.");

        CallbackBroadcastReceiver.Data data = CallbackBroadcastReceiver.Data.create(e);
        sendBroadcast(CallbackBroadcastReceiver.createIntent(data));
        return;
    }

    Configuration conf = new ConfigurationBuilder().setOAuthConsumerKey(intent.getStringExtra(KEY_CONSUMER_KEY))
            .setOAuthConsumerSecret(intent.getStringExtra(KEY_CONSUMER_SECRET)).build();

    OAuthAuthorization oauth = new OAuthAuthorization(conf);
    oauth.setOAuthAccessToken(null);

    // ?URI?
    String uri;
    try {
        uri = oauth.getOAuthRequestToken(URI_CALLBACK).getAuthorizationURL();
    } catch (TwitterException e) {
        e.printStackTrace();
        CallbackBroadcastReceiver.Data data = CallbackBroadcastReceiver.Data.create(e);
        sendBroadcast(CallbackBroadcastReceiver.createIntent(data));
        return;
    }

    // OAuthAuthorization?
    try {
        serialize(oauth, "oauth.dat");
    } catch (IOException e) {
        e.printStackTrace();
        CallbackBroadcastReceiver.Data data = CallbackBroadcastReceiver.Data.create(e);
        sendBroadcast(CallbackBroadcastReceiver.createIntent(data));
        return;
    }

    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
}

From source file:inujini_.hatate.sqlite.dao.AccountDao.java

License:MIT License

/**
 * ?Twitter?./* w w  w. ja  v  a2 s  . c  o  m*/
 * @param context
 * @return ?????????{@link Twitter}
 */
public static List<Twitter> getTwitter(Context context) {
    val q = new QueryBuilder().selectAll().from(MetaAccount.TBL_NAME).where().equal(MetaAccount.UseFlag, true)
            .toString();

    val res = context.getResources();
    val consumerKey = res.getString(R.string.consumer_key);
    val consumerSecret = res.getString(R.string.consumer_secret);

    return new DatabaseHelper(context).getList(q, context, new Func1<Cursor, Twitter>() {
        @Override
        public Twitter call(Cursor c) {
            return new TwitterFactory(new ConfigurationBuilder().setOAuthConsumerKey(consumerKey)
                    .setOAuthConsumerSecret(consumerSecret)
                    .setOAuthAccessToken(c.getStringByMeta(MetaAccount.AccessToken))
                    .setOAuthAccessTokenSecret(c.getStringByMeta(MetaAccount.AccessSecret))
                    .setHttpConnectionTimeout(15000).setHttpReadTimeout(30000).build()).getInstance();
        }
    });
}

From source file:io.spring.batch.spark.Main.java

License:Apache License

public static void main(String[] args) {
    // URL of the Spark cluster
    String sparkUrl = "local[2]";

    SparkConf conf = new SparkConf();

    conf.setMaster(sparkUrl);//from w ww  . j  a va  2 s .c o  m
    conf.setAppName("Twitter");
    conf.validateSettings();

    JavaStreamingContext ssc = new JavaStreamingContext(sparkUrl, "Twitter", new Duration(1000));

    Configuration configuration = new ConfigurationBuilder()
            .setOAuthConsumerKey(System.getProperty("twitter4j.oauth.consumerKey"))
            .setOAuthConsumerSecret(System.getProperty("twitter4j.oauth.consumerSecret"))
            .setOAuthAccessToken(System.getProperty("twitter4j.oauth.accessKey"))
            .setOAuthAccessTokenSecret(System.getProperty("twitter4j.oauth.accessSecret")).setDebugEnabled(true)
            .build();

    JavaDStream<Status> tweets = TwitterUtils.createStream(ssc, new OAuthAuthorization(configuration));

    tweets.map(new Function<Status, String>() {
        public String call(Status status) {
            return status.getText();
        }
    }).dstream().saveAsTextFiles("hdfs://localhost:8020/spark/twitter/", "txt");

    ssc.start();

    // Just run stream for 20 seconds
    ssc.awaitTermination(20000);
}

From source file:io.warp10.script.functions.TWITTERDM.java

License:Apache License

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
    ///*w  ww.j a va2  s.c  o m*/
    // Extract parameters
    //

    String text = stack.pop().toString();
    String recipient = stack.pop().toString();
    String accessSecret = stack.pop().toString();
    String accessToken = stack.pop().toString();
    String consumerSecret = stack.pop().toString();
    String consumerKey = stack.pop().toString();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessSecret);
    TwitterFactory tf = new TwitterFactory(cb.build());

    Twitter twitter = tf.getInstance();

    try {
        twitter.sendDirectMessage(recipient, text);
    } catch (TwitterException te) {
        throw new WarpScriptException("Error while sending Twitter Direct Message", te);
    }

    return stack;
}

From source file:it.greenvulcano.gvesb.social.twitter.TwitterSocialAdapterAccount.java

License:Open Source License

/**
 * This method returns the interface class towards Twitter, already instantiated with the
 * account's tokens/*from  w w w . ja v  a 2  s  .  c om*/
 * 
 * @return {@link Twitter}
 */
public Twitter getProxyObject() {
    if (twitter != null) {
        return twitter;
    } else {
        // setting OAuth tokens
        ConfigurationBuilder confBuilder = new ConfigurationBuilder();
        if (proxy != null) {
            confBuilder.setHttpProxyHost(proxy.getHttpProxyHost());
            confBuilder.setHttpProxyPort(proxy.getHttpProxyPort());
            confBuilder.setHttpProxyUser(proxy.getHttpProxyUser());
            confBuilder.setHttpProxyPassword(proxy.getHttpProxyPassword());
        }
        confBuilder.setOAuthConsumerKey(consumerKey);
        confBuilder.setOAuthConsumerSecret(consumerSecret);
        confBuilder.setOAuthAccessToken(accessToken);
        confBuilder.setOAuthAccessTokenSecret(accessTokenSecret);
        Configuration config = confBuilder.build();
        // instantiating Twitter object
        this.twitter = new TwitterFactory(config).getInstance();
    }
    logger.info("got TwitterFactory instance.");
    return twitter;
}