Example usage for twitter4j.conf ConfigurationBuilder build

List of usage examples for twitter4j.conf ConfigurationBuilder build

Introduction

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

Prototype

public Configuration build() 

Source Link

Usage

From source file:entities.TwitterFeed.java

public void postTweet() {
    KeyReader keyreader = new KeyReader();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(keyreader.getConsumerKey());
    cb.setOAuthConsumerSecret(keyreader.getConsumerSecret());
    cb.setOAuthAccessToken(keyreader.getAccessToken());
    cb.setOAuthAccessTokenSecret(keyreader.getAccessTokenSecret());

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

    try {/*from   ww w  .j a v a 2  s .  c o m*/
        tf.updateStatus(typeTweet.getText());
        System.out.println("tweet post success");

    } catch (TwitterException te) {
        System.out.println("tweet post failed");
        te.printStackTrace();
    }
}

From source file:erando.controllers.AddProductController.java

@FXML
private void addProductAction(ActionEvent event)
        throws FileNotFoundException, IOException, TwitterException, DocumentException {
    Product p = new Product();
    Sms sms = new Sms();
    ISms smsservice = new SmsService();
    IShopService productService = new ProductService();
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("YYYY:MM/HH:mm:ss");

    p.setTitre(pTitre.getText());/*www. j  a v  a 2s. co m*/
    p.setPrix(Integer.parseInt(pPrix.getText()));
    p.setDescription(pDescription.getText());
    p.setType(pType.getValue().toString());
    p.setDate(sdf.format(cal.getTime()));
    p.setImage(imageName);
    if (!pTitre.getText().isEmpty() && !pPrix.getText().isEmpty() && !pDescription.getText().isEmpty()
            && !pType.getValue().toString().isEmpty()) {
        productService.add(p);
        ////////send sms to subs
        sms.setNum("" + Parameters.user.getNumTel());
        sms.setMessagetel("Product Added To Store go check it !");
        smsservice.sendSms(sms);

        ////////share on facebook (when asked by the owner ! )
        if (shareFacebook.isSelected()) {
            String accessToken = "EAACEdEose0cBAKLtkZBKZCBoEkx4MApf3HxDMAR93PoJ6lAAuZAMdfY9vtob2ii78C6TN88hSV8HK0tDZBskaUz5pcbH1HqVeDRISuEHsG0qqUZBca4gHGnANPWcZBSZA9RNFHpbwVHJ46ITntn52SGQWetPPaZBsNlsFXbpcDrKytOVtmspQzfrM8GiUQtm1kQZD";
            FacebookClient fbClient = new DefaultFacebookClient(accessToken, Version.LATEST);
            File fs = new File("C:\\Users\\F.Mouhamed\\Desktop\\Esprit\\ERandoPi\\userfiles\\");
            fs.getParentFile().setExecutable(true);
            fs.getParentFile().setReadable(true);
            fs.getParentFile().setWritable(true);
            ////////FileInputStream fis = new FileInputStream(fs.getParentFile());
            User me = fbClient.fetchObject("me", User.class);
            FacebookType response;
            response = fbClient.publish("me/feed", FacebookType.class, Parameter.with("message",
                    p.getTitre() + "\n " + p.getDescription() + "\n Prix:" + p.getPrix()));
        }

        ////////share on twitter (when asked by the owner ! )
        if (shareTwitter.isSelected()) {
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true).setOAuthConsumerKey("dHU6c4cXI6HDeLI3pakG8PYtp")
                    .setOAuthConsumerSecret("n0NxZVXgpEMGJboWYBSD1nfbaa3Ov2qL0e9h2GzyUsa8wQ0q0p")
                    .setOAuthAccessToken("729655065716346881-gukmKiOsT5WFv05t3yfQFrWgoPycQGD")
                    .setOAuthAccessTokenSecret("4qTGW5YdG8j9biJeAybzIcivCPZaAOqES2PhoJI9S7WKL");
            TwitterFactory tf = new TwitterFactory(cb.build());
            twitter4j.Twitter tw = tf.getInstance();
            String StatusMessage = ("Titre :" + p.getTitre() + "\nDescription:\n" + p.getDescription()
                    + "\nPrix:" + p.getPrix());
            StatusUpdate status = new StatusUpdate(StatusMessage);
            tw.updateStatus(status);
        }
        /////////show notification
        Notifications notificationBuilder = Notifications.create().title("sucess").text("produit ajouter")
                .graphic(null).hideAfter(Duration.seconds(4)).position(Pos.BOTTOM_RIGHT);
        notificationBuilder.darkStyle();
        notificationBuilder.showConfirm();
        /////////send emails to users subscribed to this type of product
        List<String> subs = productService.getSubscribes(p.getType());
        mailToSubs mails = new mailToSubs();
        for (String s : subs) {
            mails.envoyerfacture(s.toString(), p.getImage().toString(), p.getId(), p.getTitre(), p.getPrix(),
                    p.getDescription());
        }
    }
}

