GithubHelp home page GithubHelp logo

twitterproject's Introduction

TwitterProject

A Spring Boot RESTful API that takes pictures and videos about dogs from Reddit using the pushshift API and posts them on Twitter for your enjoyment.

https://twitter.com/Raebay99

Sample from a controller class using a CRUD repository to read and write data to the MySQL database

@RestController
@Controller
@Service
public class PostController {

    @Autowired
    public PostRepository postRepository;

    @Async
    @RequestMapping(value = "/addPostToDB", method = RequestMethod.POST)
    public Post addPost(@RequestBody Post newPost) {
        postRepository.save(newPost);
        return newPost;
    }
    
    @Async
    @RequestMapping(value = "/getPost/{id}", method = RequestMethod.GET)
    public Post getPost(@PathVariable("id") Integer id) {
        Post post = postRepository.findById(id).get();
        return post;
    }

    @Async
    @RequestMapping(value = "/getMostRecentPost", method = RequestMethod.GET)
    public Post getMostRecentPost() {
        int dbCount = (int)postRepository.count();
        Post post = postRepository.findById(dbCount).get();
        return post;
    }

Sample from a controller class where scheduled tasks are run to execute the CRUD commands every 12 hours

//Gets most recent post from specified subreddit and saves it to database
    @Scheduled(cron = "0 0 */12 * * * ")
    public void addPost() throws IOException {
        Post post = getPost(id);
        String url = "http://localhost:8080/addPostToDB";
        restTemplate.postForObject(url, post, Post.class);
        System.out.println("Post saved to db " + post.getTitle());

    }

//Posts most recent Reddit post saved to the database on to Twitter
    @Scheduled(cron = "0 0 */12 * * * ")
    public void postToTwitter() throws Exception {
        OAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(consumerKeyStr, consumerSecretStr);
        oAuthConsumer.setTokenWithSecret(accessTokenStr, accessTokenSecretStr);
        Post post = restTemplate.getForObject("http://localhost:8080/getMostRecentPost", Post.class);
        System.out.println("Post retrieved from DB" + post.getTitle() + " " + post.getId());
        if(post.getTitle() != null){
            String str = URLEncoder.encode(post.getTitle() +"\n" + post.getText()+"\n" + post.getUrl(), "UTF-8");
            HttpPost httpPost = new HttpPost("https://api.twitter.com/1.1/statuses/update.json?status=" + str );
            oAuthConsumer.sign(httpPost);
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println(statusCode + ':' + httpResponse.getStatusLine().getReasonPhrase());
            System.out.println(IOUtils.toString(httpResponse.getEntity().getContent()));
        }
        else{
            System.out.println("Post object was null");
        }

    }

//Take first post from specific subreddit and parses JSON to java object
    public Post getPost(int id) throws IOException {
        URL url = new URL("https://api.pushshift.io/reddit/search/submission/?subreddit="+ subRed + "&after=1d&sort=desc&sort_type=num_comments&is_video=false&size=1");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        String fullStr = "";
        while ((line = inputReader.readLine()) != null) {
            fullStr += line;
        }
        JSONObject json = new JSONObject(fullStr);
        String postURL = json.getJSONArray("data").getJSONObject(0).getString("url");
        String title = json.getJSONArray("data").getJSONObject(0).getString("title");
        String text = json.getJSONArray("data").getJSONObject(0).getString("selftext");

        if(text.length() > 235){
            text = text.substring(0, 235);
        }
        if(postURL.length() > 235){
            postURL = null;
        }
            Post post = new Post(id, title, text, postURL);
            inputStream.close();
            inputReader.close();
            return post;
    }
    ```

twitterproject's People

Contributors

raebay avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.