Monday, December 10, 2012

Spring Social with JavaConfig (Part 5)

Review

In the previous section, we have discussed the Spring Security-related configurations. In this section we will discuss the remaining configuration of our application.

Table of Contents

Click on a link to jump to that section:
  1. Functional Specs
  2. Generate OAuth keys
    • Facebook
    • Twitter
  3. Spring Social configuration
  4. Spring Security configuration
  5. JavaConfig
    • ApplicationInitializer.java
    • ApplicationContext.java
    • DataConfig.java
    • ThymeleafConfig.java
    • spring.properties
  6. View with Thymeleaf
  7. Layers
    • Domain
    • Repository
    • Service
    • Controller
  8. Running the application
    • Clone from GitHub
    • Create the Database
    • Run with Maven and Tomcat 7
    • Run with Maven and Jetty 8
    • Import to Eclipse
    • Validate with W3C

JavaConfig

As stated in the introduction, we will be using JavaConfig-based configuration instead of the usual XML config. However, I don't want to alienate our readers who are used to XML. As a result, I've decided to provide both implementations. However, our focus here is still on JavaConfig.

Note: With JavaConfig, we can now omit the ubiquitous web.xml. But in order to that, we need to run a Servlet 3.0 web container. For this tutorial, I have tested the application with Tomcat 7.0.30 (Maven plugin), 7.0.33 (standalone Tomcat), and Jetty 8.1.5.v20120716 (Maven plugin).

ApplicationInitializer.java

The ApplicationInitializer.java is the equivalent of web.xml. Here's where we declare the DispatcherServlet and also we've registered two filters: one for Spring Security and another for Spring Social.



Here's the equivalent XML configuration:



ApplicationContext.java

The ApplicationContext.java contains our main configuration. It's responsible for loading other configurations, either as JavaConfig or XML config.



