Example usage for twitter4j.auth AccessToken AccessToken

List of usage examples for twitter4j.auth AccessToken AccessToken

Introduction

In this page you can find the example usage for twitter4j.auth AccessToken AccessToken.

Prototype

public AccessToken(String token, String tokenSecret) 

Source Link

Usage

From source file:org.umd.assignment.spout.TwitterSampleSpout.java

License:Apache License

@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    queue = new LinkedBlockingQueue<String>(1000);
    _collector = collector;/*  ww  w. ja v  a  2  s  . c o  m*/

    StatusListener listener = new StatusListener() {

        @Override
        public void onStatus(Status status) {
            queue.offer(status.getText());
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice sdn) {
        }

        @Override
        public void onTrackLimitationNotice(int i) {
        }

        @Override
        public void onScrubGeo(long l, long l1) {
        }

        @Override
        public void onException(Exception ex) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }

    };

    TwitterStreamFactory fact = new TwitterStreamFactory(
            new ConfigurationBuilder().setJSONStoreEnabled(true).build());

    _twitterStream = fact.getInstance();

    _twitterStream.addListener(listener);
    _twitterStream.setOAuthConsumer(consumerKey, consumerSecret);

    AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    _twitterStream.setOAuthAccessToken(token);

    if (keyWords.length == 0) {
        _twitterStream.sample();
    } else {
        FilterQuery query = new FilterQuery().track(keyWords);
        _twitterStream.filter(query);
    }

}

From source file:org.umit.icm.mobile.utils.SDCardReadWrite.java

License:Open Source License

/**
 * Returns a {@link AccessToken} object of the file content from the specified 
 * filename in directory.//from  w w w .  j a v  a 2 s. c o m
 * 
 *                                    
                             
@return  {@link AccessToken}
 *   
        
@param  dir  An object of the type {@link String}
 *         
                                                              
@see         File
 *
         
@see         FileReader
 *
         
@see         Environment
 */
public static AccessToken readAccessToken(String dir) throws IOException, RuntimeException {
    sdCard = Environment.getExternalStorageDirectory();
    File keyDir = new File(sdCard.getAbsolutePath() + dir);
    File file = new File(keyDir, Constants.ACCESS_TOKEN_FILE);
    InputStream inputStream = new FileInputStream(file.toString());
    ObjectInputStream objInputStream = new ObjectInputStream(new BufferedInputStream(inputStream));
    try {
        String token = ((String) objInputStream.readObject());
        String tokenSecret = ((String) objInputStream.readObject());
        return new AccessToken(token, tokenSecret);
    } catch (Exception e) {
        throw new RuntimeException("readToken exception", e);
    } finally {
        objInputStream.close();
    }
}

From source file:org.unimonk.flume.source.twitter.TwitterSource.java

License:Apache License

@Override
public void start() {

    final ChannelProcessor channel = getChannelProcessor();

    StatusListener listener = new StatusListener() {
        @Override/*from   ww  w  . j av  a2  s .com*/
        public void onStatus(Status status) {

            Tweet tweet = new Tweet();
            tweet.setId(status.getId());
            tweet.setUserId(status.getUser().getId());
            tweet.setLatitude(status.getGeoLocation().getLatitude());
            tweet.setLongitude(status.getGeoLocation().getLongitude());
            tweet.setText(status.getText());
            tweet.setCreatedAt(new Timestamp(status.getCreatedAt().getTime()));

            Event event = EventBuilder.withBody(tweet.toString(), Charsets.UTF_8);
            sourceCounter.incrementAppendReceivedCount();
            try {
                channel.processEvent(event);
                sourceCounter.incrementEventAcceptedCount();
            } catch (ChannelException ex) {
                logger.error("In Twitter source {} : Unable to process event due to exception {}.", getName(),
                        ex);

            }
        }

        // This listener will ignore everything except for new tweets
        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
        }

        @Override
        public void onException(Exception ex) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }
    };

    logger.debug("Setting up Twitter sample stream using consumer key {} and" + " access token {}",
            new String[] { consumerKey, accessToken });

    twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    if (keywords.length == 0) {
        logger.debug("Starting up Twitter sampling...");
        twitterStream.sample();
    } else {
        logger.debug("Starting up Twitter filtering...");
        FilterQuery query = new FilterQuery().track(keywords);
        twitterStream.filter(query);
    }
    this.sourceCounter.start();
    super.start();
}

From source file:org.wso2.fasttrack.project.roadlk.rest.DatasetGenerator.java

License:Open Source License

/**
 * @param consumerKey/*  ww w.j a v  a2s  . co m*/
 *            Twitter Consumer Key (API Key)
 * @param consumerSecret
 *            Twitter Consumer Secret (API Secret)
 * @param accessToken
 *            Twitter Access Token
 * @param accessTokenSecret
 *            Twitter Access Token Secret
 * @param pageLimit
 *            Maximum pages to be retrieved
 * @throws IOException
 * @throws TwitterException
 */
@SuppressWarnings("resource")
public void generateDataset(String consumerKey, String consumerSecret, String accessToken,
        String accessTokenSecret, int pageLimit) throws IOException, TwitterException {
    // Twitter object of Twitter4J library
    Twitter twitter = TwitterFactory.getSingleton();

    // Twitter API authentication
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    PrintWriter printWriter = null;

    try {
        printWriter = new PrintWriter(new BufferedWriter(new FileWriter("dataset.txt", true)));
    } catch (IOException e) {
        throw new IOException(e);
    }

    LOGGER.debug("Twitter feed extraction started.");

    for (int i = 1; i < pageLimit; i = i + 1) {

        Paging paging = new Paging(i, 100);
        ResponseList<Status> statuses = null;

        try {
            statuses = twitter.getUserTimeline("road_lk", paging);
        } catch (TwitterException e) {
            //LOGGER.error("TwitterException occurred." + e.getMessage());
            throw new TwitterException(e);
        }

        for (Status status : statuses) {
            printWriter.println(status.getCreatedAt() + ": " + status.getText());
        }
    }
    printWriter.close();
    LOGGER.debug("Twitter feed extraction completed.");
}