From source file:examencodtwitter.Metodos.java

/**
         /*from  w  w  w  .  j  a va 2 s.  c  o  m*/
 */
public Metodos() {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("xxxxxxxxxx").setOAuthConsumerSecret("xxxxxxxxxxxxxxxxxxxxxx")
            .setOAuthAccessToken("xxxxxxxxxxxxxxxxxxxxxx")
            .setOAuthAccessTokenSecret("xxxxxxxxxxxxxxxxxxxxxxxxxx");

    twitter = new TwitterFactory(cb.build()).getInstance();
}

From source file:examendetwitter.metodostwitter.java

/**
 * Constructor, da acceso a nuestra cuenta en twitter.
 *///from  w  ww  .  j a  v  a2s  .  com
public metodostwitter() {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("ttn86DHjTWZ21heKN6uQp9iy6")
            .setOAuthConsumerSecret("wQagAbytgoScb8UtCwY5nupQJkmW844MNrpMTVuQMFytxmceuP")
            .setOAuthAccessToken("3318200759-FsPeZSPibyDHgiPk7KllUBmvN5LarHeFpjH3JSv")
            .setOAuthAccessTokenSecret("z5I7uNEiIZH0ni9iNhKyUtASnHnGXN6puxjfQi6476RF0");
    twitter = new TwitterFactory(cb.build()).getInstance();
    twitter = new TwitterFactory("twitter4j.properties").getInstance();

}

From source file:flight_ranker.Flight_colllector.java

