Giter Site home page Giter Site logo

myfirstrepo's Introduction

tags projects
spring-social-twitter

This guide walks you through the process of creating a simple web application that fetches data from Twitter.

What you’ll build

You’ll learn how to build a Spring application that accesses profile data from a Twitter user and from people whom the user follows on Twitter.

Enable Twitter

Before you can fetch a user’s data from Twitter, you must specify your application’s ID and secret by setting the spring.social.twitter.appId and spring.social.twitter.appSecret properties. You can set these via any means supported by Spring Boot, including setting them in an application.properties file:

src/main/resources/application.properties

link:complete/src/main/resources/application.properties[role=include]

As shown here, the properties have fake values. The values given to these properties correspond to your application’s consumer key and secret you obtain when you register the application with Twitter. For the code to work, substitute the real values given to you by Twitter in place of the fake values.

The presence of these properties and Spring Social Twitter in the classpath will trigger automatic configuration of Spring Social’s ConnectController, TwitterConnectionFactory, and other components of Spring Social’s connection framework.

Create connection status views

Although much of what ConnectController does involves redirecting to Twitter and handling a redirect from Twitter, it also shows connection status when a GET request to /connect is made. ConnectController defers to a view named connect/{provider ID}Connect when no existing connection is available and to connect/{providerId}Connected when a connection exists for the provider. In this case, {provider ID} is "twitter".

ConnectController does not define its own connection views, so you need to create them. First, here’s a Thymeleaf view to be shown when no connection to Twitter exists:

src/main/resources/templates/connect/twitterConnect.html

link:complete/src/main/resources/templates/connect/twitterConnect.html[role=include]

The form on this view will POST to /connect/twitter, which is handled by ConnectController and will kick off the OAuth authorization code flow.

Here’s the view to be displayed when a connection exists:

src/main/resources/templates/connect/twitterConnected.html

link:complete/src/main/resources/templates/connect/twitterConnected.html[role=include]

Fetch Twitter data

With Twitter configured in your application, you now can write a Spring MVC controller that fetches data for the user who authorized the application and presents it in the browser. HelloController is just such a controller:

src/main/java/hello/HelloController.java

link:complete/src/main/java/hello/HelloController.java[role=include]

HelloController is created by injecting a Twitter object into its constructor. The Twitter object is a reference to Spring Social’s Twitter API binding.

The helloTwitter() method is annotated with @RequestMapping to indicate that it should handle GET requests for the root path (/). The first thing it does is check to see if the user has authorized the application to access the user’s Twitter data. If not, then the user is redirected to ConnectController with the option to begin the authorization process.

If the user authorizes the application to access the data, the application can fetch almost any data pertaining to the authorizing user. For the purposes of this guide, the application only fetches the user’s profile as well as a list of profiles belonging to Twitter users whom the user follows (but not those who follow the user). Both are placed into the model to be displayed by the view identified as "hello".

Speaking of the "hello" view, here it is as a Thymeleaf template:

src/main/resources/templates/hello.html

link:complete/src/main/resources/templates/hello.html[role=include]

This template simply displays a greeting to the user and a list of the user’s friends. Note that even though the full user profiles were fetched, only the names from those profiles are used in this template.

Make the application executable

Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method. And along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance.

src/main/java/hello/Application.java

link:complete/src/main/java/hello/Application.java[role=include]

The main() method defers to the SpringApplication helper class, providing Application.class as an argument to its run() method. This tells Spring to read the annotation metadata from Application and to manage it as a component in the Spring application context.

The @ComponentScan annotation tells Spring to search recursively through the hello package and its children for classes marked directly or indirectly with Spring’s @Component annotation. This directive ensures that Spring finds and registers the GreetingController, because it is marked with @Controller, which in turn is a kind of @Component annotation.

The @Import annotation tells Spring to import additional Java configuration. Here it is asking Spring to import the TwitterConfig class where you enabled Twitter in your application.

The @EnableAutoConfiguration annotation switches on reasonable default behaviors based on the content of your classpath. For example, because the application depends on the embeddable version of Tomcat (tomcat-embed-core.jar), a Tomcat server is set up and configured with reasonable defaults on your behalf. And because the application also depends on Spring MVC (spring-webmvc.jar), a Spring MVC DispatcherServlet is configured and registered for you — no web.xml necessary! Auto-configuration is a powerful, flexible mechanism. See the API documentation for further details.

... app starts up ...

Once the application starts up, you can point your web browser to http://localhost:8080. Because no connection is established yet, you see this screen prompting you to connect with Twitter:

No connection to Twitter exists yet.

When you click Connect to Twitter, the browser is redircted to Twitter for authorization:

Twitter needs your permission to allow the application to access your data.

At this point, Twitter asks if you’d like to allow the sample application to read tweets from your profile and see who you follow. Here the screen is misleading, because the application in this case will only read your profile details and the profile details of the people you follow. Click Authorize app to grant permission.

Once permission is granted, Twitter redirects the browser to the application. A connection is created and stored in the connection repository. You should see this page indicating that a connection was successful:

A connection with Twitter has been created.

If you click on the link on the connection status page, you are taken to the home page. This time, now that a connection exists, you see your name on Twitter and a list of your friends:

Guess noone told you life was gonna be this way.

Summary

Congratulations! You’ve developed a simple web application that uses Spring Social to obtain user authorization to fetch data from the user’s Twitter profile and from the profiles of people whom the user follows.

myfirstrepo's People

Contributors

gregturn avatar habuma avatar royclarkson avatar btalbott avatar cbeams avatar kdvolder avatar npscholar avatar

Watchers

 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.