Let's describe each annotation:
  • @Configuration
    - Marks a class as a JavaConfig
  • @ComponentScan(basePackages = {"org.krams"})
    - Configures scanning of Spring components

    This is equivalent in XML as:

  • @EnableWebMvc

    - Activates Spring's MVC support

    This is equivalent in XML as:

  • @Import({DataConfig.class, ThymeleafConfig.class, SocialConfig.class, SecurityConfig.class})
    - This allows us to import JavaConfig-based config. Notice we have imported four configuration classes
  • @ImportResource("classpath:trace-context.xml")
    - This allows us to import XML-based config files. (As a side note why can't we just declare this as a JavaConfig? It turns out there's no direct translation for the trace-context.xml, so we'll have to import it as XML).

    This is equivalent in XML as:

  • @PropertySource("classpath:spring.properties")
    - This allows us to import property files
  • @Bean
    - Declares a Spring bean

Here's the equivalent XML configuration:



DataConfig.java

The DataConfig.java contains our Spring Data configuration. This is where we declare our data source, transaction manager, and JPA entity manager.



Here's the equivalent XML configuration:



ThymeleafConfig.java

The ThymeleafConfig.java contains our Thymeleaf configuration. This is where we declare our Thymeleaf view resolver.


We've declared some special settings on our Thymeleaf configuration:
// Declare virtual paths
resolver.addTemplateAlias("connect/facebookConnect","facebook/connect");
resolver.addTemplateAlias("connect/twitterConnect","twitter/connect");
resolver.addTemplateAlias("connect/facebookConnected","facebook/connected");
resolver.addTemplateAlias("connect/twitterConnected","facebook/connected");

// Disable cache for testing purposes
resolver.setCacheable(false);

These allows to redirect virtual path requests to specific templates within our application. We need to do this because the ConnectController from Spring Social has its own built-in controller path requests. And we need to redirect the resulting views that matches our template path.

For example, when connecting to Facebook, ConnectController will use the connect/facebookConnect path and you are required to provide a view. Using the addTemplateAlias() method, we can provide a custom view, in this case, the view points to the directory in the WEB-INF/templates/facebook/connect.

Also, we've disabled the caching feature so that we can easily update and test our html pages.

Here's the equivalent XML configuration:


SecurityConfig.java

The SecurityConfig.java contains a single bean DelegatingFilterProxy. This is required for Spring Security.



spring.properties

spring.properties contains the property settings of our application. You need to declare your Facebook and Twitter OAuth settings here. Here's also where you declare your database.


messages_en.properties

This is for internationalization of messages. The default language is English. If you need to provide custom language, create a new properties file and replace the values according to the language you've chosen. Please see the Spring documentation for more info on internationalization.



Next

In the next section, we will discuss the Domain, Service, Controller, and View layers. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring Social with JavaConfig (Part 5) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring Social with JavaConfig (Part 6)

Review

In the previous section, we have discussed the remaining JavaConfig configurations. In this section, we will discuss the View layer along with Thymeleaf.

Table of Contents

Click on a link to jump to that section:
  1. Functional Specs
  2. Generate OAuth keys
    • Facebook
    • Twitter
  3. Spring Social configuration
  4. Spring Security configuration
  5. JavaConfig
    • ApplicationInitializer.java
    • ApplicationContext.java
    • DataConfig.java
    • ThymeleafConfig.java
    • spring.properties
  6. View with Thymeleaf
  7. Layers
    • Domain
    • Repository
    • Service
    • Controller
  8. Running the application
    • Clone from GitHub
    • Create the Database
    • Run with Maven and Tomcat 7
    • Run with Maven and Jetty 8
    • Import to Eclipse
    • Validate with W3C

View with Thymeleaf


The goal of this section is not to teach you everything about Thymeleaf but to point out the important sections. If you need a full Thymeleaf documentation, please see the official docs.

What is Thymeleaf?

Thymeleaf is a Java library. It is an XML / XHTML / HTML5 template engine (extensible to other formats) that can work both in web and non-web environments. It is better suited for serving XHTML/HTML5 at the view layer of web applications, but it can process any XML file even in offline environments.

It provides an optional module for integration with Spring MVC, so that you can use it as a complete substitute of JSP in your applications made with this technology, even with HTML5.

The main goal of Thymeleaf is to provide an elegant and well-formed way of creating templates. Its Standard and SpringStandard dialects allow you to create powerful natural templates, that can be correctly displayed by browsers and therefore work also as static prototypes. You can also extend Thymeleaf by developing your own dialects.

Source: Thymeleaf.org

Since we have numerous html pages with duplicate setup, I will focus on the ones that are most instructive.

Facebook profile.html
This displays our Facebook profile information.



Let's discuss the important attributes
  • The # means to resolve the attribute from the messages bundle
  • The $ means to resolve the attribute from the model
  • The # and $ can be combined together so that messages can be dynamically generated from the model and internationalized from the messages bundle
  • th:href attribute
    <link rel="stylesheet" href="../../../resources/css/style.css"  th:href="@{/resources/css/style.css}" />
    
    Declares a resource relative to the context of the app. When testing the html mockup, the th:href attribute is ignored by the browser. When running the app, Thymeleaf's preprocessor will ignore the value of the href attribute and use the value in the th:ref attribute.
  • th:text attribute
    <title th:text="#{'profile.title.' + ${source}}">Title</title>
    
    Declares the usual title element. When testing the html mockup, the th:text attribute is ignored by the browser. When running the app, Thymeleaf's preprocessor will ignore the value of the title and use the value in the th:text attribute.

    This is a common attribute. So pay attention to this one.
  • th:include attribute
    <div th:include="include :: menu"></div>
    
    Includes an html fragment. The fragment is declared in the include.html
  • th:src attribute
    <img src="#" th:src="@{'http://graph.facebook.com/' +  ${profileInfo.id}} + '/picture'" alt="profile image"/>    
    
    Declares an image element. The attribute th:src is similar with the th:href behavior.

    The value of th:src contains two parts: 'http://graph.facebook.com/' which is a literal string and ${profileInfo.id} is a model attribute. The value is sent by our Spring controller (see below):


  • th:if attribute
    <dd th:if="${#strings.isEmpty(profileInfo.email)}" th:text="'no email listed'">john@email.com</dd>     
    
    A conditional expression. This states "if the profileInfo.email attribute is empty, print out 'no email listed', but if it's not empty, then print out the value.

Note: To see the remaining html pages, please visit the Github repository. I've omitted them here because most of the Thymeleaf tags we've discussed here are also the same ones we've used on those pages.

login.html
This is the login page. We've shown it here because this is used by Spring Security for rendering the login page.



For more info, please see Spring Security 3.1 - Implement UserDetailsService with Spring Data JPA tutorial.

Next

In the next section, we will focus on the Domain, Repository, Service, and Controller classes Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring Social with JavaConfig (Part 6) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring Social with JavaConfig (Part 7)

Review

In the previous section, we have discussed the View layer along with Thymeleaf. In this section, we will focus on the Domain, Repository, Service, and Controller classes.

Table of Contents

Click on a link to jump to that section:
  1. Functional Specs
  2. Generate OAuth keys
    • Facebook
    • Twitter
  3. Spring Social configuration
  4. Spring Security configuration
  5. JavaConfig
    • ApplicationInitializer.java
    • ApplicationContext.java
    • DataConfig.java
    • ThymeleafConfig.java
    • spring.properties
  6. View with Thymeleaf
  7. Layers
    • Domain
    • Repository
    • Service
    • Controller
  8. Running the application
    • Clone from GitHub
    • Create the Database
    • Run with Maven and Tomcat 7
    • Run with Maven and Jetty 8
    • Import to Eclipse
    • Validate with W3C

Layers

Domain


Our domain layer consists of two simple classes: User.java and Role.java. By annotating these classes with @Entity we're declaring these classes as JPA entities and consequently will be persisted to a database.

The User class contains the following properties: first name, last name, username, role, and password. For the Role class, we only have two values: an admin and a regular user.





Although this is not part of the domain layer, we've included the UserDto here. This DTO is used for transferring user information to the view layer.



Controller


We have five controllers:
  • AccessController is responsible for managing login and signup requests
  • FacebookController is responsible for handling Facebook requests
  • TwitterController is responsible for handling Twitter requests
  • UserController is responsible for handling User CRUD operations
  • MediatorController simply handles call to the root page

AccessController.java


FacebookController.java


MediatorController.java


TwitterController.java


UserController.java


Repository


We have a simple repository. There's nothing much to explain here.

UserRepository.java


Service


We have two services:
  • UserService is used for handling user-related CRUD operations
  • RepositoryBasedUserDetailsService is used for retrieving user details for authentication purposes

UserService.java


RepositoryBasedUserDetailsService.java

Next

In the next section, we will study how to build and run our application. We will use Maven, Tomcat, and Jetty to run the app. We'll also study how to import the project in Eclipse. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring Social with JavaConfig (Part 7) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share