public static void main(String[] args) throws FileNotFoundException, IOException {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);//from  ww w .  j a  va 2  s .c om
    cb.setOAuthConsumerKey("Oa6WAzH0j3sgVrP0CNGvxnWA2");
    cb.setOAuthConsumerSecret("sLdoFybvJvVFz7Lxbbv9KWQDFeKcVeZAkWDC4QMHnx5lV2OmGE");
    cb.setOAuthAccessToken("2691889945-5NOBWKUgT9FiAoyOQSCFg8CLlPRlDMbWcUrJBdK");
    cb.setOAuthAccessTokenSecret("J6tA8Sxrtz2JNSFdQwAonbGxNfLNuD9I54Zfvomku3p5t");

    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

    StatusListener listener = new StatusListener() {

        @Override
        public void onException(Exception arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatus(Status status) {
            User user = status.getUser();

            // gets Username
            String username = status.getUser().getScreenName();
            long followers = user.getFollowersCount();

            long retweets = status.getRetweetCount();

            long favs = status.getFavoriteCount();

            System.out.println("USERNAME--> " + username);
            System.out.println("FOLLOWERS--> " + followers);
            String profileLocation = user.getLocation();

            //                System.out.println("RETWEETS--> "+retweets);

            //                System.out.println("FAVOURITES--> "+favs);

            System.out.println("LOCATION--> " + profileLocation);
            long tweetId = status.getId();
            System.out.println("TWEET ID--> " + tweetId);
            String content = status.getText();
            System.out.println("TWEET--> " + content + "\n");

            BufferedWriter b1 = null, b2, b3, b4, b5, b6, b7 = null;

            try {
                //output_file = new BufferedReader(new FileReader("G:\\Sentiwords.txt"));

                FileWriter f1 = new FileWriter("G:\\flights_data.txt", true);
                b1 = new BufferedWriter(f1);
                b1.write("#USERNAME- " + username);
                b1.newLine();

                b1.write("#Followers- " + followers);

                b1.newLine();

                b1.write("#Location- " + profileLocation);

                b1.newLine();
                b1.write("#ID- " + tweetId);

                b1.newLine();
                b1.write("#Tweet- " + content);
                b1.newLine();
                b1.newLine();

                tweet_editor modified_tweet = new tweet_editor(content);
                //tweet_tagger tagged_tweet = new tweet_tagger(modified_tweet.edited_tweet);
                //System.out.println(tagged_tweet.tagged);

                sentiment_calculator senti_value = new sentiment_calculator(modified_tweet.edited_tweet);

                if (content.contains("Indigo")) {
                    System.out.println("indigo");
                    FileWriter f2 = new FileWriter("G:\\Indigo.txt", true);
                    b2 = new BufferedWriter(f2);
                    b2.write(Double.toString(senti_value.senti_rate));
                    b2.newLine();
                }

                if (content.contains("Jet")) {
                    System.out.println("jet");
                    FileWriter f3 = new FileWriter("G:\\jet.txt", true);
                    b3 = new BufferedWriter(f3);
                    b3.write(Double.toString(senti_value.senti_rate));
                    b3.newLine();
                }

                if (content.contains("Indian")) {
                    System.out.println("indian");
                    FileWriter f4 = new FileWriter("G:\\Indian.txt", true);
                    b4 = new BufferedWriter(f4);
                    b4.write(Double.toString(senti_value.senti_rate));
                    b4.newLine();
                }

                if (content.contains("Spicejet")) {
                    System.out.println("spicejet");
                    FileWriter f5 = new FileWriter("G:\\spicejet.txt", true);
                    b5 = new BufferedWriter(f5);
                    b5.write(Double.toString(senti_value.senti_rate));
                    b5.newLine();
                }

                if (content.contains("AirAsia")) {
                    System.out.println("airasia");
                    FileWriter f6 = new FileWriter("G:\\airasia.txt", true);
                    b6 = new BufferedWriter(f6);
                    b6.write(Double.toString(senti_value.senti_rate));
                    b6.newLine();
                }

                try {
                    //output_file = new BufferedReader(new FileReader("G:\\Sentiwords.txt"));

                    FileWriter f7 = new FileWriter("G:\\flight_senti.txt", true);
                    b7 = new BufferedWriter(f7);
                    b7.write(String.valueOf(senti_value.senti_rate));
                    b7.newLine();

                }

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

                finally {
                    try {
                        b7.close();
                    } catch (IOException ex) {
                        Logger.getLogger(Flight_colllector.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

            }

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

            finally {
                try {
                    b1.close();
                } catch (IOException ex) {
                    Logger.getLogger(Flight_colllector.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };

    FilterQuery fq = new FilterQuery();

    String keywords[] = {
            "Indian Airlines, Indigo Airlines, Indigo Airline , Indian Airline , Spicejet , jetAirways , Jet Airways, Jet Airlines , airasia" }; //we will pass stock related keyword here

    fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.filter(fq);

}

From source file:foo.bar.twitter.sample01.Sample01Activity.java

License:Apache License

/**
 * connect twitter//from  w ww  .j  a va 2  s  . c om
 */
private void connectTwitter() {
    ConfigurationBuilder confbuilder = new ConfigurationBuilder();
    confbuilder.setOAuthConsumerKey(ConstantValue.CONSUMER_KEY);
    confbuilder.setOAuthConsumerSecret(ConstantValue.CONSUMER_SECRET);
    Configuration conf = confbuilder.build();

    twitter = new TwitterFactory(conf).getInstance();
    twitter.setOAuthAccessToken(null);

    try {
        requestToken = twitter.getOAuthRequestToken(ConstantValue.CALLBACK_URL);
        Intent intent = new Intent(this, TwitterLoginActivity.class);
        intent.putExtra(ConstantValue.IEXTRA_AUTH_URL, requestToken.getAuthorizationURL());
        this.startActivityForResult(intent, 0);
    } catch (TwitterException e) {
        Toast.makeText(this, "Twitter Exception!!\n" + e.toString(), Toast.LENGTH_LONG).show();
    }
}

From source file:formel0api.Game.java

License:Open Source License

private void sendHighScoreToServer() {
    try {/*from   w w  w .  j a  v  a2  s.  c  om*/
        String now = this.javaDate2XmlDate(new Date()).toString();

        StringBuffer xmlStr = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
                + "<highScoreRequestType \n" + "   xmlns=\"http://big.tuwien.ac.at/we/highscore/data\" \n"
                + "   xmlns:ssd=\"http://www.dbai.tuwien.ac.at/education/ssd/SS13/uebung/Tournament\">\n" + "\n"
                + "   <UserKey>34EphAp2C4ebaswu</UserKey>\n" + "   <ssd:tournament start-date=\"" + now
                + "\" end-date=\"" + now + "\" registration-deadline=\"" + now + "\">\n"
                + "      <ssd:players>\n" + "         <ssd:player username=\"" + this.getLeaderData().getName()
                + "\">\n" + "            <ssd:date-of-birth>"
                + this.getFormattedDate(this.getLeaderData().getBirthday()) + "</ssd:date-of-birth>\n"
                + "            <ssd:gender>" + this.getLeaderData().getSex() + "</ssd:gender>\n"
                + "         </ssd:player>\n" + "      </ssd:players>\n" + "      <ssd:rounds>\n"
                + "         <ssd:round number=\"0\">\n" + "            <ssd:game date=\"" + now
                + "\" status=\"finished\" duration=\"" + this.getSpentTime() + "\" winner=\""
                + this.getLeaderData().getName() + "\">\n" + "               <ssd:players>\n"
                + "                  <ssd:player ref=\"" + this.getLeaderData().getName() + "\"/>\n"
                + "               </ssd:players>\n" + "            </ssd:game>\n" + "         </ssd:round>\n"
                + "      </ssd:rounds>\n" + "   </ssd:tournament>\n" + "</highScoreRequestType>");

        JAXBContext jaxbContext = JAXBContext.newInstance(HighScoreRequestType.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        HighScoreRequestType request = (HighScoreRequestType) jaxbUnmarshaller
                .unmarshal(new StreamSource(new StringReader(xmlStr.toString())));

        PublishHighScoreService service = new PublishHighScoreService();
        PublishHighScoreEndpoint endpoint = service.getPublishHighScorePort();
        String uuid = endpoint.publishHighScore(request);

        Logger.getLogger(Game.class.getName()).log(Level.INFO, uuid);

        TwitterStatusMessage tmsg = new TwitterStatusMessage(this.getLeader().getName(), uuid, new Date());

        (new ITwitterClient() {
            @Override
            public void publishUuid(TwitterStatusMessage message) throws Exception {
                ConfigurationBuilder cb = new ConfigurationBuilder();
                cb.setDebugEnabled(true).setOAuthConsumerKey("GZ6tiy1XyB9W0P4xEJudQ")
                        .setOAuthConsumerSecret("gaJDlW0vf7en46JwHAOkZsTHvtAiZ3QUd2mD1x26J9w")
                        .setOAuthAccessToken("1366513208-MutXEbBMAVOwrbFmZtj1r4Ih2vcoHGHE2207002")
                        .setOAuthAccessTokenSecret("RMPWOePlus3xtURWRVnv1TgrjTyK7Zk33evp4KKyA");
                TwitterFactory tf = new TwitterFactory(cb.build());
                Twitter twitter = tf.getInstance();
                twitter.updateStatus(message.toString());
            }
        }).publishUuid(tmsg);

        message = "UUID " + uuid + " wurde auf Twitter verffentlicht";

    } catch (JAXBException e) {
        Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, e);
    } catch (Failure e) {
        Logger.getLogger(Game.class.getName()).log(Level.SEVERE, e.getFaultInfo().getDetail());
    } catch (Exception ex) {
        Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

License:Apache License

@GET
@Path("/postTweet")
@Produces(MediaType.APPLICATION_JSON)//from  w  ww . ja v  a 2s  . c om
public String getTweet() 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 latestStatus = "TEST55555555";
    Status status = twitter.updateStatus(latestStatus);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    return "Successfully updated status to " + status.getText();

}

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

License:Apache License

@GET
@Path("/sendTweet")
@Produces(MediaType.APPLICATION_JSON)//from   w w w  . j a va  2s  .  c om
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 {/*from ww w  . j  av  a  2 s.  c o  m*/
        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);
    }
}