Chapter 3. From Prototype to Production

If you’ve got this far, then you already have a working application with a working entity model as well as a powerful, tried and true web framework. You’ve got everything you need to take your application well past the prototype stages and develop it into a viable, production worthy application. The devil, as they say, is in the details. But fear not, Spring Roo can make short work of these tedious, but important, tasks.

In this chapter, we’ll look at testing, securing and logging.

Logging

Logging is an integral part of your application. It provides the normative connection between your application and the rest of the world, during debugging, in testing, and in production. Logging should be integrated as frequently as possible. Spring Roo comes with the Log4j dependency already enabled. With one command you can install a Log4j configuration file, log4j.properties.

logging setup --level INFO

would for sample install a configuration file setup to handle logging at the INFO debug level.

Security

Ben Alex, the creator of both the Spring Security project and of Spring Roo, joked famously about the progression of the configuration required to add Spring Security configuration to a Spring application. In earlier versions of SPring Security—which was released as Acegi Security in 2003—the configuration could be quite burdensome. Today, Spring Security provides a XML namespace as well as intelligent configuration options and factory beans, making its installation a trivial matter. However, it can be simpler. As Ben would note, Spring Roo reduces the required configuration to one, solitary line.

Spring Security is widely considered the most powerful security framework available to Java developers. It has a lot of power, and can readily meet most security challenges. Spring Roo provides a sane way to get the basics taken care of, quickly. For our purposes, we simply want to secure our web application.

You must have configured a Spring MVC application, otherwise the security commands will not be available on the shell. To get started, type:

security setup

This command packs a lot of punch. It’s added the appropriate Spring Security Maven dependencies to the pom.xml file, it’s added a new Spring configuration file (src/main/resources/META-INF/spring/applicationContext-security.xml), it’s added a login.jspx page, and a new Tiles definition (view.xml). It’s also added the Spring Security servlet to web.xml, and configured extra URL protection in webmvc-config.xml.