From source file:org.zoneproject.extractor.twitterreader.TwitterApi.java

License:Open Source License

public static ArrayList<Item> getFluxFromSearch(String search, String sourceUri) {
    ArrayList<Item> result = new ArrayList<Item>();
    try {//from  w w w.  ja va2s .  c o  m

        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(Config.getVar("Twitter-OAuth-customer"),
                Config.getVar("Twitter-OAuth-customerKey"));
        twitter.setOAuthAccessToken(new AccessToken(Config.getVar("Twitter-OAuth-access"),
                Config.getVar("Twitter-OAuth-accessKey")));

        Query query = new Query(search);
        QueryResult items = twitter.search(query);
        for (Status r : items.getTweets()) {
            result.add(TwitterApi.getItemFromStatus(r, sourceUri));
        }

        return result;
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterApi.class.getName()).log(Level.WARNING, null, ex);
        return result;
    }
}

From source file:org.zoneproject.extractor.twitterreader.TwitterApi.java

License:Open Source License

public static ArrayList<Item> getFluxFromUser(String user, String sourceUri) {
    ArrayList<Item> result = new ArrayList<Item>();
    try {/*from   w  w w.j a v  a 2s .  c  om*/

        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(Config.getVar("Twitter-OAuth-customer"),
                Config.getVar("Twitter-OAuth-customerKey"));
        twitter.setOAuthAccessToken(new AccessToken(Config.getVar("Twitter-OAuth-access"),
                Config.getVar("Twitter-OAuth-accessKey")));

        List<Status> statusess = twitter.getUserTimeline(user);
        for (Status r : statusess) {
            result.add(TwitterApi.getItemFromStatus(r, sourceUri));
        }

        return result;
    } catch (TwitterException ex) {
        logger.warn(ex.getErrorMessage());
        return result;
    }
}

From source file:org.zoneproject.extractor.twitterreader.TwitterApi.java

License:Open Source License

/**
 * Get the access token for a specified URI
 * @param the twitter URI//from www.  ja  v  a2 s  .co m
 * @return the AccessToken for specified URI
 */
private static AccessToken getAccessToken(String uri) {
    ResultSet results = Database.getRelationsForURI(uri, ZoneOntology.GRAPH_SOURCES);
    String token = null, secret = null;
    while (results.hasNext()) {
        QuerySolution result = results.nextSolution();
        if (result.get("?relation").toString().equals(ZoneOntology.SOURCES_TWITTER_TOKEN)) {
            token = result.get("?object").toString();
        } else if (result.get("?relation").toString().equals(ZoneOntology.SOURCES_TWITTER_TOKEN_SECRET)) {
            secret = result.get("?object").toString();
        }
    }
    if (token == null || secret == null) {
        return null;
    }
    return new AccessToken(token, secret);
}

From source file:reo7sp.socn.social.TwitterManager.java

License:Apache License

private AccessToken loadAuth() throws IOException {
    String token = null;//from w  w w .  j  a  v a  2s. co  m
    String tokenSecret = null;

    BufferedReader reader = new BufferedReader(new FileReader(authFile));
    String s;
    int i = 0;
    while ((s = reader.readLine()) != null) {
        switch (i) {
        case 0:
            token = s;
            break;
        case 1:
            tokenSecret = s;
            break;
        }
        i++;
    }
    reader.close();

    return new AccessToken(token, tokenSecret);
}

From source file:sentinets.ImportTweets.java

License:Open Source License

public ImportTweets() {
    twitter = new TwitterFactory().getInstance();
    AccessToken accessToken = new AccessToken(ImportTweets.accessToken, ImportTweets.accessTokenSecret);

    twitter.setOAuthConsumer(ImportTweets.consumerKey, ImportTweets.consumerSecret);
    twitter.setOAuthAccessToken(accessToken);
    //stats = new TweetCorpusStatistics();
}

From source file:servlet.TwitterClient.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w w.  j  a  v a 2 s .c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TwitterException {

    String consumerKey = "acdi5Tpjda5dshPSgsNdc2YuP";
    String consumerSecret = "5mZuFFShjXdwTCbk1hRZ9c47BJz9vKwoPFDPDHyG9xdxLGdZRi";
    String accessToken = "224428346-hU7uwq12mUSvxT7jClIEnpCN5Lj6Rp1YgnQiwG6h";
    String accessTokenSecret = "8kPqai6ciArmiWinkBOGvxHfYbif2OL7N96NbQYvEHfiH";
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    AccessToken accessTok = new AccessToken(accessToken, accessTokenSecret);
    twitter.setOAuthAccessToken(accessTok);

    String action = (request.getParameter("action") != null) ? request.getParameter("action") : "fresh";
    if (action.equalsIgnoreCase("Send")) {
        String latestStatus = request.getParameter("newTweet");
        Status status = twitter.updateStatus(latestStatus);
    }
    //cargamos todos los tweets

    ResponseList<Status> a = twitter.getUserTimeline(new Paging(1, 20));

    request.setAttribute("Tweets", a);
    //mandamos los tweets en una lista a la vista
    request.getRequestDispatcher("twitter.jsp").forward(request, response);
}