The salient configuration lives in the applicationContext-security.xml, presented below.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <!-- HTTP security configurations -->
    <http auto-config="true" use-expressions="true">
        <form-login login-processing-url="/resources/j_spring_security_check" login-page="/login" authentication-failure-url="/login?login_error=t"/>
        <logout logout-url="/resources/j_spring_security_logout"/>
        <!-- Configure these elements to secure URIs in your application -->
        <intercept-url pattern="/choices/**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="/member/**" access="isAuthenticated()" />
        <intercept-url pattern="/resources/**" access="permitAll" />
        <intercept-url pattern="/**" access="permitAll" />
    </http>

    <!-- Configure Authentication mechanism -->
    <authentication-manager alias="authenticationManager">
        <!-- SHA-256 values can be produced using 'echo -n your_desired_password | sha256sum' (using normal *nix environments) -->
        <authentication-provider>
            <password-encoder hash="sha-256"/>
            <user-service>
                <user name="admin" password="8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918" authorities="ROLE_ADMIN"/>
                <user name="user" password="04f8996da763b7a969b1028ee3007569eaf3a635486ddab211d512c85b9df8fb" authorities="ROLE_USER"/>
            </user-service>
        </authentication-provider>

    </authentication-manager>
</beans:beans>

The http element describes which roles may access which URLs. The access attribute on the intercept-url elements uses Spring Expression Language statements to specify which tests to run when unauthorized access is requested. Questions about the qualifications of a request are delegated to an authentication-manager, which you can see configured below. Like all things in Spring, the authentication-manager is pluggable through an SPI. For the common cases, the namespace provides help. You can, for example, configure authentication against a database, or a single-sign on system like CAS, or OpenSSO.

Once this configuration is in place, you can more granularly restrict access to specific fragments of pages. For example, you might wish to restrict which menu options are shown to people in the menu. Open up the menu.jspx page, and then add the JSP tag namespace for the Spring Security tag.

 xmlns:sec="http://www.springframework.org/security/tags"

For the specific parts of the page that you wish to restrict, enclose it with this new tag, like this:

<sec:authorize ifAllGranted="ROLE_ADMIN">
 ...
</sec:authorize>

With these simple changes, we’ve already introduced URL-security, login managment, and page-fragment security. A full introduction to Spring Security is out of the scope of this book, but you might consider consulting the excellent Spring Security documentation at http://static.springsource.org/spring-security/site/index.html, or the excellent PACKT book, Spring Security 3.

Testing

We’ve gotten very far, very quickly, because we’ve relied on Spring Roo to do the right thing (TM). Since it does, unfailingly, we haven’t had to worry about testing, thus far. But Spring Roo is very amenable to testing, it encourages it. Spring Roo fully supports round tripping and wants to make it as easy as possible to support testing code so that—as we introduce code that varies from the script, so to speak, we don’t risk introducing errors.

When creating entities, you can eaisly add integration tests for the created entities by appending the --testAutomatically to the command, like this:

entity --class ~.domain.Customer --testAutomatically

You can add the integration tests retroactively, too, if you forget to specify this option at creation time or you had the classes generated using database reverse engineering.

test integration --entity ~.domain.Customer

This will generate an integration test (src/test/java/com/crmco/crm/domain/CustomerIntegrationTest.java). This integration test is a standard unit test. There’s an adjacent unit test aspect, CustomerIntegrationTest_Roo_IntegrationTest, that contains unit tests for all the properties on the entity, as well as the finder methods.

You can easily generate unit tests for all the other entities. You can run the unit tests in SpringSource Tool Suite by right clicking on the unit test and selecting Run As > JUnit Test. When you build the code on the command line using Maven, the unit tests will be run automatically.

Integration tests are the most typical type of unit test, but not the only one. Roo also supports mock tests, as well as interaction testing with Selenium.

Mock testing describes the practice—nay, the art—of testing interactions between APIs by delegating API calls to dumb objects that record the interactions and check that they meet test expectations. You can create simple mock test, quickly, like this:

test mock

This will create a single mock test, which you can then build on.

Interface testing—the final frontier in unit testing—is one of the hardest types of testing to get right, and also one of the most worthwhile because the user interface layer in an application can be host to a lot of complex state management. A user interface also has a lot of logic that is business critical, and that is not served by traditional unit tests. Interface tests provide an effective way to test this logic by simulating user interactions and measuring that the behavior of the user interface is in accordance with the expected behavior.

There are several projects that provide support for these kinds of tests, including HttpUnit, HtmlUnit, and Selenium. The first two frameworks simulate requests against a web application in terms of HTTP requests (very low level) and in terms of manipulation of a web page’s document object model (mouse clicks, button presses, etc.). While HtmlUnit has a lot of potential, it is ultimately a Java simulation of the browser, not the browser itself. Selenium is different. Selenium works as a plugin in the various browsers and then surfaces a sophisticated API to “drive” the browser using those plugins. It should not be surprising then that Spring Roo makes it very simple to build Selenium tests.

Roo can generate your Selenium test for any controller, like this:

selenium test --controller ~.web.CustomerController

This modifies the Maven configuration for the project and installs support for the Maven plugin:

<plugin>
     <groupId>org.codehaus.mojo</groupId>
     <artifactId>selenium-maven-plugin</artifactId>
     <version>1.1</version>
     <configuration>
          <suite>src/main/webapp/selenium/test-suite.xhtml</suite>
          <browser>*firefox</browser>
          <results>${project.build.directory}/selenium.html</results>
         <startURL>http://localhost:4444/</startURL>
     </configuration>
</plugin>

This will generate tests for the controller in the src/main/webapp/selenium folder. You can run these tests through Maven using the following command:

mvn selenium:selenese

This will launch Firefox and run the tests for you.

Conclusion

Well, that brings us to the end of our hopping tour of Spring Roo. In the span of the wafer thin tome you hold in your hands, we’ve covered setting up a Spring application and working Maven build, addressing database persistence with JPA and Neo4j, building web applications using—among other things—Spring MVC, Spring WebFlow, GWT, and Vaadin, securing an application and testing an application. Imagine what we could do if we had written another ten pages!

We hope you’ve enjoyed this little tour, but don’t worry—the fun doesn’t stop here. If you want to learn more, we encourage you to check out http://www.springsource.org/roo, where you’ll find all sorts of information including documentation, tutorials, screencasts and news. Spring Roo’s a quickly growing project, with new features added by the development team as well as the numerous third party contributors. If Spring Roo doesn’t already have a feature that you need, then check back tomorrow! If it hasn’t been addressed by then, then we encourage you to consult the forums as well as the JIRA for the project. The Roo team heavily prioritizes community feedback in deciding what to add next and always welcomes feedback.

Finally, if you want to learn more about the many individual technologies we’ve discussed in this book, hop on over to the SpringSource web site (http://www.springsource.org). SpringSource also has a YouTube channel, at http://www.youtube.com/SpringSourceDev.

Finally, you can find your humble authors on Twitter! Follow @SpringSource, @starbuxman, and @smayzak.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.191.134